blob: d93b9e5caae29c0545898a5df825b0990e644444 [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 Chowdhary13f9b2f2020-12-02 22:46:15 -080063#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070064#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070065#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080066
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080067#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080068#include <tuple>
69
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080070using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080071using namespace android::hardware::camera;
72using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080073using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080074
75namespace android {
76
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080077Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080078 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080079 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070080 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070081 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070082 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070083 mUsePartialResult(false),
84 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080085 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070086 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070087 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070088 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070090 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000092 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010093 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070094 mLastTemplateId(-1),
95 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080096{
97 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080098 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099}
100
101Camera3Device::~Camera3Device()
102{
103 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700105 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800106}
107
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800109 return mId;
110}
111
Emilian Peevbd8c5032018-02-14 23:05:40 +0000112status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800113 ATRACE_CALL();
114 Mutex::Autolock il(mInterfaceLock);
115 Mutex::Autolock l(mLock);
116
117 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
118 if (mStatus != STATUS_UNINITIALIZED) {
119 CLOGE("Already initialized!");
120 return INVALID_OPERATION;
121 }
122 if (manager == nullptr) return INVALID_OPERATION;
123
124 sp<ICameraDeviceSession> session;
125 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800126 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800127 /*out*/ &session);
128 ATRACE_END();
129 if (res != OK) {
130 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
131 return res;
132 }
133
Steven Moreland5ff9c912017-03-09 23:13:00 -0800134 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800135 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700136 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800137 session->close();
138 return res;
139 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800140 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800141
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700143 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 if (isLogical) {
145 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700146 res = manager->getCameraCharacteristics(
147 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700148 if (res != OK) {
149 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
150 physicalId.c_str(), strerror(-res), res);
151 session->close();
152 return res;
153 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700154
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800155 bool usePrecorrectArray =
156 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
157 if (usePrecorrectArray) {
158 res = mDistortionMappers[physicalId].setupStaticInfo(
159 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700160 if (res != OK) {
161 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
162 "correction", physicalId.c_str());
163 session->close();
164 return res;
165 }
166 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800167
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800168 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800169 &mPhysicalDeviceInfoMap[physicalId],
170 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700171 }
172 }
173
Yifan Hongf79b5542017-04-11 14:44:25 -0700174 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700175 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
176 [&queue](const auto& descriptor) {
177 queue = std::make_shared<RequestMetadataQueue>(descriptor);
178 if (!queue->isValid() || queue->availableToWrite() <= 0) {
179 ALOGE("HAL returns empty request metadata fmq, not use it");
180 queue = nullptr;
181 // don't use the queue onwards.
182 }
183 });
184 if (!requestQueueRet.isOk()) {
185 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
186 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700187 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700188 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700189
190 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192 [&resQueue](const auto& descriptor) {
193 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
194 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700195 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700196 resQueue = nullptr;
197 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700198 }
199 });
200 if (!resultQueueRet.isOk()) {
201 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
202 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700203 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700204 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700205 IF_ALOGV() {
206 session->interfaceChain([](
207 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
208 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800209 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700210 ALOGV(" %s", iface.c_str());
211 }
212 });
213 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700214
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800215 camera_metadata_entry bufMgrMode =
216 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
217 if (bufMgrMode.count > 0) {
218 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
219 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
220 }
221
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700222 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
223 for (size_t i = 0; i < capabilities.count; i++) {
224 uint8_t capability = capabilities.data.u8[i];
225 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
226 mSupportOfflineProcessing = true;
227 }
228 }
229
230 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000231 std::string providerType;
232 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000233 mTagMonitor.initialize(mVendorTagId);
234 if (!monitorTags.isEmpty()) {
235 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
236 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800237
Shuzhen Wang268a1362018-10-16 16:32:59 -0700238 // Metadata tags needs fixup for monochrome camera device version less
239 // than 3.5.
240 hardware::hidl_version maxVersion{0,0};
241 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
242 if (res != OK) {
243 ALOGE("%s: Error in getting camera device version id: %s (%d)",
244 __FUNCTION__, strerror(-res), res);
245 return res;
246 }
247 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
248 maxVersion.get_major(), maxVersion.get_minor());
249
250 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700251 for (size_t i = 0; i < capabilities.count; i++) {
252 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700253 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
254 isMonochrome = true;
255 }
256 }
257 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
258
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800259 return initializeCommonLocked();
260}
261
262status_t Camera3Device::initializeCommonLocked() {
263
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 /** Start up status tracker thread */
265 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 if (res != OK) {
268 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
269 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800270 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700271 mStatusTracker.clear();
272 return res;
273 }
274
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700275 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700276 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700277
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700278 if (mUseHalBufManager) {
279 res = mRequestBufferSM.initialize(mStatusTracker);
280 if (res != OK) {
281 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
282 strerror(-res), res);
283 mInterface->close();
284 mStatusTracker.clear();
285 return res;
286 }
287 }
288
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800289 /** Create buffer manager */
290 mBufferManager = new Camera3BufferManager();
291
292 Vector<int32_t> sessionParamKeys;
293 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
294 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
295 if (sessionKeysEntry.count > 0) {
296 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
297 }
298
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700299 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700300 mRequestThread = new RequestThread(
301 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800302 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800303 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700304 SET_ERR_L("Unable to start request queue thread: %s (%d)",
305 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800306 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800307 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800308 return res;
309 }
310
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700311 mPreparerThread = new PreparerThread();
312
Ruben Brunk183f0562015-08-12 12:55:02 -0700313 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800314 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400315 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700316 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800318 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800319
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800320 // Measure the clock domain offset between camera and video/hw_composer
321 camera_metadata_entry timestampSource =
322 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
323 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
324 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
325 mTimestampOffset = getMonoToBoottimeOffset();
326 }
327
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700328 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100329 camera_metadata_entry partialResultsCount =
330 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
331 if (partialResultsCount.count > 0) {
332 mNumPartialResults = partialResultsCount.data.i32[0];
333 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700334 }
335
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800336 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
337 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700338 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700339 if (res != OK) {
340 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
341 return res;
342 }
343 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800345 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800346 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800348 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
349 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
350 }
351
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800352 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
353 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
354 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
355 if (availableTestPatternModes.data.i32[i] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
356 mSupportCameraMute = true;
357 break;
358 }
359 }
360
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800361 return OK;
362}
363
364status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700365 return disconnectImpl();
366}
367
368status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800369 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700370 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800371
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700372 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700373 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700374 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800375 Mutex::Autolock il(mInterfaceLock);
376 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
377 {
378 Mutex::Autolock l(mLock);
379 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800381 if (mStatus == STATUS_ACTIVE ||
382 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
383 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800385 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700386 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800387 } else {
388 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
389 if (res != OK) {
390 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
391 maxExpectedDuration);
392 // Continue to close device even in case of error
393 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700394 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700395 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800396
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800397 if (mStatus == STATUS_ERROR) {
398 CLOGE("Shutting down in an error state");
399 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700400
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800401 if (mStatusTracker != NULL) {
402 mStatusTracker->requestExit();
403 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700404
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800405 if (mRequestThread != NULL) {
406 mRequestThread->requestExit();
407 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800409 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
410 for (size_t i = 0; i < mOutputStreams.size(); i++) {
411 streams.push_back(mOutputStreams[i]);
412 }
413 if (mInputStream != nullptr) {
414 streams.push_back(mInputStream);
415 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700416 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800418 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
419 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700420 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
421 // HAL may be in a bad state, so waiting for request thread
422 // (which may be stuck in the HAL processCaptureRequest call)
423 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800424 // give up mInterfaceLock here and then lock it again. Could this lead
425 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 mRequestThread->join();
427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 Mutex::Autolock il(mInterfaceLock);
430 if (mStatusTracker != NULL) {
431 mStatusTracker->join();
432 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800433
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800434 HalInterface* interface;
435 {
436 Mutex::Autolock l(mLock);
437 mRequestThread.clear();
438 Mutex::Autolock stLock(mTrackerLock);
439 mStatusTracker.clear();
440 interface = mInterface.get();
441 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700442
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800443 // Call close without internal mutex held, as the HAL close may need to
444 // wait on assorted callbacks,etc, to complete before it can return.
445 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700446
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800447 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800448
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 {
450 Mutex::Autolock l(mLock);
451 mInterface->clear();
452 mOutputStreams.clear();
453 mInputStream.clear();
454 mDeletedStreams.clear();
455 mBufferManager.clear();
456 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
457 }
458
459 for (auto& weakStream : streams) {
460 sp<Camera3StreamInterface> stream = weakStream.promote();
461 if (stream != nullptr) {
462 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
463 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
464 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700465 }
466 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700467 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700468 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800469}
470
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700471// For dumping/debugging only -
472// try to acquire a lock a few times, eventually give up to proceed with
473// debug/dump operations
474bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
475 bool gotLock = false;
476 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
477 if (lock.tryLock() == NO_ERROR) {
478 gotLock = true;
479 break;
480 } else {
481 usleep(kDumpSleepDuration);
482 }
483 }
484 return gotLock;
485}
486
Shuzhen Wang83bff122020-11-20 15:51:39 -0800487camera3::Size Camera3Device::getMaxJpegResolution() const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700488 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100489 const int STREAM_CONFIGURATION_SIZE = 4;
490 const int STREAM_FORMAT_OFFSET = 0;
491 const int STREAM_WIDTH_OFFSET = 1;
492 const int STREAM_HEIGHT_OFFSET = 2;
493 const int STREAM_IS_INPUT_OFFSET = 3;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800494 bool isHighResolutionSensor =
495 camera3::SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo);
496 int32_t scalerSizesTag = isHighResolutionSensor ?
497 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_MAXIMUM_RESOLUTION :
498 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
Emilian Peev08dd2452017-04-06 16:55:14 +0100499 camera_metadata_ro_entry_t availableStreamConfigs =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800500 mDeviceInfo.find(scalerSizesTag);
Emilian Peev08dd2452017-04-06 16:55:14 +0100501 if (availableStreamConfigs.count == 0 ||
502 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800503 return camera3::Size(0, 0);
Emilian Peev08dd2452017-04-06 16:55:14 +0100504 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700505
Emilian Peev08dd2452017-04-06 16:55:14 +0100506 // Get max jpeg size (area-wise).
507 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
508 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
509 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
510 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
511 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
512 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
513 && format == HAL_PIXEL_FORMAT_BLOB &&
514 (width * height > maxJpegWidth * maxJpegHeight)) {
515 maxJpegWidth = width;
516 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700517 }
518 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100519
Shuzhen Wang83bff122020-11-20 15:51:39 -0800520 return camera3::Size(maxJpegWidth, maxJpegHeight);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700521}
522
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800523nsecs_t Camera3Device::getMonoToBoottimeOffset() {
524 // try three times to get the clock offset, choose the one
525 // with the minimum gap in measurements.
526 const int tries = 3;
527 nsecs_t bestGap, measured;
528 for (int i = 0; i < tries; ++i) {
529 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
530 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
531 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
532 const nsecs_t gap = tmono2 - tmono;
533 if (i == 0 || gap < bestGap) {
534 bestGap = gap;
535 measured = tbase - ((tmono + tmono2) >> 1);
536 }
537 }
538 return measured;
539}
540
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800541hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
542 int frameworkFormat) {
543 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
544}
545
546DataspaceFlags Camera3Device::mapToHidlDataspace(
547 android_dataspace dataSpace) {
548 return dataSpace;
549}
550
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700551BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100552 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700553 return usage;
554}
555
Emilian Peevf4816702020-04-03 15:44:51 -0700556StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700558 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800559 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700560 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800561 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700562 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800563 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700564 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800565 return StreamRotation::ROTATION_270;
566 }
567 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
568 return StreamRotation::ROTATION_0;
569}
570
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800571status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700572 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700574 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800575 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700576 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800577 *mode = StreamConfigurationMode::NORMAL_MODE;
578 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700579 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800580 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
581 break;
582 default:
583 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
584 return BAD_VALUE;
585 }
586 } else {
587 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800588 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800589 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800590}
591
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800592int Camera3Device::mapToFrameworkFormat(
593 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
594 return static_cast<uint32_t>(pixelFormat);
595}
596
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700597android_dataspace Camera3Device::mapToFrameworkDataspace(
598 DataspaceFlags dataSpace) {
599 return static_cast<android_dataspace>(dataSpace);
600}
601
Emilian Peev050f5dc2017-05-18 14:43:56 +0100602uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700603 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700604 return usage;
605}
606
Emilian Peev050f5dc2017-05-18 14:43:56 +0100607uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700608 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700609 return usage;
610}
611
Zhijun Hef7da0962014-04-24 13:27:56 -0700612ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700613 // Get max jpeg size (area-wise).
Shuzhen Wang83bff122020-11-20 15:51:39 -0800614 camera3::Size maxJpegResolution = getMaxJpegResolution();
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700615 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
617 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700618 return BAD_VALUE;
619 }
620
Zhijun Hef7da0962014-04-24 13:27:56 -0700621 // Get max jpeg buffer size
622 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700623 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
624 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
626 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700627 return BAD_VALUE;
628 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700629 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800630 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700631
632 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700633 float scaleFactor = ((float) (width * height)) /
634 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800635 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
636 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700637 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800638 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
639 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700640 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700641 }
642
643 return jpegBufferSize;
644}
645
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700646ssize_t Camera3Device::getPointCloudBufferSize() const {
647 const int FLOATS_PER_POINT=4;
648 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
649 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
651 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700652 return BAD_VALUE;
653 }
654 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
655 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
656 return maxBytesForPointCloud;
657}
658
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800659ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
660 bool maxResolution) 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 =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800666 mDeviceInfo.find(
667 camera3::SessionConfigurationUtils::getAppropriateModeTag(
668 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
669 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800670 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800671 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
673 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 return BAD_VALUE;
675 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700676
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800677 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
678 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
679 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
680 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
681 }
682 }
683
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800684 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
685 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800686 return BAD_VALUE;
687}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700688
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800689status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
690 ATRACE_CALL();
691 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700692
693 // Try to lock, but continue in case of failure (to avoid blocking in
694 // deadlocks)
695 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
696 bool gotLock = tryLockSpinRightRound(mLock);
697
698 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
700 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700701 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800702 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
703 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700704
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800705 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700706
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800707 String16 templatesOption("-t");
708 int n = args.size();
709 for (int i = 0; i < n; i++) {
710 if (args[i] == templatesOption) {
711 dumpTemplates = true;
712 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000713 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700714 if (i + 1 < n) {
715 String8 monitorTags = String8(args[i + 1]);
716 if (monitorTags == "off") {
717 mTagMonitor.disableMonitoring();
718 } else {
719 mTagMonitor.parseTagsToMonitor(monitorTags);
720 }
721 } else {
722 mTagMonitor.disableMonitoring();
723 }
724 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800725 }
726
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800728
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800729 const char *status =
730 mStatus == STATUS_ERROR ? "ERROR" :
731 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700732 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
733 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734 mStatus == STATUS_ACTIVE ? "ACTIVE" :
735 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700736
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800737 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700738 if (mStatus == STATUS_ERROR) {
739 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
740 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800742 const char *mode =
743 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
744 mOperatingMode == static_cast<int>(
745 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
746 "CUSTOM";
747 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800748
749 if (mInputStream != NULL) {
750 write(fd, lines.string(), lines.size());
751 mInputStream->dump(fd, args);
752 } else {
753 lines.appendFormat(" No input stream.\n");
754 write(fd, lines.string(), lines.size());
755 }
756 for (size_t i = 0; i < mOutputStreams.size(); i++) {
757 mOutputStreams[i]->dump(fd,args);
758 }
759
Zhijun He431503c2016-03-07 17:30:16 -0800760 if (mBufferManager != NULL) {
761 lines = String8(" Camera3 Buffer Manager:\n");
762 write(fd, lines.string(), lines.size());
763 mBufferManager->dump(fd, args);
764 }
Zhijun He125684a2015-12-26 15:07:30 -0800765
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700766 lines = String8(" In-flight requests:\n");
767 if (mInFlightMap.size() == 0) {
768 lines.append(" None\n");
769 } else {
770 for (size_t i = 0; i < mInFlightMap.size(); i++) {
771 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700772 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000773 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800774 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000775 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700776 }
777 }
778 write(fd, lines.string(), lines.size());
779
Shuzhen Wang686f6442017-06-20 16:16:04 -0700780 if (mRequestThread != NULL) {
781 mRequestThread->dumpCaptureRequestLatency(fd,
782 " ProcessCaptureRequest latency histogram:");
783 }
784
Igor Murashkin1e479c02013-09-06 16:55:14 -0700785 {
786 lines = String8(" Last request sent:\n");
787 write(fd, lines.string(), lines.size());
788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700789 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700790 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
791 }
792
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800793 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700794 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 "TEMPLATE_PREVIEW",
796 "TEMPLATE_STILL_CAPTURE",
797 "TEMPLATE_VIDEO_RECORD",
798 "TEMPLATE_VIDEO_SNAPSHOT",
799 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800800 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800801 };
802
Emilian Peevf4816702020-04-03 15:44:51 -0700803 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800804 camera_metadata_t *templateRequest = nullptr;
805 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700806 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800807 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800808 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800809 lines.append(" Not supported\n");
810 write(fd, lines.string(), lines.size());
811 } else {
812 write(fd, lines.string(), lines.size());
813 dump_indented_camera_metadata(templateRequest,
814 fd, /*verbosity*/2, /*indentation*/8);
815 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800816 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800817 }
818 }
819
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700820 mTagMonitor.dumpMonitoredMetadata(fd);
821
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800823 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800824 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800825 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800826 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800827
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700828 if (gotLock) mLock.unlock();
829 if (gotInterfaceLock) mInterfaceLock.unlock();
830
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 return OK;
832}
833
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800834const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800835 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800836 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
837 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700838 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839 mStatus == STATUS_ERROR ?
840 "when in error state" : "before init");
841 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700842 if (physicalId.isEmpty()) {
843 return mDeviceInfo;
844 } else {
845 std::string id(physicalId.c_str());
846 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
847 return mPhysicalDeviceInfoMap.at(id);
848 } else {
849 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
850 return mDeviceInfo;
851 }
852 }
853}
854
855const CameraMetadata& Camera3Device::info() const {
856 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800857 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800858}
859
Jianing Wei90e59c92014-03-12 18:29:36 -0700860status_t Camera3Device::checkStatusOkToCaptureLocked() {
861 switch (mStatus) {
862 case STATUS_ERROR:
863 CLOGE("Device has encountered a serious error");
864 return INVALID_OPERATION;
865 case STATUS_UNINITIALIZED:
866 CLOGE("Device not initialized");
867 return INVALID_OPERATION;
868 case STATUS_UNCONFIGURED:
869 case STATUS_CONFIGURED:
870 case STATUS_ACTIVE:
871 // OK
872 break;
873 default:
874 SET_ERR_L("Unexpected status: %d", mStatus);
875 return INVALID_OPERATION;
876 }
877 return OK;
878}
879
880status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000881 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700882 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700883 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700884 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 if (requestList == NULL) {
886 CLOGE("requestList cannot be NULL.");
887 return BAD_VALUE;
888 }
889
Jianing Weicb0652e2014-03-12 18:29:36 -0700890 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000891 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
893 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
894 ++metadataIt, ++surfaceMapIt) {
895 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700896 if (newRequest == 0) {
897 CLOGE("Can't create capture request");
898 return BAD_VALUE;
899 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700900
Shuzhen Wang9d066012016-09-30 11:30:20 -0700901 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700902 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700903
Jianing Weicb0652e2014-03-12 18:29:36 -0700904 // Setup burst Id and request Id
905 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800906 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
907 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700908 CLOGE("RequestID does not exist in metadata");
909 return BAD_VALUE;
910 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800911 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700912
Jianing Wei90e59c92014-03-12 18:29:36 -0700913 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700914
915 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700916 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
918 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
919 return BAD_VALUE;
920 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700921
922 // Setup batch size if this is a high speed video recording request.
923 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
924 auto firstRequest = requestList->begin();
925 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
926 if (outputStream->isVideoStream()) {
927 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800928 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700929 break;
930 }
931 }
932 }
933
Jianing Wei90e59c92014-03-12 18:29:36 -0700934 return OK;
935}
936
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800937status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800938 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800939
Emilian Peevaebbe412018-01-15 13:53:24 +0000940 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700941 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000942 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700943
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800944 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700945}
946
Emilian Peevaebbe412018-01-15 13:53:24 +0000947void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700948 std::list<const SurfaceMap>& surfaceMaps,
949 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000950 PhysicalCameraSettingsList requestList;
951 requestList.push_back({std::string(getId().string()), request});
952 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953
954 SurfaceMap surfaceMap;
955 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
956 // With no surface list passed in, stream and surface will have 1-to-1
957 // mapping. So the surface index is 0 for each stream in the surfaceMap.
958 for (size_t i = 0; i < streams.count; i++) {
959 surfaceMap[streams.data.i32[i]].push_back(0);
960 }
961 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800962}
963
Jianing Wei90e59c92014-03-12 18:29:36 -0700964status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000965 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700966 const std::list<const SurfaceMap> &surfaceMaps,
967 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700968 /*out*/
969 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700970 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700971 nsecs_t requestTimeNs = systemTime();
972
Jianing Wei90e59c92014-03-12 18:29:36 -0700973 Mutex::Autolock il(mInterfaceLock);
974 Mutex::Autolock l(mLock);
975
976 status_t res = checkStatusOkToCaptureLocked();
977 if (res != OK) {
978 // error logged by previous call
979 return res;
980 }
981
982 RequestList requestList;
983
Shuzhen Wang0129d522016-10-30 22:43:41 -0700984 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700985 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700986 if (res != OK) {
987 // error logged by previous call
988 return res;
989 }
990
991 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700992 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700994 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700995 }
996
997 if (res == OK) {
998 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
999 if (res != OK) {
1000 SET_ERR_L("Can't transition to active in %f seconds!",
1001 kActiveTimeout/1e9);
1002 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001003 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001004 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001005 } else {
1006 CLOGE("Cannot queue request. Impossible.");
1007 return BAD_VALUE;
1008 }
1009
1010 return res;
1011}
1012
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001013hardware::Return<void> Camera3Device::requestStreamBuffers(
1014 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1015 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001016 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001017 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001018 *this, *mInterface, *this};
1019 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001020 return hardware::Void();
1021}
1022
1023hardware::Return<void> Camera3Device::returnStreamBuffers(
1024 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001025 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001026 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001027 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001028 return hardware::Void();
1029}
1030
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001031hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001032 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001033 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001034 // Ideally we should grab mLock, but that can lead to deadlock, and
1035 // it's not super important to get up to date value of mStatus for this
1036 // warning print, hence skipping the lock here
1037 if (mStatus == STATUS_ERROR) {
1038 // Per API contract, HAL should act as closed after device error
1039 // But mStatus can be set to error by framework as well, so just log
1040 // a warning here.
1041 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001042 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 sp<NotificationListener> listener;
1045 {
1046 std::lock_guard<std::mutex> l(mOutputLock);
1047 listener = mListener.promote();
1048 }
1049
Yifan Honga640c5a2017-04-12 16:30:31 -07001050 if (mProcessCaptureResultLock.tryLock() != OK) {
1051 // This should never happen; it indicates a wrong client implementation
1052 // that doesn't follow the contract. But, we can be tolerant here.
1053 ALOGE("%s: callback overlapped! waiting 1s...",
1054 __FUNCTION__);
1055 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1056 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1057 __FUNCTION__);
1058 // really don't know what to do, so bail out.
1059 return hardware::Void();
1060 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001061 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001062 CaptureOutputStates states {
1063 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001064 mInFlightLock, mLastCompletedRegularFrameNumber,
1065 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1066 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001067 mNextShutterFrameNumber,
1068 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1069 mNextResultFrameNumber,
1070 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1071 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1072 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001073 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001074 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1075 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001076 };
1077
Yifan Honga640c5a2017-04-12 16:30:31 -07001078 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001079 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001080 }
1081 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001082 return hardware::Void();
1083}
1084
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001085// Only one processCaptureResult should be called at a time, so
1086// the locks won't block. The locks are present here simply to enforce this.
1087hardware::Return<void> Camera3Device::processCaptureResult(
1088 const hardware::hidl_vec<
1089 hardware::camera::device::V3_2::CaptureResult>& results) {
1090 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1091
1092 // Ideally we should grab mLock, but that can lead to deadlock, and
1093 // it's not super important to get up to date value of mStatus for this
1094 // warning print, hence skipping the lock here
1095 if (mStatus == STATUS_ERROR) {
1096 // Per API contract, HAL should act as closed after device error
1097 // But mStatus can be set to error by framework as well, so just log
1098 // a warning here.
1099 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1100 }
1101
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001102 sp<NotificationListener> listener;
1103 {
1104 std::lock_guard<std::mutex> l(mOutputLock);
1105 listener = mListener.promote();
1106 }
1107
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001108 if (mProcessCaptureResultLock.tryLock() != OK) {
1109 // This should never happen; it indicates a wrong client implementation
1110 // that doesn't follow the contract. But, we can be tolerant here.
1111 ALOGE("%s: callback overlapped! waiting 1s...",
1112 __FUNCTION__);
1113 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1114 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1115 __FUNCTION__);
1116 // really don't know what to do, so bail out.
1117 return hardware::Void();
1118 }
1119 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001120
1121 CaptureOutputStates states {
1122 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001123 mInFlightLock, mLastCompletedRegularFrameNumber,
1124 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1125 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001126 mNextShutterFrameNumber,
1127 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1128 mNextResultFrameNumber,
1129 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1130 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1131 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001132 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001133 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1134 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001135 };
1136
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001137 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001138 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001139 }
1140 mProcessCaptureResultLock.unlock();
1141 return hardware::Void();
1142}
1143
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001144hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001145 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001146 // Ideally we should grab mLock, but that can lead to deadlock, and
1147 // it's not super important to get up to date value of mStatus for this
1148 // warning print, hence skipping the lock here
1149 if (mStatus == STATUS_ERROR) {
1150 // Per API contract, HAL should act as closed after device error
1151 // But mStatus can be set to error by framework as well, so just log
1152 // a warning here.
1153 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001154 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001155
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001156 sp<NotificationListener> listener;
1157 {
1158 std::lock_guard<std::mutex> l(mOutputLock);
1159 listener = mListener.promote();
1160 }
1161
1162 CaptureOutputStates states {
1163 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001164 mInFlightLock, mLastCompletedRegularFrameNumber,
1165 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1166 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001167 mNextShutterFrameNumber,
1168 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1169 mNextResultFrameNumber,
1170 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1171 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1172 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001173 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001174 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1175 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001176 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001177 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001178 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001179 }
1180 return hardware::Void();
1181}
1182
Emilian Peevaebbe412018-01-15 13:53:24 +00001183status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001184 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001185 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001186 ATRACE_CALL();
1187
Emilian Peevaebbe412018-01-15 13:53:24 +00001188 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001189}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001190
Jianing Weicb0652e2014-03-12 18:29:36 -07001191status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1192 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001193 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001196 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001197 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001198
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001200 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201}
1202
Emilian Peevaebbe412018-01-15 13:53:24 +00001203status_t Camera3Device::setStreamingRequestList(
1204 const List<const PhysicalCameraSettingsList> &requestsList,
1205 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001206 ATRACE_CALL();
1207
Emilian Peevaebbe412018-01-15 13:53:24 +00001208 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001209}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210
1211sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001212 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 status_t res;
1214
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001216 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1217 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001218 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001219 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001220 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001222 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001224 } else if (mStatus == STATUS_UNCONFIGURED) {
1225 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 CLOGE("No streams configured");
1227 return NULL;
1228 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 }
1230
Shuzhen Wang0129d522016-10-30 22:43:41 -07001231 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001233}
1234
Jianing Weicb0652e2014-03-12 18:29:36 -07001235status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001236 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001239
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 switch (mStatus) {
1241 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001242 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return INVALID_OPERATION;
1244 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001245 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001247 case STATUS_UNCONFIGURED:
1248 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 case STATUS_ACTIVE:
1250 // OK
1251 break;
1252 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001253 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 return INVALID_OPERATION;
1255 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001256 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001257
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001258 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259}
1260
1261status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1262 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001264
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001265 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001266}
1267
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001268status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001269 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001270 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001272 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001273 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001274 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1275 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276
1277 status_t res;
1278 bool wasActive = false;
1279
1280 switch (mStatus) {
1281 case STATUS_ERROR:
1282 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1283 return INVALID_OPERATION;
1284 case STATUS_UNINITIALIZED:
1285 ALOGE("%s: Device not initialized", __FUNCTION__);
1286 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 case STATUS_UNCONFIGURED:
1288 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 // OK
1290 break;
1291 case STATUS_ACTIVE:
1292 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001293 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001294 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001295 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001296 return res;
1297 }
1298 wasActive = true;
1299 break;
1300 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001302 return INVALID_OPERATION;
1303 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001304 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001305
1306 if (mInputStream != 0) {
1307 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1308 return INVALID_OPERATION;
1309 }
1310
1311 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1312 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001313 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314
1315 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001316 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317
1318 *id = mNextStreamId++;
1319
1320 // Continue captures if active at start
1321 if (wasActive) {
1322 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001323 // Reuse current operating mode and session parameters for new stream config
1324 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001325 if (res != OK) {
1326 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1327 __FUNCTION__, mNextStreamId, strerror(-res), res);
1328 return res;
1329 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001330 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001331 }
1332
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001333 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001334 return OK;
1335}
1336
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001337status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001338 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001339 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001340 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001341 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1342 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1343 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001344 ATRACE_CALL();
1345
1346 if (consumer == nullptr) {
1347 ALOGE("%s: consumer must not be null", __FUNCTION__);
1348 return BAD_VALUE;
1349 }
1350
1351 std::vector<sp<Surface>> consumers;
1352 consumers.push_back(consumer);
1353
1354 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001355 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1356 streamSetId, isShared, isMultiResolution, consumerUsage);
1357}
1358
1359static bool isRawFormat(int format) {
1360 switch (format) {
1361 case HAL_PIXEL_FORMAT_RAW16:
1362 case HAL_PIXEL_FORMAT_RAW12:
1363 case HAL_PIXEL_FORMAT_RAW10:
1364 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1365 return true;
1366 default:
1367 return false;
1368 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001369}
1370
1371status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1372 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001373 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001374 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001375 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1376 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001378
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001379 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001380 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001383 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1384 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1385 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001386
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 status_t res;
1388 bool wasActive = false;
1389
1390 switch (mStatus) {
1391 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001392 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 return INVALID_OPERATION;
1394 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001395 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001397 case STATUS_UNCONFIGURED:
1398 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 // OK
1400 break;
1401 case STATUS_ACTIVE:
1402 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001403 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001405 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return res;
1407 }
1408 wasActive = true;
1409 break;
1410 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001411 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return INVALID_OPERATION;
1413 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001414 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415
1416 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001417
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 if (consumers.size() == 0 && !hasDeferredConsumer) {
1419 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1420 return BAD_VALUE;
1421 }
Zhijun He5d677d12016-05-29 16:52:39 -07001422
Shuzhen Wang0129d522016-10-30 22:43:41 -07001423 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001424 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1425 return BAD_VALUE;
1426 }
1427
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001428 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1429 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1430 // be found in only one sensor pixel mode.
1431 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1432 return BAD_VALUE;
1433 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001435 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001436 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001437 blobBufferSize = getPointCloudBufferSize();
1438 if (blobBufferSize <= 0) {
1439 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1440 return BAD_VALUE;
1441 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001442 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1443 blobBufferSize = width * height;
1444 } else {
1445 blobBufferSize = getJpegBufferSize(width, height);
1446 if (blobBufferSize <= 0) {
1447 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1448 return BAD_VALUE;
1449 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001450 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001451 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001452 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001453 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1454 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001455 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001456 bool maxResolution =
1457 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1458 sensorPixelModesUsed.end();
1459 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001460 if (rawOpaqueBufferSize <= 0) {
1461 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1462 return BAD_VALUE;
1463 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001464 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001465 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001466 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1467 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001468 } else if (isShared) {
1469 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1470 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001471 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1472 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001473 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001474 newStream = new Camera3OutputStream(mNextStreamId,
1475 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001476 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1477 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001479 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001480 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001481 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1482 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 }
Emilian Peev40ead602017-09-26 15:46:36 +01001484
1485 size_t consumerCount = consumers.size();
1486 for (size_t i = 0; i < consumerCount; i++) {
1487 int id = newStream->getSurfaceId(consumers[i]);
1488 if (id < 0) {
1489 SET_ERR_L("Invalid surface id");
1490 return BAD_VALUE;
1491 }
1492 if (surfaceIds != nullptr) {
1493 surfaceIds->push_back(id);
1494 }
1495 }
1496
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498
Emilian Peev08dd2452017-04-06 16:55:14 +01001499 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001500
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001501 newStream->setImageDumpMask(mImageDumpMask);
1502
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 res = mOutputStreams.add(mNextStreamId, newStream);
1504 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001505 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 return res;
1507 }
1508
Shuzhen Wang316781a2020-08-18 18:11:01 -07001509 mSessionStatsBuilder.addStream(mNextStreamId);
1510
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001512 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513
1514 // Continue captures if active at start
1515 if (wasActive) {
1516 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001517 // Reuse current operating mode and session parameters for new stream config
1518 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1521 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return res;
1523 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001526 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001528}
1529
Emilian Peev710c1422017-08-30 11:19:38 +01001530status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001531 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001532 if (nullptr == streamInfo) {
1533 return BAD_VALUE;
1534 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001537
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 switch (mStatus) {
1539 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001540 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return INVALID_OPERATION;
1542 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001543 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 case STATUS_UNCONFIGURED:
1546 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 case STATUS_ACTIVE:
1548 // OK
1549 break;
1550 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001551 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return INVALID_OPERATION;
1553 }
1554
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001555 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1556 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001557 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001558 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 }
1560
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001561 streamInfo->width = stream->getWidth();
1562 streamInfo->height = stream->getHeight();
1563 streamInfo->format = stream->getFormat();
1564 streamInfo->dataSpace = stream->getDataSpace();
1565 streamInfo->formatOverridden = stream->isFormatOverridden();
1566 streamInfo->originalFormat = stream->getOriginalFormat();
1567 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1568 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001570}
1571
1572status_t Camera3Device::setStreamTransform(int id,
1573 int transform) {
1574 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001576 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 switch (mStatus) {
1579 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001580 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 return INVALID_OPERATION;
1582 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001583 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 case STATUS_UNCONFIGURED:
1586 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 case STATUS_ACTIVE:
1588 // OK
1589 break;
1590 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001591 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 return INVALID_OPERATION;
1593 }
1594
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001595 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1596 if (stream == nullptr) {
1597 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 return BAD_VALUE;
1599 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001600 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001601}
1602
1603status_t Camera3Device::deleteStream(int id) {
1604 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 Mutex::Autolock l(mLock);
1607 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001609 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001610
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001611 // CameraDevice semantics require device to already be idle before
1612 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001614 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001615 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 }
1617
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001618 if (mStatus == STATUS_ERROR) {
1619 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1620 __FUNCTION__, mId.string());
1621 return -EBUSY;
1622 }
1623
Igor Murashkin2fba5842013-04-22 14:03:54 -07001624 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001625 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 if (mInputStream != NULL && id == mInputStream->getId()) {
1627 deletedStream = mInputStream;
1628 mInputStream.clear();
1629 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001630 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001631 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 return BAD_VALUE;
1633 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001634 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001635 }
1636
1637 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001638 if (stream != nullptr) {
1639 deletedStream = stream;
1640 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001641 }
1642
1643 // Free up the stream endpoint so that it can be used by some other stream
1644 res = deletedStream->disconnect();
1645 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001646 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001647 // fall through since we want to still list the stream as deleted.
1648 }
1649 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001650 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001651
1652 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653}
1654
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001655status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001656 ATRACE_CALL();
1657 ALOGV("%s: E", __FUNCTION__);
1658
1659 Mutex::Autolock il(mInterfaceLock);
1660 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001661
Emilian Peev811d2952018-05-25 11:08:40 +01001662 // In case the client doesn't include any session parameter, try a
1663 // speculative configuration using the values from the last cached
1664 // default request.
1665 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001666 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001667 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1668 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1669 mLastTemplateId);
1670 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1671 operatingMode);
1672 }
1673
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001674 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1675}
1676
1677status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1678 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001679 //Filter out any incoming session parameters
1680 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001681 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1682 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001683 CameraMetadata filteredParams(availableSessionKeys.count);
1684 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1685 filteredParams.getAndLock());
1686 set_camera_metadata_vendor_id(meta, mVendorTagId);
1687 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001688 if (availableSessionKeys.count > 0) {
1689 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1690 camera_metadata_ro_entry entry = params.find(
1691 availableSessionKeys.data.i32[i]);
1692 if (entry.count > 0) {
1693 filteredParams.update(entry);
1694 }
1695 }
1696 }
1697
1698 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001699}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001701status_t Camera3Device::getInputBufferProducer(
1702 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001703 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001704 Mutex::Autolock il(mInterfaceLock);
1705 Mutex::Autolock l(mLock);
1706
1707 if (producer == NULL) {
1708 return BAD_VALUE;
1709 } else if (mInputStream == NULL) {
1710 return INVALID_OPERATION;
1711 }
1712
1713 return mInputStream->getInputBufferProducer(producer);
1714}
1715
Emilian Peevf4816702020-04-03 15:44:51 -07001716status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001717 CameraMetadata *request) {
1718 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001719 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001720
Emilian Peevf4816702020-04-03 15:44:51 -07001721 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001722 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001723 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001724 return BAD_VALUE;
1725 }
1726
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001728
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001729 {
1730 Mutex::Autolock l(mLock);
1731 switch (mStatus) {
1732 case STATUS_ERROR:
1733 CLOGE("Device has encountered a serious error");
1734 return INVALID_OPERATION;
1735 case STATUS_UNINITIALIZED:
1736 CLOGE("Device is not initialized!");
1737 return INVALID_OPERATION;
1738 case STATUS_UNCONFIGURED:
1739 case STATUS_CONFIGURED:
1740 case STATUS_ACTIVE:
1741 // OK
1742 break;
1743 default:
1744 SET_ERR_L("Unexpected status: %d", mStatus);
1745 return INVALID_OPERATION;
1746 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001747
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001748 if (!mRequestTemplateCache[templateId].isEmpty()) {
1749 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001750 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001751 return OK;
1752 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001753 }
1754
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001755 camera_metadata_t *rawRequest;
1756 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001757 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001758
1759 {
1760 Mutex::Autolock l(mLock);
1761 if (res == BAD_VALUE) {
1762 ALOGI("%s: template %d is not supported on this camera device",
1763 __FUNCTION__, templateId);
1764 return res;
1765 } else if (res != OK) {
1766 CLOGE("Unable to construct request template %d: %s (%d)",
1767 templateId, strerror(-res), res);
1768 return res;
1769 }
1770
1771 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1772 mRequestTemplateCache[templateId].acquire(rawRequest);
1773
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001774 // Override the template request with zoomRatioMapper
1775 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1776 &mRequestTemplateCache[templateId]);
1777 if (res != OK) {
1778 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1779 templateId, strerror(-res), res);
1780 return res;
1781 }
1782
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001783 // Fill in JPEG_QUALITY if not available
1784 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1785 static const uint8_t kDefaultJpegQuality = 95;
1786 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1787 &kDefaultJpegQuality, 1);
1788 }
1789
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001790 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001791 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001792 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001793 return OK;
1794}
1795
1796status_t Camera3Device::waitUntilDrained() {
1797 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001799 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001801
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001802 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001803}
1804
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001805status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001806 switch (mStatus) {
1807 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809 ALOGV("%s: Already idle", __FUNCTION__);
1810 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001811 case STATUS_CONFIGURED:
1812 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 case STATUS_ERROR:
1814 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 break;
1817 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001818 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819 return INVALID_OPERATION;
1820 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001821 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1822 maxExpectedDuration);
1823 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001824 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001825 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001826 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1827 res);
1828 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 return res;
1830}
1831
Ruben Brunk183f0562015-08-12 12:55:02 -07001832
1833void Camera3Device::internalUpdateStatusLocked(Status status) {
1834 mStatus = status;
1835 mRecentStatusUpdates.add(mStatus);
1836 mStatusChanged.broadcast();
1837}
1838
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001839// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001840status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001841 if (mRequestThread.get() != nullptr) {
1842 mRequestThread->setPaused(true);
1843 } else {
1844 return NO_INIT;
1845 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001847 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1848 maxExpectedDuration);
1849 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 if (res != OK) {
1851 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001852 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853 }
1854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 return res;
1856}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858// Resume after internalPauseAndWaitLocked
1859status_t Camera3Device::internalResumeLocked() {
1860 status_t res;
1861
1862 mRequestThread->setPaused(false);
1863
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001864 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1865 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1867 if (res != OK) {
1868 SET_ERR_L("Can't transition to active in %f seconds!",
1869 kActiveTimeout/1e9);
1870 }
1871 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001873}
1874
Ruben Brunk183f0562015-08-12 12:55:02 -07001875status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001877
1878 size_t startIndex = 0;
1879 if (mStatusWaiters == 0) {
1880 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1881 // this status list
1882 mRecentStatusUpdates.clear();
1883 } else {
1884 // If other threads are waiting on updates to this status list, set the position of the
1885 // first element that this list will check rather than clearing the list.
1886 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001887 }
1888
Ruben Brunk183f0562015-08-12 12:55:02 -07001889 mStatusWaiters++;
1890
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001891 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001892 if (!active && mUseHalBufManager) {
1893 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001894 if (mStatus == STATUS_ACTIVE) {
1895 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001896 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001897 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001898 mRequestBufferSM.onWaitUntilIdle();
1899 }
1900
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001901 bool stateSeen = false;
1902 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001903 if (active == (mStatus == STATUS_ACTIVE)) {
1904 // Desired state is current
1905 break;
1906 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001907
1908 res = mStatusChanged.waitRelative(mLock, timeout);
1909 if (res != OK) break;
1910
Ruben Brunk183f0562015-08-12 12:55:02 -07001911 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1912 // transitions.
1913 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1914 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1915 __FUNCTION__);
1916
1917 // Encountered desired state since we began waiting
1918 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001919 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1920 stateSeen = true;
1921 break;
1922 }
1923 }
1924 } while (!stateSeen);
1925
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001926 if (signalPipelineDrain) {
1927 mRequestThread->resetPipelineDrain();
1928 }
1929
Ruben Brunk183f0562015-08-12 12:55:02 -07001930 mStatusWaiters--;
1931
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001932 return res;
1933}
1934
1935
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001936status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001937 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001938 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001939
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001940 if (listener != NULL && mListener != NULL) {
1941 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1942 }
1943 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001944 mRequestThread->setNotificationListener(listener);
1945 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001946
1947 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001948}
1949
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001950bool Camera3Device::willNotify3A() {
1951 return false;
1952}
1953
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001955 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001956 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001957
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001958 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001959 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1960 if (st == std::cv_status::timeout) {
1961 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001962 }
1963 }
1964 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965}
1966
Jianing Weicb0652e2014-03-12 18:29:36 -07001967status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001969 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001970
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001971 if (mResultQueue.empty()) {
1972 return NOT_ENOUGH_DATA;
1973 }
1974
Jianing Weicb0652e2014-03-12 18:29:36 -07001975 if (frame == NULL) {
1976 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1977 return BAD_VALUE;
1978 }
1979
1980 CaptureResult &result = *(mResultQueue.begin());
1981 frame->mResultExtras = result.mResultExtras;
1982 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001983 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001984 mResultQueue.erase(mResultQueue.begin());
1985
1986 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987}
1988
1989status_t Camera3Device::triggerAutofocus(uint32_t id) {
1990 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001991 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001993 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1994 // Mix-in this trigger into the next request and only the next request.
1995 RequestTrigger trigger[] = {
1996 {
1997 ANDROID_CONTROL_AF_TRIGGER,
1998 ANDROID_CONTROL_AF_TRIGGER_START
1999 },
2000 {
2001 ANDROID_CONTROL_AF_TRIGGER_ID,
2002 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002003 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002004 };
2005
2006 return mRequestThread->queueTrigger(trigger,
2007 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002008}
2009
2010status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2011 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002012 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002013
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002014 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2015 // Mix-in this trigger into the next request and only the next request.
2016 RequestTrigger trigger[] = {
2017 {
2018 ANDROID_CONTROL_AF_TRIGGER,
2019 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2020 },
2021 {
2022 ANDROID_CONTROL_AF_TRIGGER_ID,
2023 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002024 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002025 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002026
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002027 return mRequestThread->queueTrigger(trigger,
2028 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029}
2030
2031status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2032 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002033 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002034
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002035 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2036 // Mix-in this trigger into the next request and only the next request.
2037 RequestTrigger trigger[] = {
2038 {
2039 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2040 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2041 },
2042 {
2043 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2044 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002045 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002047
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002048 return mRequestThread->queueTrigger(trigger,
2049 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002050}
2051
Jianing Weicb0652e2014-03-12 18:29:36 -07002052status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002053 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002054 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002055 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002056
Zhijun He7ef20392014-04-21 16:04:17 -07002057 {
2058 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002059
2060 // b/116514106 "disconnect()" can get called twice for the same device. The
2061 // camera device will not be initialized during the second run.
2062 if (mStatus == STATUS_UNINITIALIZED) {
2063 return OK;
2064 }
2065
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002066 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002067
2068 // Stop session and stream counter
2069 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002070 }
2071
Emilian Peev08dd2452017-04-06 16:55:14 +01002072 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002073}
2074
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002075status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002076 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2077}
2078
2079status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002080 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002081 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002082 Mutex::Autolock il(mInterfaceLock);
2083 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002084
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002085 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2086 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002087 CLOGE("Stream %d does not exist", streamId);
2088 return BAD_VALUE;
2089 }
2090
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002091 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002092 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002093 return BAD_VALUE;
2094 }
2095
2096 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002097 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002098 return BAD_VALUE;
2099 }
2100
Ruben Brunkc78ac262015-08-13 17:58:46 -07002101 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002102}
2103
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002104status_t Camera3Device::tearDown(int streamId) {
2105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002106 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002107 Mutex::Autolock il(mInterfaceLock);
2108 Mutex::Autolock l(mLock);
2109
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002110 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2111 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002112 CLOGE("Stream %d does not exist", streamId);
2113 return BAD_VALUE;
2114 }
2115
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002116 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2117 CLOGE("Stream %d is a target of a in-progress request", streamId);
2118 return BAD_VALUE;
2119 }
2120
2121 return stream->tearDown();
2122}
2123
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002124status_t Camera3Device::addBufferListenerForStream(int streamId,
2125 wp<Camera3StreamBufferListener> listener) {
2126 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002127 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002128 Mutex::Autolock il(mInterfaceLock);
2129 Mutex::Autolock l(mLock);
2130
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002131 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2132 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002133 CLOGE("Stream %d does not exist", streamId);
2134 return BAD_VALUE;
2135 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002136 stream->addBufferListener(listener);
2137
2138 return OK;
2139}
2140
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002141/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002142 * Methods called by subclasses
2143 */
2144
2145void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002146 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002147 std::vector<int> streamIds;
2148 std::vector<hardware::CameraStreamStats> streamStats;
2149
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002150 {
2151 // Need mLock to safely update state and synchronize to current
2152 // state of methods in flight.
2153 Mutex::Autolock l(mLock);
2154 // We can get various system-idle notices from the status tracker
2155 // while starting up. Only care about them if we've actually sent
2156 // in some requests recently.
2157 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2158 return;
2159 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002160 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2161 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002162 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002163
2164 // Skip notifying listener if we're doing some user-transparent
2165 // state changes
2166 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002167
2168 // Populate stream statistics in case of Idle
2169 if (idle) {
2170 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2171 auto stream = mOutputStreams[i];
2172 if (stream.get() == nullptr) continue;
2173 streamIds.push_back(stream->getId());
2174 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2175 int64_t usage = 0LL;
2176 if (camera3Stream != nullptr) {
2177 usage = camera3Stream->getUsage();
2178 }
2179 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2180 stream->getFormat(), stream->getDataSpace(), usage,
2181 stream->getMaxHalBuffers(),
2182 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2183 }
2184 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002186
2187 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002188 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002189 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002190 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002191 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002192 status_t res = OK;
2193 if (listener != nullptr) {
2194 if (idle) {
2195 // Get session stats from the builder, and notify the listener.
2196 int64_t requestCount, resultErrorCount;
2197 bool deviceError;
2198 std::map<int, StreamStats> streamStatsMap;
2199 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2200 &deviceError, &streamStatsMap);
2201 for (size_t i = 0; i < streamIds.size(); i++) {
2202 int streamId = streamIds[i];
2203 auto stats = streamStatsMap.find(streamId);
2204 if (stats != streamStatsMap.end()) {
2205 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2206 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2207 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2208 streamStats[i].mHistogramType =
2209 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2210 streamStats[i].mHistogramBins.assign(
2211 stats->second.mCaptureLatencyBins.begin(),
2212 stats->second.mCaptureLatencyBins.end());
2213 streamStats[i].mHistogramCounts.assign(
2214 stats->second.mCaptureLatencyHistogram.begin(),
2215 stats->second.mCaptureLatencyHistogram.end());
2216 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002217 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002218 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2219 } else {
2220 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002221 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002222 }
2223 if (res != OK) {
2224 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2225 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002226 }
2227}
2228
Shuzhen Wang758c2152017-01-10 18:26:18 -08002229status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002230 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002231 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002232 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2233 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002234
2235 if (surfaceIds == nullptr) {
2236 return BAD_VALUE;
2237 }
2238
Zhijun He5d677d12016-05-29 16:52:39 -07002239 Mutex::Autolock il(mInterfaceLock);
2240 Mutex::Autolock l(mLock);
2241
Shuzhen Wang758c2152017-01-10 18:26:18 -08002242 if (consumers.size() == 0) {
2243 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002244 return BAD_VALUE;
2245 }
2246
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002247 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2248 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002249 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002250 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002251 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002252
2253 // isConsumerConfigurationDeferred will be off after setConsumers
2254 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002255 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002256 if (res != OK) {
2257 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2258 return res;
2259 }
2260
Emilian Peev40ead602017-09-26 15:46:36 +01002261 for (auto &consumer : consumers) {
2262 int id = stream->getSurfaceId(consumer);
2263 if (id < 0) {
2264 CLOGE("Invalid surface id!");
2265 return BAD_VALUE;
2266 }
2267 surfaceIds->push_back(id);
2268 }
2269
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002270 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002271 if (!stream->isConfiguring()) {
2272 CLOGE("Stream %d was already fully configured.", streamId);
2273 return INVALID_OPERATION;
2274 }
Zhijun He5d677d12016-05-29 16:52:39 -07002275
Shuzhen Wang0129d522016-10-30 22:43:41 -07002276 res = stream->finishConfiguration();
2277 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002278 // If finishConfiguration fails due to abandoned surface, do not set
2279 // device to error state.
2280 bool isSurfaceAbandoned =
2281 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2282 if (!isSurfaceAbandoned) {
2283 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2284 stream->getId(), strerror(-res), res);
2285 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002286 return res;
2287 }
Zhijun He5d677d12016-05-29 16:52:39 -07002288 }
2289
2290 return OK;
2291}
2292
Emilian Peev40ead602017-09-26 15:46:36 +01002293status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2294 const std::vector<OutputStreamInfo> &outputInfo,
2295 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2296 Mutex::Autolock il(mInterfaceLock);
2297 Mutex::Autolock l(mLock);
2298
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002299 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2300 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002301 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002302 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002303 }
2304
2305 for (const auto &it : removedSurfaceIds) {
2306 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2307 CLOGE("Shared surface still part of a pending request!");
2308 return -EBUSY;
2309 }
2310 }
2311
Emilian Peev40ead602017-09-26 15:46:36 +01002312 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2313 if (res != OK) {
2314 CLOGE("Stream %d failed to update stream (error %d %s) ",
2315 streamId, res, strerror(-res));
2316 if (res == UNKNOWN_ERROR) {
2317 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2318 __FUNCTION__);
2319 }
2320 return res;
2321 }
2322
2323 return res;
2324}
2325
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002326status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2327 Mutex::Autolock il(mInterfaceLock);
2328 Mutex::Autolock l(mLock);
2329
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002330 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2331 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002332 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2333 return BAD_VALUE;
2334 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002335
2336 if (dropping) {
2337 mSessionStatsBuilder.stopCounter(streamId);
2338 } else {
2339 mSessionStatsBuilder.startCounter(streamId);
2340 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002341 return stream->dropBuffers(dropping);
2342}
2343
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002344/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345 * Camera3Device private methods
2346 */
2347
2348sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002349 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002352 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002353 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354
2355 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002356 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002357 if (inputStreams.count > 0) {
2358 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002359 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002360 CLOGE("Request references unknown input stream %d",
2361 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002362 return NULL;
2363 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002364
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002366 SET_ERR_L("%s: input stream %d is not configured!",
2367 __FUNCTION__, mInputStream->getId());
2368 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002370 // Check if stream prepare is blocking requests.
2371 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002372 CLOGE("Request references an input stream that's being prepared!");
2373 return NULL;
2374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375
2376 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002377 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 }
2379
2380 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002381 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002383 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 return NULL;
2385 }
2386
2387 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002388 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2389 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002390 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002391 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 return NULL;
2393 }
Zhijun He5d677d12016-05-29 16:52:39 -07002394 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002395 auto iter = surfaceMap.find(streams.data.i32[i]);
2396 if (iter != surfaceMap.end()) {
2397 const std::vector<size_t>& surfaces = iter->second;
2398 for (const auto& surface : surfaces) {
2399 if (stream->isConsumerConfigurationDeferred(surface)) {
2400 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2401 "due to deferred consumer", stream->getId(), surface);
2402 return NULL;
2403 }
2404 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002405 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002406 }
2407
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002409 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2410 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002412 // Check if stream prepare is blocking requests.
2413 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002414 CLOGE("Request references an output stream that's being prepared!");
2415 return NULL;
2416 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417
2418 newRequest->mOutputStreams.push(stream);
2419 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002420 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002421 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002423 auto rotateAndCropEntry =
2424 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2425 if (rotateAndCropEntry.count > 0 &&
2426 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2427 newRequest->mRotateAndCropAuto = true;
2428 } else {
2429 newRequest->mRotateAndCropAuto = false;
2430 }
2431
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002432 auto zoomRatioEntry =
2433 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2434 if (zoomRatioEntry.count > 0 &&
2435 zoomRatioEntry.data.f[0] == 1.0f) {
2436 newRequest->mZoomRatioIs1x = true;
2437 } else {
2438 newRequest->mZoomRatioIs1x = false;
2439 }
2440
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002441 if (mSupportCameraMute) {
2442 auto testPatternModeEntry =
2443 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2444 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2445 testPatternModeEntry.data.i32[0] :
2446 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2447
2448 auto testPatternDataEntry =
2449 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2450 if (testPatternDataEntry.count > 0) {
2451 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2452 sizeof(newRequest->mOriginalTestPatternData));
2453 } else {
2454 newRequest->mOriginalTestPatternData[0] = 0;
2455 newRequest->mOriginalTestPatternData[1] = 0;
2456 newRequest->mOriginalTestPatternData[2] = 0;
2457 newRequest->mOriginalTestPatternData[3] = 0;
2458 }
2459 }
2460
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002461 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002462}
2463
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002464void Camera3Device::cancelStreamsConfigurationLocked() {
2465 int res = OK;
2466 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2467 res = mInputStream->cancelConfiguration();
2468 if (res != OK) {
2469 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2470 mInputStream->getId(), strerror(-res), res);
2471 }
2472 }
2473
2474 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002475 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002476 if (outputStream->isConfiguring()) {
2477 res = outputStream->cancelConfiguration();
2478 if (res != OK) {
2479 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2480 outputStream->getId(), strerror(-res), res);
2481 }
2482 }
2483 }
2484
2485 // Return state to that at start of call, so that future configures
2486 // properly clean things up
2487 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2488 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002489
2490 res = mPreparerThread->resume();
2491 if (res != OK) {
2492 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2493 }
2494}
2495
Emilian Peev0d0191e2020-04-21 17:01:18 -07002496bool Camera3Device::checkAbandonedStreamsLocked() {
2497 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2498 return true;
2499 }
2500
2501 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2502 auto stream = mOutputStreams[i];
2503 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2504 return true;
2505 }
2506 }
2507
2508 return false;
2509}
2510
Emilian Peev3bead5f2020-05-28 17:29:08 -07002511bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002512 ATRACE_CALL();
2513 bool ret = false;
2514
Shuzhen Wang316781a2020-08-18 18:11:01 -07002515 nsecs_t startTime = systemTime();
2516
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002517 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002518 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2519
2520 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002521 if (checkAbandonedStreamsLocked()) {
2522 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2523 __FUNCTION__);
2524 return true;
2525 }
2526
Emilian Peev3bead5f2020-05-28 17:29:08 -07002527 status_t rc = NO_ERROR;
2528 bool markClientActive = false;
2529 if (mStatus == STATUS_ACTIVE) {
2530 markClientActive = true;
2531 mPauseStateNotify = true;
2532 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2533
2534 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2535 }
2536
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002537 if (rc == NO_ERROR) {
2538 mNeedConfig = true;
2539 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2540 if (rc == NO_ERROR) {
2541 ret = true;
2542 mPauseStateNotify = false;
2543 //Moving to active state while holding 'mLock' is important.
2544 //There could be pending calls to 'create-/deleteStream' which
2545 //will trigger another stream configuration while the already
2546 //present streams end up with outstanding buffers that will
2547 //not get drained.
2548 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002549 } else if (rc == DEAD_OBJECT) {
2550 // DEAD_OBJECT can be returned if either the consumer surface is
2551 // abandoned, or the HAL has died.
2552 // - If the HAL has died, configureStreamsLocked call will set
2553 // device to error state,
2554 // - If surface is abandoned, we should not set device to error
2555 // state.
2556 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002557 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002558 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002559 }
2560 } else {
2561 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2562 }
2563
Shuzhen Wang316781a2020-08-18 18:11:01 -07002564 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2565 ns2ms(systemTime() - startTime));
2566
Emilian Peev3bead5f2020-05-28 17:29:08 -07002567 if (markClientActive) {
2568 mStatusTracker->markComponentActive(clientStatusId);
2569 }
2570
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002571 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002572}
2573
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002574status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002575 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576 ATRACE_CALL();
2577 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002578
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002579 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002580 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002581 return INVALID_OPERATION;
2582 }
2583
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002584 if (operatingMode < 0) {
2585 CLOGE("Invalid operating mode: %d", operatingMode);
2586 return BAD_VALUE;
2587 }
2588
2589 bool isConstrainedHighSpeed =
2590 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2591 operatingMode;
2592
2593 if (mOperatingMode != operatingMode) {
2594 mNeedConfig = true;
2595 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2596 mOperatingMode = operatingMode;
2597 }
2598
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002599 // In case called from configureStreams, abort queued input buffers not belonging to
2600 // any pending requests.
2601 if (mInputStream != NULL && notifyRequestThread) {
2602 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002603 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002604 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002605 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002606 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002607 if (res != OK) {
2608 // Exhausted acquiring all input buffers.
2609 break;
2610 }
2611
Emilian Peevf4816702020-04-03 15:44:51 -07002612 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002613 res = mInputStream->returnInputBuffer(inputBuffer);
2614 if (res != OK) {
2615 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2616 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2617 }
2618 }
2619 }
2620
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002621 if (!mNeedConfig) {
2622 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2623 return OK;
2624 }
2625
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002626 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002627 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002628 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2629 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002630 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002631 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002632 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002633 }
2634
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002635 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002636 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002638 mPreparerThread->pause();
2639
Emilian Peevf4816702020-04-03 15:44:51 -07002640 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002641 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002642 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002643 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644
Emilian Peevf4816702020-04-03 15:44:51 -07002645 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002646 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002647 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002648
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649
2650 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002651 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 inputStream = mInputStream->startConfiguration();
2653 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002654 CLOGE("Can't start input stream configuration");
2655 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656 return INVALID_OPERATION;
2657 }
2658 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002659
2660 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 }
2662
Shuzhen Wang99080502021-03-07 21:08:20 -08002663 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002665
2666 // Don't configure bidi streams twice, nor add them twice to the list
2667 if (mOutputStreams[i].get() ==
2668 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2669
2670 config.num_streams--;
2671 continue;
2672 }
2673
Emilian Peevf4816702020-04-03 15:44:51 -07002674 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002675 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002676 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002677 CLOGE("Can't start output stream configuration");
2678 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679 return INVALID_OPERATION;
2680 }
2681 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002682
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002683 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002684 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2685 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002686 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2687 bufferSizes[k] = static_cast<uint32_t>(
2688 getJpegBufferSize(outputStream->width, outputStream->height));
2689 } else if (outputStream->data_space ==
2690 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2691 bufferSizes[k] = outputStream->width * outputStream->height;
2692 } else {
2693 ALOGW("%s: Blob dataSpace %d not supported",
2694 __FUNCTION__, outputStream->data_space);
2695 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002696 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002697
2698 if (mOutputStreams[i]->isMultiResolution()) {
2699 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2700 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2701 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2702 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002703 }
2704
2705 config.streams = streams.editArray();
2706
2707 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002708 // max_buffers, usage, and priv fields, as well as data_space and format
2709 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002710
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002711 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002712 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002713 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002715 if (res == BAD_VALUE) {
2716 // HAL rejected this set of streams as unsupported, clean up config
2717 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002718 CLOGE("Set of requested inputs/outputs not supported by HAL");
2719 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002720 return BAD_VALUE;
2721 } else if (res != OK) {
2722 // Some other kind of error from configure_streams - this is not
2723 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002724 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2725 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002726 return res;
2727 }
2728
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002729 // Finish all stream configuration immediately.
2730 // TODO: Try to relax this later back to lazy completion, which should be
2731 // faster
2732
Igor Murashkin073f8572013-05-02 14:59:28 -07002733 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002734 bool streamReConfigured = false;
2735 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002736 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002737 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002738 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002739 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002740 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2741 return DEAD_OBJECT;
2742 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002743 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002744 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002745 if (streamReConfigured) {
2746 mInterface->onStreamReConfigured(mInputStream->getId());
2747 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002748 }
2749
2750 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002751 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002752 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002753 bool streamReConfigured = false;
2754 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002755 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002756 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002757 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002758 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002759 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2760 return DEAD_OBJECT;
2761 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002762 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002763 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002764 if (streamReConfigured) {
2765 mInterface->onStreamReConfigured(outputStream->getId());
2766 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002767 }
2768 }
2769
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002770 // Request thread needs to know to avoid using repeat-last-settings protocol
2771 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002772 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002773 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2774 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002775 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002776
Zhijun He90f7c372016-08-16 16:19:43 -07002777 char value[PROPERTY_VALUE_MAX];
2778 property_get("camera.fifo.disable", value, "0");
2779 int32_t disableFifo = atoi(value);
2780 if (disableFifo != 1) {
2781 // Boost priority of request thread to SCHED_FIFO.
2782 pid_t requestThreadTid = mRequestThread->getTid();
2783 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002784 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002785 if (res != OK) {
2786 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2787 strerror(-res), res);
2788 } else {
2789 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2790 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002791 }
2792
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002793 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002794 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2795 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2796 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2797 sessionParams.unlock(newSessionParams);
2798 mSessionParams.unlock(currentSessionParams);
2799 if (updateSessionParams) {
2800 mSessionParams = sessionParams;
2801 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002803 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002804
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002805 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002806 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002807
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002808 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002809
Zhijun He0a210512014-07-24 13:45:15 -07002810 // tear down the deleted streams after configure streams.
2811 mDeletedStreams.clear();
2812
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002813 auto rc = mPreparerThread->resume();
2814 if (rc != OK) {
2815 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2816 return rc;
2817 }
2818
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002819 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002820 mRequestBufferSM.onStreamsConfigured();
2821 }
2822
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002823 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002824}
2825
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002826status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002827 ATRACE_CALL();
2828 status_t res;
2829
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002830 if (mFakeStreamId != NO_STREAM) {
2831 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002832 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002833 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002834 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002835 return INVALID_OPERATION;
2836 }
2837
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002838 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002839
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002840 sp<Camera3OutputStreamInterface> fakeStream =
2841 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002842
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002843 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002844 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002845 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002846 return res;
2847 }
2848
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002849 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002850 mNextStreamId++;
2851
2852 return OK;
2853}
2854
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002855status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002856 ATRACE_CALL();
2857 status_t res;
2858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002860 if (mOutputStreams.size() == 1) return OK;
2861
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002862 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002863
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002864 // Ok, have a fake stream and there's at least one other output stream,
2865 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002866
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002867 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002868 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002869 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002870 return INVALID_OPERATION;
2871 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002873
2874 // Free up the stream endpoint so that it can be used by some other stream
2875 res = deletedStream->disconnect();
2876 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002877 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002878 // fall through since we want to still list the stream as deleted.
2879 }
2880 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002881 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882
2883 return res;
2884}
2885
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002886void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002887 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002888 Mutex::Autolock l(mLock);
2889 va_list args;
2890 va_start(args, fmt);
2891
2892 setErrorStateLockedV(fmt, args);
2893
2894 va_end(args);
2895}
2896
2897void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002898 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002899 Mutex::Autolock l(mLock);
2900 setErrorStateLockedV(fmt, args);
2901}
2902
2903void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2904 va_list args;
2905 va_start(args, fmt);
2906
2907 setErrorStateLockedV(fmt, args);
2908
2909 va_end(args);
2910}
2911
2912void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002913 // Print out all error messages to log
2914 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002915 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002916
2917 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002918 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002919
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002920 mErrorCause = errorCause;
2921
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002922 if (mRequestThread != nullptr) {
2923 mRequestThread->setPaused(true);
2924 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002925 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002926
2927 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002928 sp<NotificationListener> listener = mListener.promote();
2929 if (listener != NULL) {
2930 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002932 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002933 }
2934
2935 // Save stack trace. View by dumping it later.
2936 CameraTraces::saveTrace();
2937 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002938}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002939
2940/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002941 * In-flight request management
2942 */
2943
Jianing Weicb0652e2014-03-12 18:29:36 -07002944status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002945 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002946 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002947 const std::set<std::set<String8>>& physicalCameraIds,
2948 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2949 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002950 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002951 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002952 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002953
2954 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002955 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002956 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002957 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002958 if (res < 0) return res;
2959
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002960 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002961 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2962 // avoid a deadlock during reprocess requests.
2963 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002964 if (mStatusTracker != nullptr) {
2965 mStatusTracker->markComponentActive(mInFlightStatusId);
2966 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002967 }
2968
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002969 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002970 return OK;
2971}
2972
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002973void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002974 // Indicate idle inFlightMap to the status tracker
2975 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002976 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002977 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2978 // avoid a deadlock during reprocess requests.
2979 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002980 if (mStatusTracker != nullptr) {
2981 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2982 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002983 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002984 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002985}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002986
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002987void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002988 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002989 // something has likely gone wrong. This might still be legit only if application send in
2990 // a long burst of long exposure requests.
2991 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2992 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2993 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2994 mInFlightMap.size(), mExpectedInflightDuration);
2995 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2996 kInFlightWarnLimitHighSpeed) {
2997 CLOGW("In-flight list too large for high speed configuration: %zu,"
2998 "total inflight duration %" PRIu64,
2999 mInFlightMap.size(), mExpectedInflightDuration);
3000 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003001 }
3002}
3003
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003004void Camera3Device::onInflightMapFlushedLocked() {
3005 mExpectedInflightDuration = 0;
3006}
3007
3008void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003009 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003010 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3011 mInFlightMap.removeItemsAt(idx, 1);
3012
3013 onInflightEntryRemovedLocked(duration);
3014}
3015
3016
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003017void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003018 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003019 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003020 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003021 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003022 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003023 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003024
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003025 FlushInflightReqStates states {
3026 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003027 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003028
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003029 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003030}
3031
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003032CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003033 ALOGV("%s", __FUNCTION__);
3034
Igor Murashkin1e479c02013-09-06 16:55:14 -07003035 CameraMetadata retVal;
3036
3037 if (mRequestThread != NULL) {
3038 retVal = mRequestThread->getLatestRequest();
3039 }
3040
Igor Murashkin1e479c02013-09-06 16:55:14 -07003041 return retVal;
3042}
3043
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003044void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003045 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3046 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3047
3048 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3049 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003050}
3051
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003052/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003053 * HalInterface inner class methods
3054 */
3055
Yifan Hongf79b5542017-04-11 14:44:25 -07003056Camera3Device::HalInterface::HalInterface(
3057 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003058 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003059 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003060 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003061 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003062 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003063 mIsReconfigurationQuerySupported(true),
3064 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003065 // Check with hardware service manager if we can downcast these interfaces
3066 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003067 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3068 if (castResult_3_7.isOk()) {
3069 mHidlSession_3_7 = castResult_3_7;
3070 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003071 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3072 if (castResult_3_6.isOk()) {
3073 mHidlSession_3_6 = castResult_3_6;
3074 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003075 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3076 if (castResult_3_5.isOk()) {
3077 mHidlSession_3_5 = castResult_3_5;
3078 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003079 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3080 if (castResult_3_4.isOk()) {
3081 mHidlSession_3_4 = castResult_3_4;
3082 }
3083 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3084 if (castResult_3_3.isOk()) {
3085 mHidlSession_3_3 = castResult_3_3;
3086 }
3087}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003089Camera3Device::HalInterface::HalInterface() :
3090 mUseHalBufManager(false),
3091 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092
3093Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003094 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003095 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003096 mUseHalBufManager(other.mUseHalBufManager),
3097 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003098
3099bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003100 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003101}
3102
3103void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003104 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003105 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003106 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003107 mHidlSession_3_4.clear();
3108 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003109 mHidlSession.clear();
3110}
3111
3112status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003113 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003114 /*out*/ camera_metadata_t **requestTemplate) {
3115 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3116 if (!valid()) return INVALID_OPERATION;
3117 status_t res = OK;
3118
Emilian Peev31abd0a2017-05-11 18:37:46 +01003119 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003120
3121 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003122 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003123 status = s;
3124 if (status == common::V1_0::Status::OK) {
3125 const camera_metadata *r =
3126 reinterpret_cast<const camera_metadata_t*>(request.data());
3127 size_t expectedSize = request.size();
3128 int ret = validate_camera_metadata_structure(r, &expectedSize);
3129 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3130 *requestTemplate = clone_camera_metadata(r);
3131 if (*requestTemplate == nullptr) {
3132 ALOGE("%s: Unable to clone camera metadata received from HAL",
3133 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003134 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003135 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003136 } else {
3137 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3138 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003139 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003140 }
3141 };
3142 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003143 RequestTemplate id;
3144 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003145 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003146 id = RequestTemplate::PREVIEW;
3147 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003148 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003149 id = RequestTemplate::STILL_CAPTURE;
3150 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003151 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003152 id = RequestTemplate::VIDEO_RECORD;
3153 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003154 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003155 id = RequestTemplate::VIDEO_SNAPSHOT;
3156 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003157 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003158 id = RequestTemplate::ZERO_SHUTTER_LAG;
3159 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003160 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003161 id = RequestTemplate::MANUAL;
3162 break;
3163 default:
3164 // Unknown template ID, or this HAL is too old to support it
3165 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003166 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003167 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003168
Emilian Peev31abd0a2017-05-11 18:37:46 +01003169 if (!err.isOk()) {
3170 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3171 res = DEAD_OBJECT;
3172 } else {
3173 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003174 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003175
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003176 return res;
3177}
3178
Emilian Peev4ec17882019-01-24 17:16:58 -08003179bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3180 CameraMetadata& newSessionParams) {
3181 // We do reconfiguration by default;
3182 bool ret = true;
3183 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3184 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3185 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3186 oldSessionParams.getAndLock());
3187 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3188 newSessionParams.getAndLock());
3189 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3190 get_camera_metadata_size(oldSessioMeta));
3191 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3192 get_camera_metadata_size(newSessioMeta));
3193 hardware::camera::common::V1_0::Status callStatus;
3194 bool required;
3195 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3196 bool requiredFlag) {
3197 callStatus = s;
3198 required = requiredFlag;
3199 };
3200 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3201 oldSessionParams.unlock(oldSessioMeta);
3202 newSessionParams.unlock(newSessioMeta);
3203 if (err.isOk()) {
3204 switch (callStatus) {
3205 case hardware::camera::common::V1_0::Status::OK:
3206 ret = required;
3207 break;
3208 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3209 mIsReconfigurationQuerySupported = false;
3210 ret = true;
3211 break;
3212 default:
3213 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3214 ret = true;
3215 }
3216 } else {
3217 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3218 ret = true;
3219 }
3220 }
3221
3222 return ret;
3223}
3224
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003225status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003226 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003227 ATRACE_NAME("CameraHal::configureStreams");
3228 if (!valid()) return INVALID_OPERATION;
3229 status_t res = OK;
3230
Shuzhen Wang83bff122020-11-20 15:51:39 -08003231 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3232 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3233 return BAD_VALUE;
3234 }
3235
Emilian Peev31abd0a2017-05-11 18:37:46 +01003236 // Convert stream config to HIDL
3237 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003238 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3239 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003240 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003241 requestedConfiguration3_2.streams.resize(config->num_streams);
3242 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003243 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003244 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003245 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3246 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003247 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003248 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003249
Emilian Peev31abd0a2017-05-11 18:37:46 +01003250 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3251 cam3stream->setBufferFreedListener(this);
3252 int streamId = cam3stream->getId();
3253 StreamType streamType;
3254 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003255 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003256 streamType = StreamType::OUTPUT;
3257 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003258 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003259 streamType = StreamType::INPUT;
3260 break;
3261 default:
3262 ALOGE("%s: Stream %d: Unsupported stream type %d",
3263 __FUNCTION__, streamId, config->streams[i]->stream_type);
3264 return BAD_VALUE;
3265 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003266 dst3_2.id = streamId;
3267 dst3_2.streamType = streamType;
3268 dst3_2.width = src->width;
3269 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003270 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003271 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003272 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003273 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003274 if (mHidlSession_3_5 != nullptr) {
3275 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3276 cam3stream->getOriginalFormat() : src->format);
3277 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3278 cam3stream->getOriginalDataSpace() : src->data_space);
3279 } else {
3280 dst3_2.format = mapToPixelFormat(src->format);
3281 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3282 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003283 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003284 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003285 if (src->physical_camera_id != nullptr) {
3286 dst3_4.physicalCameraId = src->physical_camera_id;
3287 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003288 dst3_7.v3_4 = dst3_4;
3289 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003290 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3291 size_t j = 0;
3292 for (int mode : src->sensor_pixel_modes_used) {
3293 dst3_7.sensorPixelModesUsed[j++] =
3294 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3295 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003296 activeStreams.insert(streamId);
3297 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003298 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003299 }
3300 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003301 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003302
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003303 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003304 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003305 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003306 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003307 if (res != OK) {
3308 return res;
3309 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003310 requestedConfiguration3_2.operationMode = operationMode;
3311 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003312 requestedConfiguration3_7.operationMode = operationMode;
3313 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003314 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003315 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003316 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003317 requestedConfiguration3_7.operationMode = operationMode;
3318 requestedConfiguration3_7.sessionParams.setToExternal(
3319 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003320 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003321
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003323 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003324 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003325 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003326 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003327
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003328 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003329 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3330 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003331 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003332 };
3333
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003334 auto configStream36Cb = [&status, &finalConfiguration3_6]
3335 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3336 finalConfiguration3_6 = halConfiguration;
3337 status = s;
3338 };
3339
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003340 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3341 (hardware::Return<void>& err) -> status_t {
3342 if (!err.isOk()) {
3343 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3344 return DEAD_OBJECT;
3345 }
3346 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3347 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3348 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3349 }
3350 return OK;
3351 };
3352
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003353 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3354 (hardware::Return<void>& err) -> status_t {
3355 if (!err.isOk()) {
3356 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3357 return DEAD_OBJECT;
3358 }
3359 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3360 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3361 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3362 }
3363 return OK;
3364 };
3365
Shuzhen Wang92653952019-05-07 15:11:43 -07003366 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003367 if (mHidlSession_3_7 != nullptr) {
3368 ALOGV("%s: v3.7 device found", __FUNCTION__);
3369 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3370 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3371 auto err = mHidlSession_3_7->configureStreams_3_7(
3372 requestedConfiguration3_7, configStream36Cb);
3373 res = postprocConfigStream36(err);
3374 if (res != OK) {
3375 return res;
3376 }
3377 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003378 ALOGV("%s: v3.6 device found", __FUNCTION__);
3379 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3380 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3381 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3382 auto err = mHidlSession_3_6->configureStreams_3_6(
3383 requestedConfiguration3_5, configStream36Cb);
3384 res = postprocConfigStream36(err);
3385 if (res != OK) {
3386 return res;
3387 }
3388 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003389 ALOGV("%s: v3.5 device found", __FUNCTION__);
3390 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3391 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3392 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3393 auto err = mHidlSession_3_5->configureStreams_3_5(
3394 requestedConfiguration3_5, configStream34Cb);
3395 res = postprocConfigStream34(err);
3396 if (res != OK) {
3397 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003398 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003399 } else if (mHidlSession_3_4 != nullptr) {
3400 // We do; use v3.4 for the call
3401 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003402 auto err = mHidlSession_3_4->configureStreams_3_4(
3403 requestedConfiguration3_4, configStream34Cb);
3404 res = postprocConfigStream34(err);
3405 if (res != OK) {
3406 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003407 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003408 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003409 // We do; use v3.3 for the call
3410 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003411 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003412 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003413 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003414 finalConfiguration = halConfiguration;
3415 status = s;
3416 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003417 if (!err.isOk()) {
3418 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3419 return DEAD_OBJECT;
3420 }
3421 } else {
3422 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3423 ALOGV("%s: v3.2 device found", __FUNCTION__);
3424 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003425 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003426 [&status, &finalConfiguration_3_2]
3427 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3428 finalConfiguration_3_2 = halConfiguration;
3429 status = s;
3430 });
3431 if (!err.isOk()) {
3432 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3433 return DEAD_OBJECT;
3434 }
3435 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3436 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3437 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3438 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003439 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003440 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003441 }
3442
3443 if (status != common::V1_0::Status::OK ) {
3444 return CameraProviderManager::mapToStatusT(status);
3445 }
3446
3447 // And convert output stream configuration from HIDL
3448
3449 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003450 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003451 int streamId = Camera3Stream::cast(dst)->getId();
3452
3453 // Start scan at i, with the assumption that the stream order matches
3454 size_t realIdx = i;
3455 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003456 size_t halStreamCount = finalConfiguration.streams.size();
3457 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003458 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003459 found = true;
3460 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003461 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003462 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003463 }
3464 if (!found) {
3465 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3466 __FUNCTION__, streamId);
3467 return INVALID_OPERATION;
3468 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003469 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003470 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003471
Emilian Peev710c1422017-08-30 11:19:38 +01003472 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003473 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3474 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3475
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003476 if (mHidlSession_3_6 != nullptr) {
3477 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3478 }
3479
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003480 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003481 dstStream->setFormatOverride(false);
3482 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003483 if (dst->format != overrideFormat) {
3484 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3485 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003486 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003487 if (dst->data_space != overrideDataSpace) {
3488 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3489 streamId, dst->format);
3490 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003492 bool needFormatOverride =
3493 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3494 bool needDataspaceOverride =
3495 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003497 dstStream->setFormatOverride(needFormatOverride);
3498 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003500 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003501 }
3502
Emilian Peevf4816702020-04-03 15:44:51 -07003503 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003504 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003505 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003506 __FUNCTION__, streamId);
3507 return INVALID_OPERATION;
3508 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003509 dstStream->setUsage(
3510 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003511 } else {
3512 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003513 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3515 __FUNCTION__, streamId);
3516 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003517 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003518 dstStream->setUsage(
3519 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003520 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003521 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003522 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003523
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003524 return res;
3525}
3526
Emilian Peevf4816702020-04-03 15:44:51 -07003527status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003528 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003529 /*out*/std::vector<native_handle_t*>* handlesCreated,
3530 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003531 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003532 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3533 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3534 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003535 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003536 }
3537
3538 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003539
3540 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003541
3542 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003543 if (request->input_buffer != nullptr) {
3544 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3545 buffer_handle_t buf = *(request->input_buffer->buffer);
3546 auto pair = getBufferId(buf, streamId);
3547 bool isNewBuffer = pair.first;
3548 uint64_t bufferId = pair.second;
3549 captureRequest->inputBuffer.streamId = streamId;
3550 captureRequest->inputBuffer.bufferId = bufferId;
3551 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3552 captureRequest->inputBuffer.status = BufferStatus::OK;
3553 native_handle_t *acquireFence = nullptr;
3554 if (request->input_buffer->acquire_fence != -1) {
3555 acquireFence = native_handle_create(1,0);
3556 acquireFence->data[0] = request->input_buffer->acquire_fence;
3557 handlesCreated->push_back(acquireFence);
3558 }
3559 captureRequest->inputBuffer.acquireFence = acquireFence;
3560 captureRequest->inputBuffer.releaseFence = nullptr;
3561
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003562 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003563 request->input_buffer->buffer);
3564 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003565 } else {
3566 captureRequest->inputBuffer.streamId = -1;
3567 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3568 }
3569
3570 captureRequest->outputBuffers.resize(request->num_output_buffers);
3571 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003572 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003573 StreamBuffer &dst = captureRequest->outputBuffers[i];
3574 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003575 if (src->buffer != nullptr) {
3576 buffer_handle_t buf = *(src->buffer);
3577 auto pair = getBufferId(buf, streamId);
3578 bool isNewBuffer = pair.first;
3579 dst.bufferId = pair.second;
3580 dst.buffer = isNewBuffer ? buf : nullptr;
3581 native_handle_t *acquireFence = nullptr;
3582 if (src->acquire_fence != -1) {
3583 acquireFence = native_handle_create(1,0);
3584 acquireFence->data[0] = src->acquire_fence;
3585 handlesCreated->push_back(acquireFence);
3586 }
3587 dst.acquireFence = acquireFence;
3588 } else if (mUseHalBufManager) {
3589 // HAL buffer management path
3590 dst.bufferId = BUFFER_ID_NO_BUFFER;
3591 dst.buffer = nullptr;
3592 dst.acquireFence = nullptr;
3593 } else {
3594 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3595 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003596 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003597 dst.streamId = streamId;
3598 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003599 dst.releaseFence = nullptr;
3600
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003601 // Output buffers are empty when using HAL buffer manager
3602 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003603 mBufferRecords.pushInflightBuffer(
3604 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003605 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003606 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003607 }
3608 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003609 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003610}
3611
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003612void Camera3Device::HalInterface::cleanupNativeHandles(
3613 std::vector<native_handle_t*> *handles, bool closeFd) {
3614 if (handles == nullptr) {
3615 return;
3616 }
3617 if (closeFd) {
3618 for (auto& handle : *handles) {
3619 native_handle_close(handle);
3620 }
3621 }
3622 for (auto& handle : *handles) {
3623 native_handle_delete(handle);
3624 }
3625 handles->clear();
3626 return;
3627}
3628
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003629status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003630 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003631 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3632 if (!valid()) return INVALID_OPERATION;
3633
Emilian Peevaebbe412018-01-15 13:53:24 +00003634 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003635 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3636 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3637 if (castResult_3_7.isOk()) {
3638 hidlSession_3_7 = castResult_3_7;
3639 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003640 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3641 if (castResult_3_4.isOk()) {
3642 hidlSession_3_4 = castResult_3_4;
3643 }
3644
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003645 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003646 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003647 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003648 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003649 if (hidlSession_3_7 != nullptr) {
3650 captureRequests_3_7.resize(batchSize);
3651 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003652 captureRequests_3_4.resize(batchSize);
3653 } else {
3654 captureRequests.resize(batchSize);
3655 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003656 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003657 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003658
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003659 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003660 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003661 if (hidlSession_3_7 != nullptr) {
3662 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3663 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3664 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003665 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003666 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003667 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003668 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3669 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003670 }
3671 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003672 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003673 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003674 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003675 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003676 }
3677
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003678 std::vector<device::V3_2::BufferCache> cachesToRemove;
3679 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003680 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003681 for (auto& pair : mFreedBuffers) {
3682 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003683 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003684 cachesToRemove.push_back({pair.first, pair.second});
3685 }
3686 }
3687 mFreedBuffers.clear();
3688 }
3689
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003690 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3691 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003692
3693 // Write metadata to FMQ.
3694 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003695 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003696 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003697 if (hidlSession_3_7 != nullptr) {
3698 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3699 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003700 captureRequest = &captureRequests_3_4[i].v3_2;
3701 } else {
3702 captureRequest = &captureRequests[i];
3703 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003704
3705 if (request->settings != nullptr) {
3706 size_t settingsSize = get_camera_metadata_size(request->settings);
3707 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3708 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3709 captureRequest->settings.resize(0);
3710 captureRequest->fmqSettingsSize = settingsSize;
3711 } else {
3712 if (mRequestMetadataQueue != nullptr) {
3713 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3714 }
3715 captureRequest->settings.setToExternal(
3716 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3717 get_camera_metadata_size(request->settings));
3718 captureRequest->fmqSettingsSize = 0u;
3719 }
3720 } else {
3721 // A null request settings maps to a size-0 CameraMetadata
3722 captureRequest->settings.resize(0);
3723 captureRequest->fmqSettingsSize = 0u;
3724 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003725
Shuzhen Wang83bff122020-11-20 15:51:39 -08003726 // hidl session 3.7 specific handling.
3727 if (hidlSession_3_7 != nullptr) {
3728 captureRequests_3_7[i].inputWidth = request->input_width;
3729 captureRequests_3_7[i].inputHeight = request->input_height;
3730 }
3731
3732 // hidl session 3.7 and 3.4 specific handling.
3733 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3734 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3735 (hidlSession_3_7 != nullptr) ?
3736 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3737 captureRequests_3_4[i].physicalCameraSettings;
3738 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003739 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003740 if (request->physcam_settings != nullptr) {
3741 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3742 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3743 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3744 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003745 physicalCameraSettings[j].settings.resize(0);
3746 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003747 } else {
3748 if (mRequestMetadataQueue != nullptr) {
3749 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3750 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003751 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003752 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3753 request->physcam_settings[j])),
3754 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003755 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003756 }
Emilian Peev00420d22018-02-05 21:33:13 +00003757 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003758 physicalCameraSettings[j].fmqSettingsSize = 0u;
3759 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003760 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003761 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003762 }
3763 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003764 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003765
3766 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003767 auto resultCallback =
3768 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3769 status = s;
3770 *numRequestProcessed = n;
3771 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003772 if (hidlSession_3_7 != nullptr) {
3773 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3774 resultCallback);
3775 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003776 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003777 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003778 } else {
3779 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003780 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003781 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003782 if (!err.isOk()) {
3783 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003784 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003785 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003786
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003787 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3788 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3789 __FUNCTION__, *numRequestProcessed, batchSize);
3790 status = common::V1_0::Status::INTERNAL_ERROR;
3791 }
3792
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003793 res = CameraProviderManager::mapToStatusT(status);
3794 if (res == OK) {
3795 if (mHidlSession->isRemote()) {
3796 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3797 // sent to camera HAL processes)
3798 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3799 } else {
3800 // In passthrough mode the FDs are now owned by HAL
3801 cleanupNativeHandles(&handlesCreated);
3802 }
3803 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003804 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003805 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003806 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003807 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003808}
3809
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003810status_t Camera3Device::HalInterface::flush() {
3811 ATRACE_NAME("CameraHal::flush");
3812 if (!valid()) return INVALID_OPERATION;
3813 status_t res = OK;
3814
Emilian Peev31abd0a2017-05-11 18:37:46 +01003815 auto err = mHidlSession->flush();
3816 if (!err.isOk()) {
3817 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3818 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003819 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003820 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003821 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003822
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003823 return res;
3824}
3825
Emilian Peev31abd0a2017-05-11 18:37:46 +01003826status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003827 ATRACE_NAME("CameraHal::dump");
3828 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003829
Emilian Peev31abd0a2017-05-11 18:37:46 +01003830 // Handled by CameraProviderManager::dump
3831
3832 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003833}
3834
3835status_t Camera3Device::HalInterface::close() {
3836 ATRACE_NAME("CameraHal::close()");
3837 if (!valid()) return INVALID_OPERATION;
3838 status_t res = OK;
3839
Emilian Peev31abd0a2017-05-11 18:37:46 +01003840 auto err = mHidlSession->close();
3841 // Interface will be dead shortly anyway, so don't log errors
3842 if (!err.isOk()) {
3843 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003844 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003845
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003846 return res;
3847}
3848
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003849void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3850 ATRACE_NAME("CameraHal::signalPipelineDrain");
3851 if (!valid() || mHidlSession_3_5 == nullptr) {
3852 ALOGE("%s called on invalid camera!", __FUNCTION__);
3853 return;
3854 }
3855
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003856 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003857 if (!err.isOk()) {
3858 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3859 return;
3860 }
3861}
3862
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003863status_t Camera3Device::HalInterface::switchToOffline(
3864 const std::vector<int32_t>& streamsToKeep,
3865 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003866 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3867 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003868 ATRACE_NAME("CameraHal::switchToOffline");
3869 if (!valid() || mHidlSession_3_6 == nullptr) {
3870 ALOGE("%s called on invalid camera!", __FUNCTION__);
3871 return INVALID_OPERATION;
3872 }
3873
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003874 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3875 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003876 return INVALID_OPERATION;
3877 }
3878
3879 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003880 auto resultCallback =
3881 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3882 status = s;
3883 *offlineSessionInfo = info;
3884 *offlineSession = session;
3885 };
3886 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3887
3888 if (!err.isOk()) {
3889 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3890 return DEAD_OBJECT;
3891 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003892
3893 status_t ret = CameraProviderManager::mapToStatusT(status);
3894 if (ret != OK) {
3895 return ret;
3896 }
3897
3898 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3899 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3900 // returns from switchToOffline.
3901
3902
3903 // Validate buffer caches
3904 std::vector<int32_t> streams;
3905 streams.reserve(offlineSessionInfo->offlineStreams.size());
3906 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3907 int32_t id = offlineStream.id;
3908 streams.push_back(id);
3909 // Verify buffer caches
3910 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3911 offlineStream.circulatingBufferIds.end());
3912 if (!verifyBufferIds(id, bufIds)) {
3913 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3914 return UNKNOWN_ERROR;
3915 }
3916 }
3917
3918 // Move buffer records
3919 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3920 bufferRecords->takeInflightBufferMap(mBufferRecords);
3921 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3922 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003923}
3924
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003925void Camera3Device::HalInterface::getInflightBufferKeys(
3926 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003927 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003928 return;
3929}
3930
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003931void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3932 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003933 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003934 return;
3935}
3936
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003937bool Camera3Device::HalInterface::verifyBufferIds(
3938 int32_t streamId, std::vector<uint64_t>& bufIds) {
3939 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003940}
3941
3942status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003943 int32_t frameNumber, int32_t streamId,
3944 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003945 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003946}
3947
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003948status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003949 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003950 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003951}
3952
3953// Find and pop a buffer_handle_t based on bufferId
3954status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003955 uint64_t bufferId,
3956 /*out*/ buffer_handle_t** buffer,
3957 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003958 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003959}
3960
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003961std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3962 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003963 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003964}
3965
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003966void Camera3Device::HalInterface::onBufferFreed(
3967 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003968 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3969 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3970 if (bufferId != BUFFER_ID_NO_BUFFER) {
3971 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003972 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003973}
3974
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003975void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003976 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3977 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3978 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003979 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3980 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003981}
3982
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003983/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003984 * RequestThread inner class methods
3985 */
3986
3987Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003988 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003989 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3990 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003991 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003992 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003993 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003995 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003996 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003997 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003998 mReconfigured(false),
3999 mDoPause(false),
4000 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004001 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004002 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004003 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004004 mCurrentAfTriggerId(0),
4005 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004006 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004007 mCameraMute(false),
4008 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004009 mRepeatingLastFrameNumber(
4010 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004011 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004012 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004013 mRequestLatency(kRequestLatencyBinSize),
4014 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004015 mLatestSessionParams(sessionParamKeys.size()),
4016 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004017 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004018}
4019
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004020Camera3Device::RequestThread::~RequestThread() {}
4021
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004022void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004023 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004024 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004025 Mutex::Autolock l(mRequestLock);
4026 mListener = listener;
4027}
4028
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004029void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004030 const CameraMetadata& sessionParams,
4031 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004032 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004033 Mutex::Autolock l(mRequestLock);
4034 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004035 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004036 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004037 // Prepare video stream for high speed recording.
4038 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004039 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004040}
4041
Jianing Wei90e59c92014-03-12 18:29:36 -07004042status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004043 List<sp<CaptureRequest> > &requests,
4044 /*out*/
4045 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004046 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004047 Mutex::Autolock l(mRequestLock);
4048 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4049 ++it) {
4050 mRequestQueue.push_back(*it);
4051 }
4052
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004053 if (lastFrameNumber != NULL) {
4054 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4055 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4056 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4057 *lastFrameNumber);
4058 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004059
Jianing Wei90e59c92014-03-12 18:29:36 -07004060 unpauseForNewRequests();
4061
4062 return OK;
4063}
4064
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004065
4066status_t Camera3Device::RequestThread::queueTrigger(
4067 RequestTrigger trigger[],
4068 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004069 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004070 Mutex::Autolock l(mTriggerMutex);
4071 status_t ret;
4072
4073 for (size_t i = 0; i < count; ++i) {
4074 ret = queueTriggerLocked(trigger[i]);
4075
4076 if (ret != OK) {
4077 return ret;
4078 }
4079 }
4080
4081 return OK;
4082}
4083
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004084const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4085 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004086 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004087 if (d != nullptr) return d->mId;
4088 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004089}
4090
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004091status_t Camera3Device::RequestThread::queueTriggerLocked(
4092 RequestTrigger trigger) {
4093
4094 uint32_t tag = trigger.metadataTag;
4095 ssize_t index = mTriggerMap.indexOfKey(tag);
4096
4097 switch (trigger.getTagType()) {
4098 case TYPE_BYTE:
4099 // fall-through
4100 case TYPE_INT32:
4101 break;
4102 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004103 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4104 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004105 return INVALID_OPERATION;
4106 }
4107
4108 /**
4109 * Collect only the latest trigger, since we only have 1 field
4110 * in the request settings per trigger tag, and can't send more than 1
4111 * trigger per request.
4112 */
4113 if (index != NAME_NOT_FOUND) {
4114 mTriggerMap.editValueAt(index) = trigger;
4115 } else {
4116 mTriggerMap.add(tag, trigger);
4117 }
4118
4119 return OK;
4120}
4121
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004122status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004123 const RequestList &requests,
4124 /*out*/
4125 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004126 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004127 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004128 if (lastFrameNumber != NULL) {
4129 *lastFrameNumber = mRepeatingLastFrameNumber;
4130 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004131 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004132 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004133 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4134 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004135
4136 unpauseForNewRequests();
4137
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004138 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004139 return OK;
4140}
4141
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004142bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004143 if (mRepeatingRequests.empty()) {
4144 return false;
4145 }
4146 int32_t requestId = requestIn->mResultExtras.requestId;
4147 const RequestList &repeatRequests = mRepeatingRequests;
4148 // All repeating requests are guaranteed to have same id so only check first quest
4149 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4150 return (firstRequest->mResultExtras.requestId == requestId);
4151}
4152
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004153status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004154 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004155 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004156 return clearRepeatingRequestsLocked(lastFrameNumber);
4157
4158}
4159
4160status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004161 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004162 if (lastFrameNumber != NULL) {
4163 *lastFrameNumber = mRepeatingLastFrameNumber;
4164 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004165 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004166 return OK;
4167}
4168
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004169status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004170 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004171 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004172 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004173 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004174
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004175 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004176
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004177 // Send errors for all requests pending in the request queue, including
4178 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004179 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004180 if (listener != NULL) {
4181 for (RequestList::iterator it = mRequestQueue.begin();
4182 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004183 // Abort the input buffers for reprocess requests.
4184 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004185 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004186 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004187 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004188 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004189 if (res != OK) {
4190 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4191 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4192 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004193 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004194 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4195 if (res != OK) {
4196 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4197 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4198 }
4199 }
4200 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004201 // Set the frame number this request would have had, if it
4202 // had been submitted; this frame number will not be reused.
4203 // The requestId and burstId fields were set when the request was
4204 // submitted originally (in convertMetadataListToRequestListLocked)
4205 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004206 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004207 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004208 }
4209 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004210 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004211
4212 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004213 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004214 if (lastFrameNumber != NULL) {
4215 *lastFrameNumber = mRepeatingLastFrameNumber;
4216 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004217 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004218 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004219 return OK;
4220}
4221
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222status_t Camera3Device::RequestThread::flush() {
4223 ATRACE_CALL();
4224 Mutex::Autolock l(mFlushLock);
4225
Emilian Peev08dd2452017-04-06 16:55:14 +01004226 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004227}
4228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004229void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004230 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004231 Mutex::Autolock l(mPauseLock);
4232 mDoPause = paused;
4233 mDoPauseSignal.signal();
4234}
4235
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004236status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4237 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004238 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004239 Mutex::Autolock l(mLatestRequestMutex);
4240 status_t res;
4241 while (mLatestRequestId != requestId) {
4242 nsecs_t startTime = systemTime();
4243
4244 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4245 if (res != OK) return res;
4246
4247 timeout -= (systemTime() - startTime);
4248 }
4249
4250 return OK;
4251}
4252
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004253void Camera3Device::RequestThread::requestExit() {
4254 // Call parent to set up shutdown
4255 Thread::requestExit();
4256 // The exit from any possible waits
4257 mDoPauseSignal.signal();
4258 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004259
4260 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4261 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004262}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004263
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004264void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004265 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004266 bool surfaceAbandoned = false;
4267 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004268 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004269 {
4270 Mutex::Autolock l(mRequestLock);
4271 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4272 // repeating requests.
4273 for (const auto& request : mRepeatingRequests) {
4274 for (const auto& s : request->mOutputStreams) {
4275 if (s->isAbandoned()) {
4276 surfaceAbandoned = true;
4277 clearRepeatingRequestsLocked(&lastFrameNumber);
4278 break;
4279 }
4280 }
4281 if (surfaceAbandoned) {
4282 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004283 }
4284 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004285 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004286 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004287
4288 if (listener != NULL && surfaceAbandoned) {
4289 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004290 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004291}
4292
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004293bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004294 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004295 status_t res;
4296 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004297 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004298 uint32_t numRequestProcessed = 0;
4299 for (size_t i = 0; i < batchSize; i++) {
4300 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004301 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004302 }
4303
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004304 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4305
4306 bool triggerRemoveFailed = false;
4307 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4308 for (size_t i = 0; i < numRequestProcessed; i++) {
4309 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4310 nextRequest.submitted = true;
4311
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004312 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004313
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004314 if (!triggerRemoveFailed) {
4315 // Remove any previously queued triggers (after unlock)
4316 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4317 if (removeTriggerRes != OK) {
4318 triggerRemoveFailed = true;
4319 triggerFailedRequest = nextRequest;
4320 }
4321 }
4322 }
4323
4324 if (triggerRemoveFailed) {
4325 SET_ERR("RequestThread: Unable to remove triggers "
4326 "(capture request %d, HAL device: %s (%d)",
4327 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4328 cleanUpFailedRequests(/*sendRequestError*/ false);
4329 return false;
4330 }
4331
4332 if (res != OK) {
4333 // Should only get a failure here for malformed requests or device-level
4334 // errors, so consider all errors fatal. Bad metadata failures should
4335 // come through notify.
4336 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4337 mNextRequests[numRequestProcessed].halRequest.frame_number,
4338 strerror(-res), res);
4339 cleanUpFailedRequests(/*sendRequestError*/ false);
4340 return false;
4341 }
4342 return true;
4343}
4344
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004345nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4346 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4347 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4348 find_camera_metadata_ro_entry(request,
4349 ANDROID_CONTROL_AE_MODE,
4350 &e);
4351 if (e.count == 0) return maxExpectedDuration;
4352
4353 switch (e.data.u8[0]) {
4354 case ANDROID_CONTROL_AE_MODE_OFF:
4355 find_camera_metadata_ro_entry(request,
4356 ANDROID_SENSOR_EXPOSURE_TIME,
4357 &e);
4358 if (e.count > 0) {
4359 maxExpectedDuration = e.data.i64[0];
4360 }
4361 find_camera_metadata_ro_entry(request,
4362 ANDROID_SENSOR_FRAME_DURATION,
4363 &e);
4364 if (e.count > 0) {
4365 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4366 }
4367 break;
4368 default:
4369 find_camera_metadata_ro_entry(request,
4370 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4371 &e);
4372 if (e.count > 1) {
4373 maxExpectedDuration = 1e9 / e.data.u8[0];
4374 }
4375 break;
4376 }
4377
4378 return maxExpectedDuration;
4379}
4380
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004381bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4382 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4383 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4384 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4385 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4386 return true;
4387 }
4388
4389 return false;
4390}
4391
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004392void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4393 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004394 camera_capture_request_t& halRequest = nextRequest.halRequest;
4395 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004396 Mutex::Autolock al(mLatestRequestMutex);
4397
Shuzhen Wang83bff122020-11-20 15:51:39 -08004398 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004399 mLatestRequest.acquire(cloned);
4400
4401 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004402 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4403 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4404 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004405 CameraMetadata(cloned));
4406 }
4407
4408 sp<Camera3Device> parent = mParent.promote();
4409 if (parent != NULL) {
4410 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004411 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004412 0, mLatestRequest, mLatestPhysicalRequest);
4413 }
4414 }
4415
Shuzhen Wang83bff122020-11-20 15:51:39 -08004416 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004417 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004418 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004419 }
4420
Shuzhen Wang83bff122020-11-20 15:51:39 -08004421 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004422}
4423
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004424bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4425 ATRACE_CALL();
4426 bool updatesDetected = false;
4427
Emilian Peev4ec17882019-01-24 17:16:58 -08004428 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004429 for (auto tag : mSessionParamKeys) {
4430 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004431 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004432
4433 if (entry.count > 0) {
4434 bool isDifferent = false;
4435 if (lastEntry.count > 0) {
4436 // Have a last value, compare to see if changed
4437 if (lastEntry.type == entry.type &&
4438 lastEntry.count == entry.count) {
4439 // Same type and count, compare values
4440 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4441 size_t entryBytes = bytesPerValue * lastEntry.count;
4442 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4443 if (cmp != 0) {
4444 isDifferent = true;
4445 }
4446 } else {
4447 // Count or type has changed
4448 isDifferent = true;
4449 }
4450 } else {
4451 // No last entry, so always consider to be different
4452 isDifferent = true;
4453 }
4454
4455 if (isDifferent) {
4456 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004457 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4458 updatesDetected = true;
4459 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004460 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004461 }
4462 } else if (lastEntry.count > 0) {
4463 // Value has been removed
4464 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004465 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004466 updatesDetected = true;
4467 }
4468 }
4469
Emilian Peev4ec17882019-01-24 17:16:58 -08004470 bool reconfigureRequired;
4471 if (updatesDetected) {
4472 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4473 updatedParams);
4474 mLatestSessionParams = updatedParams;
4475 } else {
4476 reconfigureRequired = false;
4477 }
4478
4479 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004480}
4481
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004482bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004483 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004484 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004485 // Any function called from threadLoop() must not hold mInterfaceLock since
4486 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4487 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004488
4489 // Handle paused state.
4490 if (waitIfPaused()) {
4491 return true;
4492 }
4493
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004494 // Wait for the next batch of requests.
4495 waitForNextRequestBatch();
4496 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004497 return true;
4498 }
4499
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004500 // Get the latest request ID, if any
4501 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004502 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004503 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004504 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004505 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004506 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004507 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4508 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004509 }
4510
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004511 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4512 // or a single request from streaming or burst. In either case the first element
4513 // should contain the latest camera settings that we need to check for any session
4514 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004515 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004516 res = OK;
4517
4518 //Input stream buffers are already acquired at this point so an input stream
4519 //will not be able to move to idle state unless we force it.
4520 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4521 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4522 if (res != OK) {
4523 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4524 cleanUpFailedRequests(/*sendRequestError*/ false);
4525 return false;
4526 }
4527 }
4528
4529 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004530 sp<Camera3Device> parent = mParent.promote();
4531 if (parent != nullptr) {
4532 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004533 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004534 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004535
4536 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4537 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4538 if (res != OK) {
4539 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4540 cleanUpFailedRequests(/*sendRequestError*/ false);
4541 return false;
4542 }
4543 }
4544 }
4545 }
4546
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004547 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004548 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004549 if (res == TIMED_OUT) {
4550 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004551 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004552 // Check if any stream is abandoned.
4553 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004554 return true;
4555 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004556 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004557 return false;
4558 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004559
Zhijun Hecc27e112013-10-03 16:12:43 -07004560 // Inform waitUntilRequestProcessed thread of a new request ID
4561 {
4562 Mutex::Autolock al(mLatestRequestMutex);
4563
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004564 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004565 mLatestRequestSignal.signal();
4566 }
4567
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004568 // Submit a batch of requests to HAL.
4569 // Use flush lock only when submitting multilple requests in a batch.
4570 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4571 // which may take a long time to finish so synchronizing flush() and
4572 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4573 // For now, only synchronize for high speed recording and we should figure something out for
4574 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004575 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004576
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004577 if (useFlushLock) {
4578 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004579 }
4580
Zhijun Hef0645c12016-08-02 00:58:11 -07004581 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004582 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004583
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004584 sp<Camera3Device> parent = mParent.promote();
4585 if (parent != nullptr) {
4586 parent->mRequestBufferSM.onSubmittingRequest();
4587 }
4588
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004589 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004590 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004591 submitRequestSuccess = sendRequestsBatch();
4592
Shuzhen Wang686f6442017-06-20 16:16:04 -07004593 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4594 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004595
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004596 if (useFlushLock) {
4597 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004598 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004599
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004600 // Unset as current request
4601 {
4602 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004603 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004604 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004605 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004606
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004607 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004608}
4609
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004610status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004611 ATRACE_CALL();
4612
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004613 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004614 for (size_t i = 0; i < mNextRequests.size(); i++) {
4615 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004616 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004617 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4618 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004619
4620 // Prepare a request to HAL
4621 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4622
4623 // Insert any queued triggers (before metadata is locked)
4624 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004625 if (res < 0) {
4626 SET_ERR("RequestThread: Unable to insert triggers "
4627 "(capture request %d, HAL device: %s (%d)",
4628 halRequest->frame_number, strerror(-res), res);
4629 return INVALID_OPERATION;
4630 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004631
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004632 int triggerCount = res;
4633 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4634 mPrevTriggers = triggerCount;
4635
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004636 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004637 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004638
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004639 // If the request is the same as last, or we had triggers now or last time or
4640 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004641 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004642 (mPrevRequest != captureRequest || triggersMixedIn ||
4643 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004644 // Request settings are all the same within one batch, so only treat the first
4645 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004646 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004647 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004648 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004649 /**
4650 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004651 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004652 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004653 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004654 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004655 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004656 "(capture request %d, HAL device: %s (%d)",
4657 halRequest->frame_number, strerror(-res), res);
4658 return INVALID_OPERATION;
4659 }
4660
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004661 {
4662 // Correct metadata regions for distortion correction if enabled
4663 sp<Camera3Device> parent = mParent.promote();
4664 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004665 List<PhysicalCameraSettings>::iterator it;
4666 for (it = captureRequest->mSettingsList.begin();
4667 it != captureRequest->mSettingsList.end(); it++) {
4668 if (parent->mDistortionMappers.find(it->cameraId) ==
4669 parent->mDistortionMappers.end()) {
4670 continue;
4671 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004672
4673 if (!captureRequest->mDistortionCorrectionUpdated) {
4674 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4675 &(it->metadata));
4676 if (res != OK) {
4677 SET_ERR("RequestThread: Unable to correct capture requests "
4678 "for lens distortion for request %d: %s (%d)",
4679 halRequest->frame_number, strerror(-res), res);
4680 return INVALID_OPERATION;
4681 }
4682 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004683 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004684 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004685
4686 for (it = captureRequest->mSettingsList.begin();
4687 it != captureRequest->mSettingsList.end(); it++) {
4688 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4689 parent->mZoomRatioMappers.end()) {
4690 continue;
4691 }
4692
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004693 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004694 cameraIdsWithZoom.insert(it->cameraId);
4695 }
4696
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004697 if (!captureRequest->mZoomRatioUpdated) {
4698 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4699 &(it->metadata));
4700 if (res != OK) {
4701 SET_ERR("RequestThread: Unable to correct capture requests "
4702 "for zoom ratio for request %d: %s (%d)",
4703 halRequest->frame_number, strerror(-res), res);
4704 return INVALID_OPERATION;
4705 }
4706 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004707 }
4708 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004709 if (captureRequest->mRotateAndCropAuto &&
4710 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004711 for (it = captureRequest->mSettingsList.begin();
4712 it != captureRequest->mSettingsList.end(); it++) {
4713 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4714 if (mapper != parent->mRotateAndCropMappers.end()) {
4715 res = mapper->second.updateCaptureRequest(&(it->metadata));
4716 if (res != OK) {
4717 SET_ERR("RequestThread: Unable to correct capture requests "
4718 "for rotate-and-crop for request %d: %s (%d)",
4719 halRequest->frame_number, strerror(-res), res);
4720 return INVALID_OPERATION;
4721 }
4722 }
4723 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004724 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004725 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004726 }
4727 }
4728
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004729 /**
4730 * The request should be presorted so accesses in HAL
4731 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4732 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004733 captureRequest->mSettingsList.begin()->metadata.sort();
4734 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004735 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004736 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004737 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4738
4739 IF_ALOGV() {
4740 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4741 find_camera_metadata_ro_entry(
4742 halRequest->settings,
4743 ANDROID_CONTROL_AF_TRIGGER,
4744 &e
4745 );
4746 if (e.count > 0) {
4747 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4748 __FUNCTION__,
4749 halRequest->frame_number,
4750 e.data.u8[0]);
4751 }
4752 }
4753 } else {
4754 // leave request.settings NULL to indicate 'reuse latest given'
4755 ALOGVV("%s: Request settings are REUSED",
4756 __FUNCTION__);
4757 }
4758
Emilian Peevaebbe412018-01-15 13:53:24 +00004759 if (captureRequest->mSettingsList.size() > 1) {
4760 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4761 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004762 if (newRequest) {
4763 halRequest->physcam_settings =
4764 new const camera_metadata* [halRequest->num_physcam_settings];
4765 } else {
4766 halRequest->physcam_settings = nullptr;
4767 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004768 auto it = ++captureRequest->mSettingsList.begin();
4769 size_t i = 0;
4770 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4771 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004772 if (newRequest) {
4773 it->metadata.sort();
4774 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4775 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004776 }
4777 }
4778
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 uint32_t totalNumBuffers = 0;
4780
4781 // Fill in buffers
4782 if (captureRequest->mInputStream != NULL) {
4783 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004784
4785 halRequest->input_width = captureRequest->mInputBufferSize.width;
4786 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004787 totalNumBuffers += 1;
4788 } else {
4789 halRequest->input_buffer = NULL;
4790 }
4791
Emilian Peevf4816702020-04-03 15:44:51 -07004792 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 captureRequest->mOutputStreams.size());
4794 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004795 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004796
4797 sp<Camera3Device> parent = mParent.promote();
4798 if (parent == NULL) {
4799 // Should not happen, and nowhere to send errors to, so just log it
4800 CLOGE("RequestThread: Parent is gone");
4801 return INVALID_OPERATION;
4802 }
4803 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4804
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004805 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004806 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004807 sp<Camera3OutputStreamInterface> outputStream =
4808 captureRequest->mOutputStreams.editItemAt(j);
4809 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004810
4811 // Prepare video buffers for high speed recording on the first video request.
4812 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4813 // Only try to prepare video stream on the first video request.
4814 mPrepareVideoStream = false;
4815
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004816 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4817 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004818 while (res == NOT_ENOUGH_DATA) {
4819 res = outputStream->prepareNextBuffer();
4820 }
4821 if (res != OK) {
4822 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4823 __FUNCTION__, strerror(-res), res);
4824 outputStream->cancelPrepare();
4825 }
4826 }
4827
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004828 std::vector<size_t> uniqueSurfaceIds;
4829 res = outputStream->getUniqueSurfaceIds(
4830 captureRequest->mOutputSurfaces[streamId],
4831 &uniqueSurfaceIds);
4832 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4833 if (res != OK && res != INVALID_OPERATION) {
4834 ALOGE("%s: failed to query stream %d unique surface IDs",
4835 __FUNCTION__, streamId);
4836 return res;
4837 }
4838 if (res == OK) {
4839 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4840 }
4841
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004842 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004843 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004844 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004845 return TIMED_OUT;
4846 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004847 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004848 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004849 buffer.stream = outputStream->asHalStream();
4850 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004851 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004852 buffer.acquire_fence = -1;
4853 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004854 // Mark the output stream as unpreparable to block clients from calling
4855 // 'prepare' after this request reaches CameraHal and before the respective
4856 // buffers are requested.
4857 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004858 } else {
4859 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4860 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004861 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004862 if (res != OK) {
4863 // Can't get output buffer from gralloc queue - this could be due to
4864 // abandoned queue or other consumer misbehavior, so not a fatal
4865 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004866 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004867 " %s (%d)", strerror(-res), res);
4868
4869 return TIMED_OUT;
4870 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004871 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004872
4873 {
4874 sp<Camera3Device> parent = mParent.promote();
4875 if (parent != nullptr) {
4876 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4877 for (const auto& settings : captureRequest->mSettingsList) {
4878 if ((streamCameraId.isEmpty() &&
4879 parent->getId() == settings.cameraId.c_str()) ||
4880 streamCameraId == settings.cameraId.c_str()) {
4881 outputStream->fireBufferRequestForFrameNumber(
4882 captureRequest->mResultExtras.frameNumber,
4883 settings.metadata);
4884 }
4885 }
4886 }
4887 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004888
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004889 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08004890 int32_t streamGroupId = outputStream->getHalStreamGroupId();
4891 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
4892 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
4893 } else if (!physicalCameraId.isEmpty()) {
4894 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004895 }
4896 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004897 }
4898 totalNumBuffers += halRequest->num_output_buffers;
4899
4900 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004901 // If this request list is for constrained high speed recording (not
4902 // preview), and the current request is not the last one in the batch,
4903 // do not send callback to the app.
4904 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004905 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004906 hasCallback = false;
4907 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004908 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004909 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004910 const camera_metadata_t* settings = halRequest->settings;
4911 bool shouldUnlockSettings = false;
4912 if (settings == nullptr) {
4913 shouldUnlockSettings = true;
4914 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4915 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004916 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4917 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004918 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004919 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4920 isStillCapture = true;
4921 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4922 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004923
Emilian Peevaf8416e2021-02-04 17:52:43 -08004924 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004925 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004926 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4927 isZslCapture = true;
4928 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004929 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004930 res = parent->registerInFlight(halRequest->frame_number,
4931 totalNumBuffers, captureRequest->mResultExtras,
4932 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004933 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004934 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004935 requestedPhysicalCameras, isStillCapture, isZslCapture,
4936 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004937 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004938 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004939 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4940 ", burstId = %" PRId32 ".",
4941 __FUNCTION__,
4942 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4943 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004944
4945 if (shouldUnlockSettings) {
4946 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4947 }
4948
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004949 if (res != OK) {
4950 SET_ERR("RequestThread: Unable to register new in-flight request:"
4951 " %s (%d)", strerror(-res), res);
4952 return INVALID_OPERATION;
4953 }
4954 }
4955
4956 return OK;
4957}
4958
Igor Murashkin1e479c02013-09-06 16:55:14 -07004959CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004960 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004961 Mutex::Autolock al(mLatestRequestMutex);
4962
4963 ALOGV("RequestThread::%s", __FUNCTION__);
4964
4965 return mLatestRequest;
4966}
4967
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004968bool Camera3Device::RequestThread::isStreamPending(
4969 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004970 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004971 Mutex::Autolock l(mRequestLock);
4972
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004973 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004974 if (!nextRequest.submitted) {
4975 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4976 if (stream == s) return true;
4977 }
4978 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004979 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004980 }
4981
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004982 for (const auto& request : mRequestQueue) {
4983 for (const auto& s : request->mOutputStreams) {
4984 if (stream == s) return true;
4985 }
4986 if (stream == request->mInputStream) return true;
4987 }
4988
4989 for (const auto& request : mRepeatingRequests) {
4990 for (const auto& s : request->mOutputStreams) {
4991 if (stream == s) return true;
4992 }
4993 if (stream == request->mInputStream) return true;
4994 }
4995
4996 return false;
4997}
Jianing Weicb0652e2014-03-12 18:29:36 -07004998
Emilian Peev40ead602017-09-26 15:46:36 +01004999bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5000 ATRACE_CALL();
5001 Mutex::Autolock l(mRequestLock);
5002
5003 for (const auto& nextRequest : mNextRequests) {
5004 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5005 if (s.first == streamId) {
5006 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5007 if (it != s.second.end()) {
5008 return true;
5009 }
5010 }
5011 }
5012 }
5013
5014 for (const auto& request : mRequestQueue) {
5015 for (const auto& s : request->mOutputSurfaces) {
5016 if (s.first == streamId) {
5017 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5018 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005019 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005020 }
5021 }
5022 }
5023 }
5024
5025 for (const auto& request : mRepeatingRequests) {
5026 for (const auto& s : request->mOutputSurfaces) {
5027 if (s.first == streamId) {
5028 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5029 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005030 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005031 }
5032 }
5033 }
5034 }
5035
5036 return false;
5037}
5038
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005039void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5040 if (!mUseHalBufManager) {
5041 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5042 return;
5043 }
5044
5045 Mutex::Autolock pl(mPauseLock);
5046 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005047 mInterface->signalPipelineDrain(streamIds);
5048 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005049 }
5050 // If request thread is still busy, wait until paused then notify HAL
5051 mNotifyPipelineDrain = true;
5052 mStreamIdsToBeDrained = streamIds;
5053}
5054
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005055void Camera3Device::RequestThread::resetPipelineDrain() {
5056 Mutex::Autolock pl(mPauseLock);
5057 mNotifyPipelineDrain = false;
5058 mStreamIdsToBeDrained.clear();
5059}
5060
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005061void Camera3Device::RequestThread::clearPreviousRequest() {
5062 Mutex::Autolock l(mRequestLock);
5063 mPrevRequest.clear();
5064}
5065
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005066status_t Camera3Device::RequestThread::switchToOffline(
5067 const std::vector<int32_t>& streamsToKeep,
5068 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005069 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5070 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005071 Mutex::Autolock l(mRequestLock);
5072 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5073
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005074 // Wait until request thread is fully stopped
5075 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5076
5077 // We could also check for mRepeatingRequests.empty(), but the API interface
5078 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5079 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005080 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5081 while (!queueEmpty) {
5082 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5083 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005084 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005085 return res;
5086 } else if (res != OK) {
5087 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5088 __FUNCTION__, strerror(-res), res);
5089 return res;
5090 }
5091 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5092 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005093
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005094 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005095 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005096}
5097
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005098status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5099 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5100 ATRACE_CALL();
5101 Mutex::Autolock l(mTriggerMutex);
5102 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5103 return BAD_VALUE;
5104 }
5105 mRotateAndCropOverride = rotateAndCropValue;
5106 return OK;
5107}
5108
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005109status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
5110 ATRACE_CALL();
5111 Mutex::Autolock l(mTriggerMutex);
5112 if (enabled != mCameraMute) {
5113 mCameraMute = enabled;
5114 mCameraMuteChanged = true;
5115 }
5116 return OK;
5117}
5118
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005119nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005120 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005121 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005122 return mExpectedInflightDuration > kMinInflightDuration ?
5123 mExpectedInflightDuration : kMinInflightDuration;
5124}
5125
Emilian Peevaebbe412018-01-15 13:53:24 +00005126void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005127 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005128 if ((request == nullptr) || (halRequest == nullptr)) {
5129 ALOGE("%s: Invalid request!", __FUNCTION__);
5130 return;
5131 }
5132
5133 if (halRequest->num_physcam_settings > 0) {
5134 if (halRequest->physcam_id != nullptr) {
5135 delete [] halRequest->physcam_id;
5136 halRequest->physcam_id = nullptr;
5137 }
5138 if (halRequest->physcam_settings != nullptr) {
5139 auto it = ++(request->mSettingsList.begin());
5140 size_t i = 0;
5141 for (; it != request->mSettingsList.end(); it++, i++) {
5142 it->metadata.unlock(halRequest->physcam_settings[i]);
5143 }
5144 delete [] halRequest->physcam_settings;
5145 halRequest->physcam_settings = nullptr;
5146 }
5147 }
5148}
5149
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005150void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5151 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005152 return;
5153 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005155 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005156 // Skip the ones that have been submitted successfully.
5157 if (nextRequest.submitted) {
5158 continue;
5159 }
5160
5161 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005162 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5163 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005164
5165 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005166 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005167 }
5168
Emilian Peevaebbe412018-01-15 13:53:24 +00005169 cleanupPhysicalSettings(captureRequest, halRequest);
5170
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005171 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005172 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005173 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5174 }
5175
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005176 // No output buffer can be returned when using HAL buffer manager
5177 if (!mUseHalBufManager) {
5178 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5179 //Buffers that failed processing could still have
5180 //valid acquire fence.
5181 int acquireFence = (*outputBuffers)[i].acquire_fence;
5182 if (0 <= acquireFence) {
5183 close(acquireFence);
5184 outputBuffers->editItemAt(i).acquire_fence = -1;
5185 }
Emilian Peevf4816702020-04-03 15:44:51 -07005186 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005187 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5188 /*timestampIncreasing*/true, std::vector<size_t> (),
5189 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005190 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005191 }
5192
5193 if (sendRequestError) {
5194 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005195 sp<NotificationListener> listener = mListener.promote();
5196 if (listener != NULL) {
5197 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005198 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005199 captureRequest->mResultExtras);
5200 }
5201 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005202
5203 // Remove yet-to-be submitted inflight request from inflightMap
5204 {
5205 sp<Camera3Device> parent = mParent.promote();
5206 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005207 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005208 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5209 if (idx >= 0) {
5210 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5211 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5212 parent->removeInFlightMapEntryLocked(idx);
5213 }
5214 }
5215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005216 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005217
5218 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005219 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005220}
5221
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005222void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005223 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 // Optimized a bit for the simple steady-state case (single repeating
5225 // request), to avoid putting that request in the queue temporarily.
5226 Mutex::Autolock l(mRequestLock);
5227
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005228 assert(mNextRequests.empty());
5229
5230 NextRequest nextRequest;
5231 nextRequest.captureRequest = waitForNextRequestLocked();
5232 if (nextRequest.captureRequest == nullptr) {
5233 return;
5234 }
5235
Emilian Peevf4816702020-04-03 15:44:51 -07005236 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005237 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005238 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005239
5240 // Wait for additional requests
5241 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5242
5243 for (size_t i = 1; i < batchSize; i++) {
5244 NextRequest additionalRequest;
5245 additionalRequest.captureRequest = waitForNextRequestLocked();
5246 if (additionalRequest.captureRequest == nullptr) {
5247 break;
5248 }
5249
Emilian Peevf4816702020-04-03 15:44:51 -07005250 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005251 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005252 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005253 }
5254
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005255 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005256 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005257 mNextRequests.size(), batchSize);
5258 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005259 }
5260
5261 return;
5262}
5263
5264sp<Camera3Device::CaptureRequest>
5265 Camera3Device::RequestThread::waitForNextRequestLocked() {
5266 status_t res;
5267 sp<CaptureRequest> nextRequest;
5268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005269 while (mRequestQueue.empty()) {
5270 if (!mRepeatingRequests.empty()) {
5271 // Always atomically enqueue all requests in a repeating request
5272 // list. Guarantees a complete in-sequence set of captures to
5273 // application.
5274 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005275 if (mFirstRepeating) {
5276 mFirstRepeating = false;
5277 } else {
5278 for (auto& request : requests) {
5279 // For repeating requests, override timestamp request using
5280 // the time a request is inserted into the request queue,
5281 // because the original repeating request will have an old
5282 // fixed timestamp.
5283 request->mRequestTimeNs = systemTime();
5284 }
5285 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005286 RequestList::const_iterator firstRequest =
5287 requests.begin();
5288 nextRequest = *firstRequest;
5289 mRequestQueue.insert(mRequestQueue.end(),
5290 ++firstRequest,
5291 requests.end());
5292 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005293
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005294 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005295
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005296 break;
5297 }
5298
5299 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5300
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005301 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5302 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005303 Mutex::Autolock pl(mPauseLock);
5304 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005305 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005306 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005307 if (mNotifyPipelineDrain) {
5308 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5309 mNotifyPipelineDrain = false;
5310 mStreamIdsToBeDrained.clear();
5311 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005312 // Let the tracker know
5313 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5314 if (statusTracker != 0) {
5315 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5316 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005317 sp<Camera3Device> parent = mParent.promote();
5318 if (parent != nullptr) {
5319 parent->mRequestBufferSM.onRequestThreadPaused();
5320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005321 }
5322 // Stop waiting for now and let thread management happen
5323 return NULL;
5324 }
5325 }
5326
5327 if (nextRequest == NULL) {
5328 // Don't have a repeating request already in hand, so queue
5329 // must have an entry now.
5330 RequestList::iterator firstRequest =
5331 mRequestQueue.begin();
5332 nextRequest = *firstRequest;
5333 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005334 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5335 sp<NotificationListener> listener = mListener.promote();
5336 if (listener != NULL) {
5337 listener->notifyRequestQueueEmpty();
5338 }
5339 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005340 }
5341
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005342 // In case we've been unpaused by setPaused clearing mDoPause, need to
5343 // update internal pause state (capture/setRepeatingRequest unpause
5344 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005345 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005346 if (mPaused) {
5347 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5348 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5349 if (statusTracker != 0) {
5350 statusTracker->markComponentActive(mStatusId);
5351 }
5352 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005353 mPaused = false;
5354
5355 // Check if we've reconfigured since last time, and reset the preview
5356 // request if so. Can't use 'NULL request == repeat' across configure calls.
5357 if (mReconfigured) {
5358 mPrevRequest.clear();
5359 mReconfigured = false;
5360 }
5361
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005362 if (nextRequest != NULL) {
5363 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005364 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5365 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005366
5367 // Since RequestThread::clear() removes buffers from the input stream,
5368 // get the right buffer here before unlocking mRequestLock
5369 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005370 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5371 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005372 if (res != OK) {
5373 // Can't get input buffer from gralloc queue - this could be due to
5374 // disconnected queue or other producer misbehavior, so not a fatal
5375 // error
5376 ALOGE("%s: Can't get input buffer, skipping request:"
5377 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005378
5379 sp<NotificationListener> listener = mListener.promote();
5380 if (listener != NULL) {
5381 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005382 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005383 nextRequest->mResultExtras);
5384 }
5385 return NULL;
5386 }
5387 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005388 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005389
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005390 return nextRequest;
5391}
5392
5393bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005394 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005395 status_t res;
5396 Mutex::Autolock l(mPauseLock);
5397 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005398 if (mPaused == false) {
5399 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005400 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005401 if (mNotifyPipelineDrain) {
5402 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5403 mNotifyPipelineDrain = false;
5404 mStreamIdsToBeDrained.clear();
5405 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005406 // Let the tracker know
5407 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5408 if (statusTracker != 0) {
5409 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5410 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005411 sp<Camera3Device> parent = mParent.promote();
5412 if (parent != nullptr) {
5413 parent->mRequestBufferSM.onRequestThreadPaused();
5414 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005415 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005416
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005417 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005418 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005419 return true;
5420 }
5421 }
5422 // We don't set mPaused to false here, because waitForNextRequest needs
5423 // to further manage the paused state in case of starvation.
5424 return false;
5425}
5426
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005427void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005428 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005429 // With work to do, mark thread as unpaused.
5430 // If paused by request (setPaused), don't resume, to avoid
5431 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005432 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005433 Mutex::Autolock p(mPauseLock);
5434 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005435 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5436 if (mPaused) {
5437 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5438 if (statusTracker != 0) {
5439 statusTracker->markComponentActive(mStatusId);
5440 }
5441 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005442 mPaused = false;
5443 }
5444}
5445
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005446void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5447 sp<Camera3Device> parent = mParent.promote();
5448 if (parent != NULL) {
5449 va_list args;
5450 va_start(args, fmt);
5451
5452 parent->setErrorStateV(fmt, args);
5453
5454 va_end(args);
5455 }
5456}
5457
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005458status_t Camera3Device::RequestThread::insertTriggers(
5459 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005460 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005461 Mutex::Autolock al(mTriggerMutex);
5462
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005463 sp<Camera3Device> parent = mParent.promote();
5464 if (parent == NULL) {
5465 CLOGE("RequestThread: Parent is gone");
5466 return DEAD_OBJECT;
5467 }
5468
Emilian Peevaebbe412018-01-15 13:53:24 +00005469 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005470 size_t count = mTriggerMap.size();
5471
5472 for (size_t i = 0; i < count; ++i) {
5473 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005474 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005475
5476 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5477 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5478 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005479 if (isAeTrigger) {
5480 request->mResultExtras.precaptureTriggerId = triggerId;
5481 mCurrentPreCaptureTriggerId = triggerId;
5482 } else {
5483 request->mResultExtras.afTriggerId = triggerId;
5484 mCurrentAfTriggerId = triggerId;
5485 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005486 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005487 }
5488
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005489 camera_metadata_entry entry = metadata.find(tag);
5490
5491 if (entry.count > 0) {
5492 /**
5493 * Already has an entry for this trigger in the request.
5494 * Rewrite it with our requested trigger value.
5495 */
5496 RequestTrigger oldTrigger = trigger;
5497
5498 oldTrigger.entryValue = entry.data.u8[0];
5499
5500 mTriggerReplacedMap.add(tag, oldTrigger);
5501 } else {
5502 /**
5503 * More typical, no trigger entry, so we just add it
5504 */
5505 mTriggerRemovedMap.add(tag, trigger);
5506 }
5507
5508 status_t res;
5509
5510 switch (trigger.getTagType()) {
5511 case TYPE_BYTE: {
5512 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5513 res = metadata.update(tag,
5514 &entryValue,
5515 /*count*/1);
5516 break;
5517 }
5518 case TYPE_INT32:
5519 res = metadata.update(tag,
5520 &trigger.entryValue,
5521 /*count*/1);
5522 break;
5523 default:
5524 ALOGE("%s: Type not supported: 0x%x",
5525 __FUNCTION__,
5526 trigger.getTagType());
5527 return INVALID_OPERATION;
5528 }
5529
5530 if (res != OK) {
5531 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5532 ", value %d", __FUNCTION__, trigger.getTagName(),
5533 trigger.entryValue);
5534 return res;
5535 }
5536
5537 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5538 trigger.getTagName(),
5539 trigger.entryValue);
5540 }
5541
5542 mTriggerMap.clear();
5543
5544 return count;
5545}
5546
5547status_t Camera3Device::RequestThread::removeTriggers(
5548 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005549 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005550 Mutex::Autolock al(mTriggerMutex);
5551
Emilian Peevaebbe412018-01-15 13:53:24 +00005552 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005553
5554 /**
5555 * Replace all old entries with their old values.
5556 */
5557 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5558 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5559
5560 status_t res;
5561
5562 uint32_t tag = trigger.metadataTag;
5563 switch (trigger.getTagType()) {
5564 case TYPE_BYTE: {
5565 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5566 res = metadata.update(tag,
5567 &entryValue,
5568 /*count*/1);
5569 break;
5570 }
5571 case TYPE_INT32:
5572 res = metadata.update(tag,
5573 &trigger.entryValue,
5574 /*count*/1);
5575 break;
5576 default:
5577 ALOGE("%s: Type not supported: 0x%x",
5578 __FUNCTION__,
5579 trigger.getTagType());
5580 return INVALID_OPERATION;
5581 }
5582
5583 if (res != OK) {
5584 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5585 ", trigger value %d", __FUNCTION__,
5586 trigger.getTagName(), trigger.entryValue);
5587 return res;
5588 }
5589 }
5590 mTriggerReplacedMap.clear();
5591
5592 /**
5593 * Remove all new entries.
5594 */
5595 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5596 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5597 status_t res = metadata.erase(trigger.metadataTag);
5598
5599 if (res != OK) {
5600 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5601 ", trigger value %d", __FUNCTION__,
5602 trigger.getTagName(), trigger.entryValue);
5603 return res;
5604 }
5605 }
5606 mTriggerRemovedMap.clear();
5607
5608 return OK;
5609}
5610
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005611status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005612 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005613 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005614 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005615 status_t res;
5616
Emilian Peevaebbe412018-01-15 13:53:24 +00005617 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005618
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005619 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005620 // exists
5621 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5622 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5623 if (afTrigger.count > 0 &&
5624 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5625 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005626 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005627 if (res != OK) return res;
5628 }
5629
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005630 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005631 // if none already exists
5632 camera_metadata_entry pcTrigger =
5633 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5634 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5635 if (pcTrigger.count > 0 &&
5636 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5637 pcId.count == 0) {
5638 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005639 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005640 if (res != OK) return res;
5641 }
5642
5643 return OK;
5644}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005645
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005646bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5647 const sp<CaptureRequest> &request) {
5648 ATRACE_CALL();
5649
5650 if (request->mRotateAndCropAuto) {
5651 Mutex::Autolock l(mTriggerMutex);
5652 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5653
5654 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5655 if (rotateAndCropEntry.count > 0) {
5656 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5657 return false;
5658 } else {
5659 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5660 return true;
5661 }
5662 } else {
5663 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5664 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5665 &rotateAndCrop_u8, 1);
5666 return true;
5667 }
5668 }
5669 return false;
5670}
5671
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005672bool Camera3Device::RequestThread::overrideTestPattern(
5673 const sp<CaptureRequest> &request) {
5674 ATRACE_CALL();
5675
5676 Mutex::Autolock l(mTriggerMutex);
5677
5678 bool changed = false;
5679
5680 int32_t testPatternMode = request->mOriginalTestPatternMode;
5681 int32_t testPatternData[4] = {
5682 request->mOriginalTestPatternData[0],
5683 request->mOriginalTestPatternData[1],
5684 request->mOriginalTestPatternData[2],
5685 request->mOriginalTestPatternData[3]
5686 };
5687
5688 if (mCameraMute) {
5689 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5690 testPatternData[0] = 0;
5691 testPatternData[1] = 0;
5692 testPatternData[2] = 0;
5693 testPatternData[3] = 0;
5694 }
5695
5696 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5697
5698 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5699 if (testPatternEntry.count > 0) {
5700 if (testPatternEntry.data.i32[0] != testPatternMode) {
5701 testPatternEntry.data.i32[0] = testPatternMode;
5702 changed = true;
5703 }
5704 } else {
5705 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5706 &testPatternMode, 1);
5707 changed = true;
5708 }
5709
5710 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5711 if (testPatternColor.count > 0) {
5712 for (size_t i = 0; i < 4; i++) {
5713 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5714 testPatternColor.data.i32[i] = testPatternData[i];
5715 changed = true;
5716 }
5717 }
5718 } else {
5719 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5720 (int32_t*)testPatternData, 4);
5721 changed = true;
5722 }
5723
5724 return changed;
5725}
5726
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005727/**
5728 * PreparerThread inner class methods
5729 */
5730
5731Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005732 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005733 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005734}
5735
5736Camera3Device::PreparerThread::~PreparerThread() {
5737 Thread::requestExitAndWait();
5738 if (mCurrentStream != nullptr) {
5739 mCurrentStream->cancelPrepare();
5740 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5741 mCurrentStream.clear();
5742 }
5743 clear();
5744}
5745
Ruben Brunkc78ac262015-08-13 17:58:46 -07005746status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005747 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005748 status_t res;
5749
5750 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005751 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005752
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005753 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005754 if (res == OK) {
5755 // No preparation needed, fire listener right off
5756 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005757 if (listener != NULL) {
5758 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005759 }
5760 return OK;
5761 } else if (res != NOT_ENOUGH_DATA) {
5762 return res;
5763 }
5764
5765 // Need to prepare, start up thread if necessary
5766 if (!mActive) {
5767 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5768 // isn't running
5769 Thread::requestExitAndWait();
5770 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5771 if (res != OK) {
5772 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005773 if (listener != NULL) {
5774 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005775 }
5776 return res;
5777 }
5778 mCancelNow = false;
5779 mActive = true;
5780 ALOGV("%s: Preparer stream started", __FUNCTION__);
5781 }
5782
5783 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005784 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005785 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5786
5787 return OK;
5788}
5789
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005790void Camera3Device::PreparerThread::pause() {
5791 ATRACE_CALL();
5792
5793 Mutex::Autolock l(mLock);
5794
5795 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5796 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5797 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5798 int currentMaxCount = mCurrentMaxCount;
5799 mPendingStreams.clear();
5800 mCancelNow = true;
5801 while (mActive) {
5802 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5803 if (res == TIMED_OUT) {
5804 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5805 return;
5806 } else if (res != OK) {
5807 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5808 return;
5809 }
5810 }
5811
5812 //Check whether the prepare thread was able to complete the current
5813 //stream. In case work is still pending emplace it along with the rest
5814 //of the streams in the pending list.
5815 if (currentStream != nullptr) {
5816 if (!mCurrentPrepareComplete) {
5817 pendingStreams.emplace(currentMaxCount, currentStream);
5818 }
5819 }
5820
5821 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5822 for (const auto& it : mPendingStreams) {
5823 it.second->cancelPrepare();
5824 }
5825}
5826
5827status_t Camera3Device::PreparerThread::resume() {
5828 ATRACE_CALL();
5829 status_t res;
5830
5831 Mutex::Autolock l(mLock);
5832 sp<NotificationListener> listener = mListener.promote();
5833
5834 if (mActive) {
5835 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5836 return NO_INIT;
5837 }
5838
5839 auto it = mPendingStreams.begin();
5840 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005841 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005842 if (res == OK) {
5843 if (listener != NULL) {
5844 listener->notifyPrepared(it->second->getId());
5845 }
5846 it = mPendingStreams.erase(it);
5847 } else if (res != NOT_ENOUGH_DATA) {
5848 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5849 res, strerror(-res));
5850 it = mPendingStreams.erase(it);
5851 } else {
5852 it++;
5853 }
5854 }
5855
5856 if (mPendingStreams.empty()) {
5857 return OK;
5858 }
5859
5860 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5861 if (res != OK) {
5862 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5863 __FUNCTION__, res, strerror(-res));
5864 return res;
5865 }
5866 mCancelNow = false;
5867 mActive = true;
5868 ALOGV("%s: Preparer stream started", __FUNCTION__);
5869
5870 return OK;
5871}
5872
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005873status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005874 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005875 Mutex::Autolock l(mLock);
5876
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005877 for (const auto& it : mPendingStreams) {
5878 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005879 }
5880 mPendingStreams.clear();
5881 mCancelNow = true;
5882
5883 return OK;
5884}
5885
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005886void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005887 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005888 Mutex::Autolock l(mLock);
5889 mListener = listener;
5890}
5891
5892bool Camera3Device::PreparerThread::threadLoop() {
5893 status_t res;
5894 {
5895 Mutex::Autolock l(mLock);
5896 if (mCurrentStream == nullptr) {
5897 // End thread if done with work
5898 if (mPendingStreams.empty()) {
5899 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5900 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5901 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5902 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005903 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005904 return false;
5905 }
5906
5907 // Get next stream to prepare
5908 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005909 mCurrentStream = it->second;
5910 mCurrentMaxCount = it->first;
5911 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005912 mPendingStreams.erase(it);
5913 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5914 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5915 } else if (mCancelNow) {
5916 mCurrentStream->cancelPrepare();
5917 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5918 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5919 mCurrentStream.clear();
5920 mCancelNow = false;
5921 return true;
5922 }
5923 }
5924
5925 res = mCurrentStream->prepareNextBuffer();
5926 if (res == NOT_ENOUGH_DATA) return true;
5927 if (res != OK) {
5928 // Something bad happened; try to recover by cancelling prepare and
5929 // signalling listener anyway
5930 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5931 mCurrentStream->getId(), res, strerror(-res));
5932 mCurrentStream->cancelPrepare();
5933 }
5934
5935 // This stream has finished, notify listener
5936 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005937 sp<NotificationListener> listener = mListener.promote();
5938 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005939 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5940 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005941 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005942 }
5943
5944 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5945 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005946 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005947
5948 return true;
5949}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005950
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005951status_t Camera3Device::RequestBufferStateMachine::initialize(
5952 sp<camera3::StatusTracker> statusTracker) {
5953 if (statusTracker == nullptr) {
5954 ALOGE("%s: statusTracker is null", __FUNCTION__);
5955 return BAD_VALUE;
5956 }
5957
5958 std::lock_guard<std::mutex> lock(mLock);
5959 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005960 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005961 return OK;
5962}
5963
5964bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5965 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005966 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005967 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005968 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005969 return true;
5970 }
5971 return false;
5972}
5973
5974void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5975 std::lock_guard<std::mutex> lock(mLock);
5976 if (!mRequestBufferOngoing) {
5977 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5978 return;
5979 }
5980 mRequestBufferOngoing = false;
5981 if (mStatus == RB_STATUS_PENDING_STOP) {
5982 checkSwitchToStopLocked();
5983 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005984 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005985}
5986
5987void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5988 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005989 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005990 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005991 return;
5992}
5993
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005994void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005995 std::lock_guard<std::mutex> lock(mLock);
5996 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005997 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5998 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005999 mInflightMapEmpty = false;
6000 if (mStatus == RB_STATUS_STOPPED) {
6001 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006002 }
6003 return;
6004}
6005
6006void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6007 std::lock_guard<std::mutex> lock(mLock);
6008 mRequestThreadPaused = true;
6009 if (mStatus == RB_STATUS_PENDING_STOP) {
6010 checkSwitchToStopLocked();
6011 }
6012 return;
6013}
6014
6015void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6016 std::lock_guard<std::mutex> lock(mLock);
6017 mInflightMapEmpty = true;
6018 if (mStatus == RB_STATUS_PENDING_STOP) {
6019 checkSwitchToStopLocked();
6020 }
6021 return;
6022}
6023
6024void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6025 std::lock_guard<std::mutex> lock(mLock);
6026 if (!checkSwitchToStopLocked()) {
6027 mStatus = RB_STATUS_PENDING_STOP;
6028 }
6029 return;
6030}
6031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006032bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6033 std::lock_guard<std::mutex> lock(mLock);
6034 if (mRequestBufferOngoing) {
6035 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6036 __FUNCTION__);
6037 return false;
6038 }
6039 mSwitchedToOffline = true;
6040 mInflightMapEmpty = true;
6041 mRequestThreadPaused = true;
6042 mStatus = RB_STATUS_STOPPED;
6043 return true;
6044}
6045
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006046void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6047 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6048 if (statusTracker != nullptr) {
6049 if (active) {
6050 statusTracker->markComponentActive(mRequestBufferStatusId);
6051 } else {
6052 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6053 }
6054 }
6055}
6056
6057bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6058 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6059 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006060 return true;
6061 }
6062 return false;
6063}
6064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006065bool Camera3Device::startRequestBuffer() {
6066 return mRequestBufferSM.startRequestBuffer();
6067}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006069void Camera3Device::endRequestBuffer() {
6070 mRequestBufferSM.endRequestBuffer();
6071}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006072
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006073nsecs_t Camera3Device::getWaitDuration() {
6074 return kBaseGetBufferWait + getExpectedInFlightDuration();
6075}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006076
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006077void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6078 mInterface->getInflightBufferKeys(out);
6079}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006080
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006081void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6082 mInterface->getInflightRequestBufferKeys(out);
6083}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006084
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006085std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6086 std::vector<sp<Camera3StreamInterface>> ret;
6087 bool hasInputStream = mInputStream != nullptr;
6088 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6089 if (hasInputStream) {
6090 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006091 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006092 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6093 ret.push_back(mOutputStreams[i]);
6094 }
6095 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6096 ret.push_back(mDeletedStreams[i]);
6097 }
6098 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006099}
6100
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006101status_t Camera3Device::switchToOffline(
6102 const std::vector<int32_t>& streamsToKeep,
6103 /*out*/ sp<CameraOfflineSessionBase>* session) {
6104 ATRACE_CALL();
6105 if (session == nullptr) {
6106 ALOGE("%s: session must not be null", __FUNCTION__);
6107 return BAD_VALUE;
6108 }
6109
6110 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006111
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006112 bool hasInputStream = mInputStream != nullptr;
6113 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6114 bool inputStreamSupportsOffline = hasInputStream ?
6115 mInputStream->getOfflineProcessingSupport() : false;
6116 auto outputStreamIds = mOutputStreams.getStreamIds();
6117 auto streamIds = outputStreamIds;
6118 if (hasInputStream) {
6119 streamIds.push_back(mInputStream->getId());
6120 }
6121
6122 // Check all streams in streamsToKeep supports offline mode
6123 for (auto id : streamsToKeep) {
6124 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6125 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6126 return BAD_VALUE;
6127 } else if (id == inputStreamId) {
6128 if (!inputStreamSupportsOffline) {
6129 ALOGE("%s: input stream %d cannot be switched to offline",
6130 __FUNCTION__, id);
6131 return BAD_VALUE;
6132 }
6133 } else {
6134 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6135 if (!stream->getOfflineProcessingSupport()) {
6136 ALOGE("%s: output stream %d cannot be switched to offline",
6137 __FUNCTION__, id);
6138 return BAD_VALUE;
6139 }
6140 }
6141 }
6142
6143 // TODO: block surface sharing and surface group streams until we can support them
6144
6145 // Stop repeating request, wait until all remaining requests are submitted, then call into
6146 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006147 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6148 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006149 camera3::BufferRecords bufferRecords;
6150 status_t ret = mRequestThread->switchToOffline(
6151 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006152
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006153 if (ret != OK) {
6154 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6155 return ret;
6156 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006157
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006158 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6159 if (!succ) {
6160 SET_ERR("HAL must not be calling requestStreamBuffers call");
6161 // TODO: block ALL callbacks from HAL till app configured new streams?
6162 return UNKNOWN_ERROR;
6163 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006164
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006165 // Verify offlineSessionInfo
6166 std::vector<int32_t> offlineStreamIds;
6167 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6168 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6169 // verify stream IDs
6170 int32_t id = offlineStream.id;
6171 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6172 SET_ERR("stream ID %d not found!", id);
6173 return UNKNOWN_ERROR;
6174 }
6175
6176 // When not using HAL buf manager, only allow streams requested by app to be preserved
6177 if (!mUseHalBufManager) {
6178 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6179 SET_ERR("stream ID %d must not be switched to offline!", id);
6180 return UNKNOWN_ERROR;
6181 }
6182 }
6183
6184 offlineStreamIds.push_back(id);
6185 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6186 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6187 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6188 // Verify number of outstanding buffers
6189 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6190 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6191 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6192 return UNKNOWN_ERROR;
6193 }
6194 }
6195
6196 // Verify all streams to be deleted don't have any outstanding buffers
6197 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6198 inputStreamId) == offlineStreamIds.end()) {
6199 if (mInputStream->hasOutstandingBuffers()) {
6200 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6201 inputStreamId, mInputStream->getOutstandingBuffersCount());
6202 return UNKNOWN_ERROR;
6203 }
6204 }
6205
6206 for (const auto& outStreamId : outputStreamIds) {
6207 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6208 outStreamId) == offlineStreamIds.end()) {
6209 auto outStream = mOutputStreams.get(outStreamId);
6210 if (outStream->hasOutstandingBuffers()) {
6211 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6212 outStreamId, outStream->getOutstandingBuffersCount());
6213 return UNKNOWN_ERROR;
6214 }
6215 }
6216 }
6217
6218 InFlightRequestMap offlineReqs;
6219 // Verify inflight requests and their pending buffers
6220 {
6221 std::lock_guard<std::mutex> l(mInFlightLock);
6222 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6223 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6224 if (idx == NAME_NOT_FOUND) {
6225 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6226 return UNKNOWN_ERROR;
6227 }
6228
6229 const auto& inflightReq = mInFlightMap.valueAt(idx);
6230 // TODO: check specific stream IDs
6231 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6232 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6233 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6234 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6235 return UNKNOWN_ERROR;
6236 }
6237 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6238 }
6239 }
6240
6241 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006242 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006243 camera3::StreamSet offlineStreamSet;
6244 sp<camera3::Camera3Stream> inputStream;
6245 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6246 int32_t id = offlineStream.id;
6247 if (mInputStream != nullptr && id == mInputStream->getId()) {
6248 inputStream = mInputStream;
6249 } else {
6250 offlineStreamSet.add(id, mOutputStreams.get(id));
6251 }
6252 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006253
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006254 // TODO: check if we need to lock before copying states
6255 // though technically no other thread should be talking to Camera3Device at this point
6256 Camera3OfflineStates offlineStates(
6257 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006258 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6259 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6260 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6261 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6262 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6263 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6264 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006265
6266 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6267 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6268
6269 // Delete all streams that has been transferred to offline session
6270 Mutex::Autolock l(mLock);
6271 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6272 int32_t id = offlineStream.id;
6273 if (mInputStream != nullptr && id == mInputStream->getId()) {
6274 mInputStream.clear();
6275 } else {
6276 mOutputStreams.remove(id);
6277 }
6278 }
6279
6280 // disconnect all other streams and switch to UNCONFIGURED state
6281 if (mInputStream != nullptr) {
6282 ret = mInputStream->disconnect();
6283 if (ret != OK) {
6284 SET_ERR_L("disconnect input stream failed!");
6285 return UNKNOWN_ERROR;
6286 }
6287 }
6288
6289 for (auto streamId : mOutputStreams.getStreamIds()) {
6290 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6291 ret = stream->disconnect();
6292 if (ret != OK) {
6293 SET_ERR_L("disconnect output stream %d failed!", streamId);
6294 return UNKNOWN_ERROR;
6295 }
6296 }
6297
6298 mInputStream.clear();
6299 mOutputStreams.clear();
6300 mNeedConfig = true;
6301 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6302 mOperatingMode = NO_MODE;
6303 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006304 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006305
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006306 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006307 // TO be done by CameraDeviceClient/Camera3OfflineSession
6308 // register the offline client to camera service
6309 // Setup result passthing threads etc
6310 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6311 // TODO: check how many onIdle callback will be sent
6312 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006313}
6314
Emilian Peevcc0b7952020-01-07 13:54:47 -08006315void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6316 ATRACE_CALL();
6317
6318 if (offlineStreamIds == nullptr) {
6319 return;
6320 }
6321
6322 Mutex::Autolock il(mInterfaceLock);
6323
6324 auto streamIds = mOutputStreams.getStreamIds();
6325 bool hasInputStream = mInputStream != nullptr;
6326 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6327 offlineStreamIds->push_back(mInputStream->getId());
6328 }
6329
6330 for (const auto & streamId : streamIds) {
6331 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6332 // Streams that use the camera buffer manager are currently not supported in
6333 // offline mode
6334 if (stream->getOfflineProcessingSupport() &&
6335 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6336 offlineStreamIds->push_back(streamId);
6337 }
6338 }
6339}
6340
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006341status_t Camera3Device::setRotateAndCropAutoBehavior(
6342 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6343 ATRACE_CALL();
6344 Mutex::Autolock il(mInterfaceLock);
6345 Mutex::Autolock l(mLock);
6346 if (mRequestThread == nullptr) {
6347 return INVALID_OPERATION;
6348 }
6349 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6350}
6351
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006352bool Camera3Device::supportsCameraMute() {
6353 Mutex::Autolock il(mInterfaceLock);
6354 Mutex::Autolock l(mLock);
6355
6356 return mSupportCameraMute;
6357}
6358
6359status_t Camera3Device::setCameraMute(bool enabled) {
6360 ATRACE_CALL();
6361 Mutex::Autolock il(mInterfaceLock);
6362 Mutex::Autolock l(mLock);
6363
6364 if (mRequestThread == nullptr || !mSupportCameraMute) {
6365 return INVALID_OPERATION;
6366 }
6367 return mRequestThread->setCameraMute(enabled);
6368}
6369
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006370}; // namespace android