blob: bf7e597685c904143bb7721aa7228e8b08c60259 [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 }
2192 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002193 // Get session stats from the builder, and notify the listener.
2194 int64_t requestCount, resultErrorCount;
2195 bool deviceError;
2196 std::map<int, StreamStats> streamStatsMap;
2197 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2198 &deviceError, &streamStatsMap);
2199 for (size_t i = 0; i < streamIds.size(); i++) {
2200 int streamId = streamIds[i];
2201 auto stats = streamStatsMap.find(streamId);
2202 if (stats != streamStatsMap.end()) {
2203 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2204 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2205 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002206 streamStats[i].mHistogramType =
2207 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2208 streamStats[i].mHistogramBins.assign(
2209 stats->second.mCaptureLatencyBins.begin(),
2210 stats->second.mCaptureLatencyBins.end());
2211 streamStats[i].mHistogramCounts.assign(
2212 stats->second.mCaptureLatencyHistogram.begin(),
2213 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002214 }
2215 }
2216 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 }
2218}
2219
Shuzhen Wang758c2152017-01-10 18:26:18 -08002220status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002221 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002222 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002223 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2224 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002225
2226 if (surfaceIds == nullptr) {
2227 return BAD_VALUE;
2228 }
2229
Zhijun He5d677d12016-05-29 16:52:39 -07002230 Mutex::Autolock il(mInterfaceLock);
2231 Mutex::Autolock l(mLock);
2232
Shuzhen Wang758c2152017-01-10 18:26:18 -08002233 if (consumers.size() == 0) {
2234 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002235 return BAD_VALUE;
2236 }
2237
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002238 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2239 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002240 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002241 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002242 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002243
2244 // isConsumerConfigurationDeferred will be off after setConsumers
2245 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002246 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002247 if (res != OK) {
2248 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2249 return res;
2250 }
2251
Emilian Peev40ead602017-09-26 15:46:36 +01002252 for (auto &consumer : consumers) {
2253 int id = stream->getSurfaceId(consumer);
2254 if (id < 0) {
2255 CLOGE("Invalid surface id!");
2256 return BAD_VALUE;
2257 }
2258 surfaceIds->push_back(id);
2259 }
2260
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002261 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002262 if (!stream->isConfiguring()) {
2263 CLOGE("Stream %d was already fully configured.", streamId);
2264 return INVALID_OPERATION;
2265 }
Zhijun He5d677d12016-05-29 16:52:39 -07002266
Shuzhen Wang0129d522016-10-30 22:43:41 -07002267 res = stream->finishConfiguration();
2268 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002269 // If finishConfiguration fails due to abandoned surface, do not set
2270 // device to error state.
2271 bool isSurfaceAbandoned =
2272 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2273 if (!isSurfaceAbandoned) {
2274 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2275 stream->getId(), strerror(-res), res);
2276 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002277 return res;
2278 }
Zhijun He5d677d12016-05-29 16:52:39 -07002279 }
2280
2281 return OK;
2282}
2283
Emilian Peev40ead602017-09-26 15:46:36 +01002284status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2285 const std::vector<OutputStreamInfo> &outputInfo,
2286 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2287 Mutex::Autolock il(mInterfaceLock);
2288 Mutex::Autolock l(mLock);
2289
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002290 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2291 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002292 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002293 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002294 }
2295
2296 for (const auto &it : removedSurfaceIds) {
2297 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2298 CLOGE("Shared surface still part of a pending request!");
2299 return -EBUSY;
2300 }
2301 }
2302
Emilian Peev40ead602017-09-26 15:46:36 +01002303 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2304 if (res != OK) {
2305 CLOGE("Stream %d failed to update stream (error %d %s) ",
2306 streamId, res, strerror(-res));
2307 if (res == UNKNOWN_ERROR) {
2308 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2309 __FUNCTION__);
2310 }
2311 return res;
2312 }
2313
2314 return res;
2315}
2316
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002317status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2318 Mutex::Autolock il(mInterfaceLock);
2319 Mutex::Autolock l(mLock);
2320
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002321 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2322 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002323 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2324 return BAD_VALUE;
2325 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002326
2327 if (dropping) {
2328 mSessionStatsBuilder.stopCounter(streamId);
2329 } else {
2330 mSessionStatsBuilder.startCounter(streamId);
2331 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002332 return stream->dropBuffers(dropping);
2333}
2334
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002335/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002336 * Camera3Device private methods
2337 */
2338
2339sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002340 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002341 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002342
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002343 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002344 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345
2346 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002347 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002348 if (inputStreams.count > 0) {
2349 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002350 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002351 CLOGE("Request references unknown input stream %d",
2352 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002353 return NULL;
2354 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002355
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002357 SET_ERR_L("%s: input stream %d is not configured!",
2358 __FUNCTION__, mInputStream->getId());
2359 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002361 // Check if stream prepare is blocking requests.
2362 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002363 CLOGE("Request references an input stream that's being prepared!");
2364 return NULL;
2365 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366
2367 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002368 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 }
2370
2371 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002372 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002374 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375 return NULL;
2376 }
2377
2378 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002379 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2380 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002381 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002382 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 return NULL;
2384 }
Zhijun He5d677d12016-05-29 16:52:39 -07002385 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002386 auto iter = surfaceMap.find(streams.data.i32[i]);
2387 if (iter != surfaceMap.end()) {
2388 const std::vector<size_t>& surfaces = iter->second;
2389 for (const auto& surface : surfaces) {
2390 if (stream->isConsumerConfigurationDeferred(surface)) {
2391 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2392 "due to deferred consumer", stream->getId(), surface);
2393 return NULL;
2394 }
2395 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002396 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002397 }
2398
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002400 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2401 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002402 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002403 // Check if stream prepare is blocking requests.
2404 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002405 CLOGE("Request references an output stream that's being prepared!");
2406 return NULL;
2407 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002408
2409 newRequest->mOutputStreams.push(stream);
2410 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002411 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002412 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002414 auto rotateAndCropEntry =
2415 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2416 if (rotateAndCropEntry.count > 0 &&
2417 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2418 newRequest->mRotateAndCropAuto = true;
2419 } else {
2420 newRequest->mRotateAndCropAuto = false;
2421 }
2422
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002423 auto zoomRatioEntry =
2424 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2425 if (zoomRatioEntry.count > 0 &&
2426 zoomRatioEntry.data.f[0] == 1.0f) {
2427 newRequest->mZoomRatioIs1x = true;
2428 } else {
2429 newRequest->mZoomRatioIs1x = false;
2430 }
2431
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002432 if (mSupportCameraMute) {
2433 auto testPatternModeEntry =
2434 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2435 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2436 testPatternModeEntry.data.i32[0] :
2437 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2438
2439 auto testPatternDataEntry =
2440 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2441 if (testPatternDataEntry.count > 0) {
2442 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2443 sizeof(newRequest->mOriginalTestPatternData));
2444 } else {
2445 newRequest->mOriginalTestPatternData[0] = 0;
2446 newRequest->mOriginalTestPatternData[1] = 0;
2447 newRequest->mOriginalTestPatternData[2] = 0;
2448 newRequest->mOriginalTestPatternData[3] = 0;
2449 }
2450 }
2451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002453}
2454
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002455void Camera3Device::cancelStreamsConfigurationLocked() {
2456 int res = OK;
2457 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2458 res = mInputStream->cancelConfiguration();
2459 if (res != OK) {
2460 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2461 mInputStream->getId(), strerror(-res), res);
2462 }
2463 }
2464
2465 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002466 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002467 if (outputStream->isConfiguring()) {
2468 res = outputStream->cancelConfiguration();
2469 if (res != OK) {
2470 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2471 outputStream->getId(), strerror(-res), res);
2472 }
2473 }
2474 }
2475
2476 // Return state to that at start of call, so that future configures
2477 // properly clean things up
2478 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2479 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002480
2481 res = mPreparerThread->resume();
2482 if (res != OK) {
2483 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2484 }
2485}
2486
Emilian Peev0d0191e2020-04-21 17:01:18 -07002487bool Camera3Device::checkAbandonedStreamsLocked() {
2488 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2489 return true;
2490 }
2491
2492 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2493 auto stream = mOutputStreams[i];
2494 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2495 return true;
2496 }
2497 }
2498
2499 return false;
2500}
2501
Emilian Peev3bead5f2020-05-28 17:29:08 -07002502bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002503 ATRACE_CALL();
2504 bool ret = false;
2505
Shuzhen Wang316781a2020-08-18 18:11:01 -07002506 nsecs_t startTime = systemTime();
2507
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002508 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002509 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2510
2511 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002512 if (checkAbandonedStreamsLocked()) {
2513 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2514 __FUNCTION__);
2515 return true;
2516 }
2517
Emilian Peev3bead5f2020-05-28 17:29:08 -07002518 status_t rc = NO_ERROR;
2519 bool markClientActive = false;
2520 if (mStatus == STATUS_ACTIVE) {
2521 markClientActive = true;
2522 mPauseStateNotify = true;
2523 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2524
2525 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2526 }
2527
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002528 if (rc == NO_ERROR) {
2529 mNeedConfig = true;
2530 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2531 if (rc == NO_ERROR) {
2532 ret = true;
2533 mPauseStateNotify = false;
2534 //Moving to active state while holding 'mLock' is important.
2535 //There could be pending calls to 'create-/deleteStream' which
2536 //will trigger another stream configuration while the already
2537 //present streams end up with outstanding buffers that will
2538 //not get drained.
2539 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002540 } else if (rc == DEAD_OBJECT) {
2541 // DEAD_OBJECT can be returned if either the consumer surface is
2542 // abandoned, or the HAL has died.
2543 // - If the HAL has died, configureStreamsLocked call will set
2544 // device to error state,
2545 // - If surface is abandoned, we should not set device to error
2546 // state.
2547 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002548 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002549 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002550 }
2551 } else {
2552 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2553 }
2554
Shuzhen Wang316781a2020-08-18 18:11:01 -07002555 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2556 ns2ms(systemTime() - startTime));
2557
Emilian Peev3bead5f2020-05-28 17:29:08 -07002558 if (markClientActive) {
2559 mStatusTracker->markComponentActive(clientStatusId);
2560 }
2561
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002562 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002563}
2564
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002565status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002566 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002567 ATRACE_CALL();
2568 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002569
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002570 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002571 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002572 return INVALID_OPERATION;
2573 }
2574
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002575 if (operatingMode < 0) {
2576 CLOGE("Invalid operating mode: %d", operatingMode);
2577 return BAD_VALUE;
2578 }
2579
2580 bool isConstrainedHighSpeed =
2581 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2582 operatingMode;
2583
2584 if (mOperatingMode != operatingMode) {
2585 mNeedConfig = true;
2586 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2587 mOperatingMode = operatingMode;
2588 }
2589
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002590 // In case called from configureStreams, abort queued input buffers not belonging to
2591 // any pending requests.
2592 if (mInputStream != NULL && notifyRequestThread) {
2593 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002594 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002595 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002596 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002597 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002598 if (res != OK) {
2599 // Exhausted acquiring all input buffers.
2600 break;
2601 }
2602
Emilian Peevf4816702020-04-03 15:44:51 -07002603 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002604 res = mInputStream->returnInputBuffer(inputBuffer);
2605 if (res != OK) {
2606 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2607 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2608 }
2609 }
2610 }
2611
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002612 if (!mNeedConfig) {
2613 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2614 return OK;
2615 }
2616
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002617 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002618 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2620 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002621 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002622 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002623 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 }
2625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002627 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002628
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002629 mPreparerThread->pause();
2630
Emilian Peevf4816702020-04-03 15:44:51 -07002631 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002632 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002634 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002635
Emilian Peevf4816702020-04-03 15:44:51 -07002636 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002638 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640
2641 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002642 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002643 inputStream = mInputStream->startConfiguration();
2644 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002645 CLOGE("Can't start input stream configuration");
2646 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647 return INVALID_OPERATION;
2648 }
2649 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002650
2651 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 }
2653
Shuzhen Wang99080502021-03-07 21:08:20 -08002654 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002656
2657 // Don't configure bidi streams twice, nor add them twice to the list
2658 if (mOutputStreams[i].get() ==
2659 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2660
2661 config.num_streams--;
2662 continue;
2663 }
2664
Emilian Peevf4816702020-04-03 15:44:51 -07002665 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002666 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002668 CLOGE("Can't start output stream configuration");
2669 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 return INVALID_OPERATION;
2671 }
2672 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002673
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002674 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002675 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2676 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002677 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2678 bufferSizes[k] = static_cast<uint32_t>(
2679 getJpegBufferSize(outputStream->width, outputStream->height));
2680 } else if (outputStream->data_space ==
2681 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2682 bufferSizes[k] = outputStream->width * outputStream->height;
2683 } else {
2684 ALOGW("%s: Blob dataSpace %d not supported",
2685 __FUNCTION__, outputStream->data_space);
2686 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002687 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002688
2689 if (mOutputStreams[i]->isMultiResolution()) {
2690 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2691 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2692 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2693 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694 }
2695
2696 config.streams = streams.editArray();
2697
2698 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002699 // max_buffers, usage, and priv fields, as well as data_space and format
2700 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002701
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002702 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002703 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002704 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002705
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002706 if (res == BAD_VALUE) {
2707 // HAL rejected this set of streams as unsupported, clean up config
2708 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002709 CLOGE("Set of requested inputs/outputs not supported by HAL");
2710 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002711 return BAD_VALUE;
2712 } else if (res != OK) {
2713 // Some other kind of error from configure_streams - this is not
2714 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002715 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2716 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717 return res;
2718 }
2719
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002720 // Finish all stream configuration immediately.
2721 // TODO: Try to relax this later back to lazy completion, which should be
2722 // faster
2723
Igor Murashkin073f8572013-05-02 14:59:28 -07002724 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002725 bool streamReConfigured = false;
2726 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002727 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002728 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002729 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002730 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002731 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2732 return DEAD_OBJECT;
2733 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002734 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002735 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002736 if (streamReConfigured) {
2737 mInterface->onStreamReConfigured(mInputStream->getId());
2738 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002739 }
2740
2741 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002742 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002743 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002744 bool streamReConfigured = false;
2745 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002746 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002747 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002748 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002749 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002750 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2751 return DEAD_OBJECT;
2752 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002754 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002755 if (streamReConfigured) {
2756 mInterface->onStreamReConfigured(outputStream->getId());
2757 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002758 }
2759 }
2760
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002761 // Request thread needs to know to avoid using repeat-last-settings protocol
2762 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002763 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002764 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2765 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002766 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002767
Zhijun He90f7c372016-08-16 16:19:43 -07002768 char value[PROPERTY_VALUE_MAX];
2769 property_get("camera.fifo.disable", value, "0");
2770 int32_t disableFifo = atoi(value);
2771 if (disableFifo != 1) {
2772 // Boost priority of request thread to SCHED_FIFO.
2773 pid_t requestThreadTid = mRequestThread->getTid();
2774 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002775 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002776 if (res != OK) {
2777 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2778 strerror(-res), res);
2779 } else {
2780 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2781 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002782 }
2783
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002784 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002785 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2786 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2787 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2788 sessionParams.unlock(newSessionParams);
2789 mSessionParams.unlock(currentSessionParams);
2790 if (updateSessionParams) {
2791 mSessionParams = sessionParams;
2792 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002793
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002794 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002795
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002796 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002797 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002798
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002799 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002800
Zhijun He0a210512014-07-24 13:45:15 -07002801 // tear down the deleted streams after configure streams.
2802 mDeletedStreams.clear();
2803
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002804 auto rc = mPreparerThread->resume();
2805 if (rc != OK) {
2806 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2807 return rc;
2808 }
2809
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002810 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002811 mRequestBufferSM.onStreamsConfigured();
2812 }
2813
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002814 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002815}
2816
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002817status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002818 ATRACE_CALL();
2819 status_t res;
2820
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002821 if (mFakeStreamId != NO_STREAM) {
2822 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002823 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002824 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002825 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002826 return INVALID_OPERATION;
2827 }
2828
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002829 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002830
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002831 sp<Camera3OutputStreamInterface> fakeStream =
2832 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002833
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002834 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002835 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002836 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002837 return res;
2838 }
2839
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002840 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002841 mNextStreamId++;
2842
2843 return OK;
2844}
2845
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002846status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002847 ATRACE_CALL();
2848 status_t res;
2849
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002850 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002851 if (mOutputStreams.size() == 1) return OK;
2852
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002853 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002854
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002855 // Ok, have a fake stream and there's at least one other output stream,
2856 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002857
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002858 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002859 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002860 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002861 return INVALID_OPERATION;
2862 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002863 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002864
2865 // Free up the stream endpoint so that it can be used by some other stream
2866 res = deletedStream->disconnect();
2867 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002868 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002869 // fall through since we want to still list the stream as deleted.
2870 }
2871 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002872 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002873
2874 return res;
2875}
2876
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002877void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002878 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002879 Mutex::Autolock l(mLock);
2880 va_list args;
2881 va_start(args, fmt);
2882
2883 setErrorStateLockedV(fmt, args);
2884
2885 va_end(args);
2886}
2887
2888void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002889 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002890 Mutex::Autolock l(mLock);
2891 setErrorStateLockedV(fmt, args);
2892}
2893
2894void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2895 va_list args;
2896 va_start(args, fmt);
2897
2898 setErrorStateLockedV(fmt, args);
2899
2900 va_end(args);
2901}
2902
2903void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002904 // Print out all error messages to log
2905 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002906 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002907
2908 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002909 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002910
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002911 mErrorCause = errorCause;
2912
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002913 if (mRequestThread != nullptr) {
2914 mRequestThread->setPaused(true);
2915 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002916 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002917
2918 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002919 sp<NotificationListener> listener = mListener.promote();
2920 if (listener != NULL) {
2921 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002922 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002923 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002924 }
2925
2926 // Save stack trace. View by dumping it later.
2927 CameraTraces::saveTrace();
2928 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002929}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002930
2931/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002932 * In-flight request management
2933 */
2934
Jianing Weicb0652e2014-03-12 18:29:36 -07002935status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002936 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002937 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002938 const std::set<std::set<String8>>& physicalCameraIds,
2939 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2940 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002941 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002942 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002943 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002944
2945 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002946 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002947 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002948 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002949 if (res < 0) return res;
2950
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002951 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002952 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2953 // avoid a deadlock during reprocess requests.
2954 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002955 if (mStatusTracker != nullptr) {
2956 mStatusTracker->markComponentActive(mInFlightStatusId);
2957 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002958 }
2959
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002960 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002961 return OK;
2962}
2963
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002964void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002965 // Indicate idle inFlightMap to the status tracker
2966 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002967 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002968 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2969 // avoid a deadlock during reprocess requests.
2970 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002971 if (mStatusTracker != nullptr) {
2972 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2973 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002974 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002975 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002976}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002977
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002978void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002979 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002980 // something has likely gone wrong. This might still be legit only if application send in
2981 // a long burst of long exposure requests.
2982 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2983 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2984 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2985 mInFlightMap.size(), mExpectedInflightDuration);
2986 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2987 kInFlightWarnLimitHighSpeed) {
2988 CLOGW("In-flight list too large for high speed configuration: %zu,"
2989 "total inflight duration %" PRIu64,
2990 mInFlightMap.size(), mExpectedInflightDuration);
2991 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002992 }
2993}
2994
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002995void Camera3Device::onInflightMapFlushedLocked() {
2996 mExpectedInflightDuration = 0;
2997}
2998
2999void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003000 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003001 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3002 mInFlightMap.removeItemsAt(idx, 1);
3003
3004 onInflightEntryRemovedLocked(duration);
3005}
3006
3007
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003008void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003009 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003010 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003011 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003012 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003013 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003014 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003015
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003016 FlushInflightReqStates states {
3017 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003018 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003019
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003020 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003021}
3022
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003023CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003024 ALOGV("%s", __FUNCTION__);
3025
Igor Murashkin1e479c02013-09-06 16:55:14 -07003026 CameraMetadata retVal;
3027
3028 if (mRequestThread != NULL) {
3029 retVal = mRequestThread->getLatestRequest();
3030 }
3031
Igor Murashkin1e479c02013-09-06 16:55:14 -07003032 return retVal;
3033}
3034
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003035void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003036 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3037 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3038
3039 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3040 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003041}
3042
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003043/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003044 * HalInterface inner class methods
3045 */
3046
Yifan Hongf79b5542017-04-11 14:44:25 -07003047Camera3Device::HalInterface::HalInterface(
3048 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003049 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003050 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003051 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003052 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003053 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003054 mIsReconfigurationQuerySupported(true),
3055 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003056 // Check with hardware service manager if we can downcast these interfaces
3057 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003058 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3059 if (castResult_3_7.isOk()) {
3060 mHidlSession_3_7 = castResult_3_7;
3061 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003062 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3063 if (castResult_3_6.isOk()) {
3064 mHidlSession_3_6 = castResult_3_6;
3065 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003066 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3067 if (castResult_3_5.isOk()) {
3068 mHidlSession_3_5 = castResult_3_5;
3069 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003070 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3071 if (castResult_3_4.isOk()) {
3072 mHidlSession_3_4 = castResult_3_4;
3073 }
3074 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3075 if (castResult_3_3.isOk()) {
3076 mHidlSession_3_3 = castResult_3_3;
3077 }
3078}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003079
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003080Camera3Device::HalInterface::HalInterface() :
3081 mUseHalBufManager(false),
3082 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003083
3084Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003085 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003086 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003087 mUseHalBufManager(other.mUseHalBufManager),
3088 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003089
3090bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003091 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092}
3093
3094void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003095 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003096 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003097 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003098 mHidlSession_3_4.clear();
3099 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003100 mHidlSession.clear();
3101}
3102
3103status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003104 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003105 /*out*/ camera_metadata_t **requestTemplate) {
3106 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3107 if (!valid()) return INVALID_OPERATION;
3108 status_t res = OK;
3109
Emilian Peev31abd0a2017-05-11 18:37:46 +01003110 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003111
3112 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003113 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003114 status = s;
3115 if (status == common::V1_0::Status::OK) {
3116 const camera_metadata *r =
3117 reinterpret_cast<const camera_metadata_t*>(request.data());
3118 size_t expectedSize = request.size();
3119 int ret = validate_camera_metadata_structure(r, &expectedSize);
3120 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3121 *requestTemplate = clone_camera_metadata(r);
3122 if (*requestTemplate == nullptr) {
3123 ALOGE("%s: Unable to clone camera metadata received from HAL",
3124 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003125 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003126 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003127 } else {
3128 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3129 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003130 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003131 }
3132 };
3133 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003134 RequestTemplate id;
3135 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003136 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003137 id = RequestTemplate::PREVIEW;
3138 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003139 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003140 id = RequestTemplate::STILL_CAPTURE;
3141 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003142 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003143 id = RequestTemplate::VIDEO_RECORD;
3144 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003145 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003146 id = RequestTemplate::VIDEO_SNAPSHOT;
3147 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003148 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003149 id = RequestTemplate::ZERO_SHUTTER_LAG;
3150 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003151 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003152 id = RequestTemplate::MANUAL;
3153 break;
3154 default:
3155 // Unknown template ID, or this HAL is too old to support it
3156 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003157 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003158 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003159
Emilian Peev31abd0a2017-05-11 18:37:46 +01003160 if (!err.isOk()) {
3161 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3162 res = DEAD_OBJECT;
3163 } else {
3164 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003165 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003166
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003167 return res;
3168}
3169
Emilian Peev4ec17882019-01-24 17:16:58 -08003170bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3171 CameraMetadata& newSessionParams) {
3172 // We do reconfiguration by default;
3173 bool ret = true;
3174 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3175 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3176 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3177 oldSessionParams.getAndLock());
3178 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3179 newSessionParams.getAndLock());
3180 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3181 get_camera_metadata_size(oldSessioMeta));
3182 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3183 get_camera_metadata_size(newSessioMeta));
3184 hardware::camera::common::V1_0::Status callStatus;
3185 bool required;
3186 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3187 bool requiredFlag) {
3188 callStatus = s;
3189 required = requiredFlag;
3190 };
3191 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3192 oldSessionParams.unlock(oldSessioMeta);
3193 newSessionParams.unlock(newSessioMeta);
3194 if (err.isOk()) {
3195 switch (callStatus) {
3196 case hardware::camera::common::V1_0::Status::OK:
3197 ret = required;
3198 break;
3199 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3200 mIsReconfigurationQuerySupported = false;
3201 ret = true;
3202 break;
3203 default:
3204 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3205 ret = true;
3206 }
3207 } else {
3208 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3209 ret = true;
3210 }
3211 }
3212
3213 return ret;
3214}
3215
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003216status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003217 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003218 ATRACE_NAME("CameraHal::configureStreams");
3219 if (!valid()) return INVALID_OPERATION;
3220 status_t res = OK;
3221
Shuzhen Wang83bff122020-11-20 15:51:39 -08003222 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3223 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3224 return BAD_VALUE;
3225 }
3226
Emilian Peev31abd0a2017-05-11 18:37:46 +01003227 // Convert stream config to HIDL
3228 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003229 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3230 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003231 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003232 requestedConfiguration3_2.streams.resize(config->num_streams);
3233 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003234 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003235 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003236 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3237 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003238 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003239 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003240
Emilian Peev31abd0a2017-05-11 18:37:46 +01003241 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3242 cam3stream->setBufferFreedListener(this);
3243 int streamId = cam3stream->getId();
3244 StreamType streamType;
3245 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003246 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003247 streamType = StreamType::OUTPUT;
3248 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003249 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003250 streamType = StreamType::INPUT;
3251 break;
3252 default:
3253 ALOGE("%s: Stream %d: Unsupported stream type %d",
3254 __FUNCTION__, streamId, config->streams[i]->stream_type);
3255 return BAD_VALUE;
3256 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003257 dst3_2.id = streamId;
3258 dst3_2.streamType = streamType;
3259 dst3_2.width = src->width;
3260 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003261 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003262 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003263 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003264 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003265 if (mHidlSession_3_5 != nullptr) {
3266 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3267 cam3stream->getOriginalFormat() : src->format);
3268 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3269 cam3stream->getOriginalDataSpace() : src->data_space);
3270 } else {
3271 dst3_2.format = mapToPixelFormat(src->format);
3272 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3273 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003274 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003275 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003276 if (src->physical_camera_id != nullptr) {
3277 dst3_4.physicalCameraId = src->physical_camera_id;
3278 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 dst3_7.v3_4 = dst3_4;
3280 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003281 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3282 size_t j = 0;
3283 for (int mode : src->sensor_pixel_modes_used) {
3284 dst3_7.sensorPixelModesUsed[j++] =
3285 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3286 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003287 activeStreams.insert(streamId);
3288 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003289 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003290 }
3291 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003292 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003293
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003294 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003296 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003297 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 if (res != OK) {
3299 return res;
3300 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003301 requestedConfiguration3_2.operationMode = operationMode;
3302 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003303 requestedConfiguration3_7.operationMode = operationMode;
3304 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003305 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003306 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003307 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003308 requestedConfiguration3_7.operationMode = operationMode;
3309 requestedConfiguration3_7.sessionParams.setToExternal(
3310 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003311 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003312
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003314 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003315 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003316 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003317 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003318
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003319 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003320 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3321 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003322 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003323 };
3324
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003325 auto configStream36Cb = [&status, &finalConfiguration3_6]
3326 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3327 finalConfiguration3_6 = halConfiguration;
3328 status = s;
3329 };
3330
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003331 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3332 (hardware::Return<void>& err) -> status_t {
3333 if (!err.isOk()) {
3334 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3335 return DEAD_OBJECT;
3336 }
3337 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3338 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3339 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3340 }
3341 return OK;
3342 };
3343
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003344 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3345 (hardware::Return<void>& err) -> status_t {
3346 if (!err.isOk()) {
3347 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3348 return DEAD_OBJECT;
3349 }
3350 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3351 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3352 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3353 }
3354 return OK;
3355 };
3356
Shuzhen Wang92653952019-05-07 15:11:43 -07003357 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003358 if (mHidlSession_3_7 != nullptr) {
3359 ALOGV("%s: v3.7 device found", __FUNCTION__);
3360 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3361 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3362 auto err = mHidlSession_3_7->configureStreams_3_7(
3363 requestedConfiguration3_7, configStream36Cb);
3364 res = postprocConfigStream36(err);
3365 if (res != OK) {
3366 return res;
3367 }
3368 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003369 ALOGV("%s: v3.6 device found", __FUNCTION__);
3370 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3371 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3372 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3373 auto err = mHidlSession_3_6->configureStreams_3_6(
3374 requestedConfiguration3_5, configStream36Cb);
3375 res = postprocConfigStream36(err);
3376 if (res != OK) {
3377 return res;
3378 }
3379 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003380 ALOGV("%s: v3.5 device found", __FUNCTION__);
3381 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3382 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3383 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3384 auto err = mHidlSession_3_5->configureStreams_3_5(
3385 requestedConfiguration3_5, configStream34Cb);
3386 res = postprocConfigStream34(err);
3387 if (res != OK) {
3388 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003389 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003390 } else if (mHidlSession_3_4 != nullptr) {
3391 // We do; use v3.4 for the call
3392 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003393 auto err = mHidlSession_3_4->configureStreams_3_4(
3394 requestedConfiguration3_4, configStream34Cb);
3395 res = postprocConfigStream34(err);
3396 if (res != OK) {
3397 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003398 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003399 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003400 // We do; use v3.3 for the call
3401 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003402 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003403 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003404 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003405 finalConfiguration = halConfiguration;
3406 status = s;
3407 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003408 if (!err.isOk()) {
3409 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3410 return DEAD_OBJECT;
3411 }
3412 } else {
3413 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3414 ALOGV("%s: v3.2 device found", __FUNCTION__);
3415 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003416 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003417 [&status, &finalConfiguration_3_2]
3418 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3419 finalConfiguration_3_2 = halConfiguration;
3420 status = s;
3421 });
3422 if (!err.isOk()) {
3423 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3424 return DEAD_OBJECT;
3425 }
3426 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3427 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3428 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3429 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003430 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003431 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003432 }
3433
3434 if (status != common::V1_0::Status::OK ) {
3435 return CameraProviderManager::mapToStatusT(status);
3436 }
3437
3438 // And convert output stream configuration from HIDL
3439
3440 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003441 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003442 int streamId = Camera3Stream::cast(dst)->getId();
3443
3444 // Start scan at i, with the assumption that the stream order matches
3445 size_t realIdx = i;
3446 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003447 size_t halStreamCount = finalConfiguration.streams.size();
3448 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003449 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003450 found = true;
3451 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003452 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003453 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003454 }
3455 if (!found) {
3456 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3457 __FUNCTION__, streamId);
3458 return INVALID_OPERATION;
3459 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003460 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003461 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003462
Emilian Peev710c1422017-08-30 11:19:38 +01003463 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003464 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3465 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3466
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003467 if (mHidlSession_3_6 != nullptr) {
3468 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3469 }
3470
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003471 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003472 dstStream->setFormatOverride(false);
3473 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003474 if (dst->format != overrideFormat) {
3475 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3476 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003477 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003478 if (dst->data_space != overrideDataSpace) {
3479 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3480 streamId, dst->format);
3481 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003482 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003483 bool needFormatOverride =
3484 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3485 bool needDataspaceOverride =
3486 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003487 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003488 dstStream->setFormatOverride(needFormatOverride);
3489 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003490 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003491 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003492 }
3493
Emilian Peevf4816702020-04-03 15:44:51 -07003494 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003495 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003497 __FUNCTION__, streamId);
3498 return INVALID_OPERATION;
3499 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003500 dstStream->setUsage(
3501 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 } else {
3503 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003504 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003505 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3506 __FUNCTION__, streamId);
3507 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003508 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003509 dstStream->setUsage(
3510 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003511 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003512 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003513 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003515 return res;
3516}
3517
Emilian Peevf4816702020-04-03 15:44:51 -07003518status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003519 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003520 /*out*/std::vector<native_handle_t*>* handlesCreated,
3521 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003522 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003523 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3524 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3525 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003526 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003527 }
3528
3529 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003530
3531 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003532
3533 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003534 if (request->input_buffer != nullptr) {
3535 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3536 buffer_handle_t buf = *(request->input_buffer->buffer);
3537 auto pair = getBufferId(buf, streamId);
3538 bool isNewBuffer = pair.first;
3539 uint64_t bufferId = pair.second;
3540 captureRequest->inputBuffer.streamId = streamId;
3541 captureRequest->inputBuffer.bufferId = bufferId;
3542 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3543 captureRequest->inputBuffer.status = BufferStatus::OK;
3544 native_handle_t *acquireFence = nullptr;
3545 if (request->input_buffer->acquire_fence != -1) {
3546 acquireFence = native_handle_create(1,0);
3547 acquireFence->data[0] = request->input_buffer->acquire_fence;
3548 handlesCreated->push_back(acquireFence);
3549 }
3550 captureRequest->inputBuffer.acquireFence = acquireFence;
3551 captureRequest->inputBuffer.releaseFence = nullptr;
3552
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003553 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003554 request->input_buffer->buffer);
3555 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003556 } else {
3557 captureRequest->inputBuffer.streamId = -1;
3558 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3559 }
3560
3561 captureRequest->outputBuffers.resize(request->num_output_buffers);
3562 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003563 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003564 StreamBuffer &dst = captureRequest->outputBuffers[i];
3565 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003566 if (src->buffer != nullptr) {
3567 buffer_handle_t buf = *(src->buffer);
3568 auto pair = getBufferId(buf, streamId);
3569 bool isNewBuffer = pair.first;
3570 dst.bufferId = pair.second;
3571 dst.buffer = isNewBuffer ? buf : nullptr;
3572 native_handle_t *acquireFence = nullptr;
3573 if (src->acquire_fence != -1) {
3574 acquireFence = native_handle_create(1,0);
3575 acquireFence->data[0] = src->acquire_fence;
3576 handlesCreated->push_back(acquireFence);
3577 }
3578 dst.acquireFence = acquireFence;
3579 } else if (mUseHalBufManager) {
3580 // HAL buffer management path
3581 dst.bufferId = BUFFER_ID_NO_BUFFER;
3582 dst.buffer = nullptr;
3583 dst.acquireFence = nullptr;
3584 } else {
3585 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3586 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003587 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003588 dst.streamId = streamId;
3589 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003590 dst.releaseFence = nullptr;
3591
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003592 // Output buffers are empty when using HAL buffer manager
3593 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003594 mBufferRecords.pushInflightBuffer(
3595 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003596 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003597 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003598 }
3599 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003600 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003601}
3602
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003603void Camera3Device::HalInterface::cleanupNativeHandles(
3604 std::vector<native_handle_t*> *handles, bool closeFd) {
3605 if (handles == nullptr) {
3606 return;
3607 }
3608 if (closeFd) {
3609 for (auto& handle : *handles) {
3610 native_handle_close(handle);
3611 }
3612 }
3613 for (auto& handle : *handles) {
3614 native_handle_delete(handle);
3615 }
3616 handles->clear();
3617 return;
3618}
3619
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003620status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003621 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003622 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3623 if (!valid()) return INVALID_OPERATION;
3624
Emilian Peevaebbe412018-01-15 13:53:24 +00003625 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003626 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3627 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3628 if (castResult_3_7.isOk()) {
3629 hidlSession_3_7 = castResult_3_7;
3630 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003631 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3632 if (castResult_3_4.isOk()) {
3633 hidlSession_3_4 = castResult_3_4;
3634 }
3635
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003636 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003637 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003638 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003639 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003640 if (hidlSession_3_7 != nullptr) {
3641 captureRequests_3_7.resize(batchSize);
3642 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003643 captureRequests_3_4.resize(batchSize);
3644 } else {
3645 captureRequests.resize(batchSize);
3646 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003647 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003648 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003649
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003650 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003651 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003652 if (hidlSession_3_7 != nullptr) {
3653 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3654 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3655 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003656 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003657 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003658 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003659 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3660 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003661 }
3662 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003663 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003664 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003665 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003666 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003667 }
3668
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003669 std::vector<device::V3_2::BufferCache> cachesToRemove;
3670 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003671 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003672 for (auto& pair : mFreedBuffers) {
3673 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003674 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003675 cachesToRemove.push_back({pair.first, pair.second});
3676 }
3677 }
3678 mFreedBuffers.clear();
3679 }
3680
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003681 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3682 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003683
3684 // Write metadata to FMQ.
3685 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003686 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003687 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003688 if (hidlSession_3_7 != nullptr) {
3689 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3690 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003691 captureRequest = &captureRequests_3_4[i].v3_2;
3692 } else {
3693 captureRequest = &captureRequests[i];
3694 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003695
3696 if (request->settings != nullptr) {
3697 size_t settingsSize = get_camera_metadata_size(request->settings);
3698 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3699 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3700 captureRequest->settings.resize(0);
3701 captureRequest->fmqSettingsSize = settingsSize;
3702 } else {
3703 if (mRequestMetadataQueue != nullptr) {
3704 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3705 }
3706 captureRequest->settings.setToExternal(
3707 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3708 get_camera_metadata_size(request->settings));
3709 captureRequest->fmqSettingsSize = 0u;
3710 }
3711 } else {
3712 // A null request settings maps to a size-0 CameraMetadata
3713 captureRequest->settings.resize(0);
3714 captureRequest->fmqSettingsSize = 0u;
3715 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003716
Shuzhen Wang83bff122020-11-20 15:51:39 -08003717 // hidl session 3.7 specific handling.
3718 if (hidlSession_3_7 != nullptr) {
3719 captureRequests_3_7[i].inputWidth = request->input_width;
3720 captureRequests_3_7[i].inputHeight = request->input_height;
3721 }
3722
3723 // hidl session 3.7 and 3.4 specific handling.
3724 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3725 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3726 (hidlSession_3_7 != nullptr) ?
3727 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3728 captureRequests_3_4[i].physicalCameraSettings;
3729 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003730 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003731 if (request->physcam_settings != nullptr) {
3732 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3733 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3734 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3735 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003736 physicalCameraSettings[j].settings.resize(0);
3737 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003738 } else {
3739 if (mRequestMetadataQueue != nullptr) {
3740 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3741 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003742 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003743 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3744 request->physcam_settings[j])),
3745 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003746 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003747 }
Emilian Peev00420d22018-02-05 21:33:13 +00003748 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003749 physicalCameraSettings[j].fmqSettingsSize = 0u;
3750 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003751 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003752 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003753 }
3754 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003755 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003756
3757 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003758 auto resultCallback =
3759 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3760 status = s;
3761 *numRequestProcessed = n;
3762 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003763 if (hidlSession_3_7 != nullptr) {
3764 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3765 resultCallback);
3766 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003767 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003768 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003769 } else {
3770 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003771 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003772 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003773 if (!err.isOk()) {
3774 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003775 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003776 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003777
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003778 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3779 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3780 __FUNCTION__, *numRequestProcessed, batchSize);
3781 status = common::V1_0::Status::INTERNAL_ERROR;
3782 }
3783
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003784 res = CameraProviderManager::mapToStatusT(status);
3785 if (res == OK) {
3786 if (mHidlSession->isRemote()) {
3787 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3788 // sent to camera HAL processes)
3789 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3790 } else {
3791 // In passthrough mode the FDs are now owned by HAL
3792 cleanupNativeHandles(&handlesCreated);
3793 }
3794 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003795 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003796 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003797 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003798 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003799}
3800
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003801status_t Camera3Device::HalInterface::flush() {
3802 ATRACE_NAME("CameraHal::flush");
3803 if (!valid()) return INVALID_OPERATION;
3804 status_t res = OK;
3805
Emilian Peev31abd0a2017-05-11 18:37:46 +01003806 auto err = mHidlSession->flush();
3807 if (!err.isOk()) {
3808 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3809 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003810 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003811 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003812 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003813
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003814 return res;
3815}
3816
Emilian Peev31abd0a2017-05-11 18:37:46 +01003817status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003818 ATRACE_NAME("CameraHal::dump");
3819 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003820
Emilian Peev31abd0a2017-05-11 18:37:46 +01003821 // Handled by CameraProviderManager::dump
3822
3823 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003824}
3825
3826status_t Camera3Device::HalInterface::close() {
3827 ATRACE_NAME("CameraHal::close()");
3828 if (!valid()) return INVALID_OPERATION;
3829 status_t res = OK;
3830
Emilian Peev31abd0a2017-05-11 18:37:46 +01003831 auto err = mHidlSession->close();
3832 // Interface will be dead shortly anyway, so don't log errors
3833 if (!err.isOk()) {
3834 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003835 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003836
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003837 return res;
3838}
3839
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003840void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3841 ATRACE_NAME("CameraHal::signalPipelineDrain");
3842 if (!valid() || mHidlSession_3_5 == nullptr) {
3843 ALOGE("%s called on invalid camera!", __FUNCTION__);
3844 return;
3845 }
3846
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003847 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003848 if (!err.isOk()) {
3849 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3850 return;
3851 }
3852}
3853
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003854status_t Camera3Device::HalInterface::switchToOffline(
3855 const std::vector<int32_t>& streamsToKeep,
3856 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003857 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3858 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003859 ATRACE_NAME("CameraHal::switchToOffline");
3860 if (!valid() || mHidlSession_3_6 == nullptr) {
3861 ALOGE("%s called on invalid camera!", __FUNCTION__);
3862 return INVALID_OPERATION;
3863 }
3864
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003865 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3866 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003867 return INVALID_OPERATION;
3868 }
3869
3870 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003871 auto resultCallback =
3872 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3873 status = s;
3874 *offlineSessionInfo = info;
3875 *offlineSession = session;
3876 };
3877 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3878
3879 if (!err.isOk()) {
3880 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3881 return DEAD_OBJECT;
3882 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003883
3884 status_t ret = CameraProviderManager::mapToStatusT(status);
3885 if (ret != OK) {
3886 return ret;
3887 }
3888
3889 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3890 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3891 // returns from switchToOffline.
3892
3893
3894 // Validate buffer caches
3895 std::vector<int32_t> streams;
3896 streams.reserve(offlineSessionInfo->offlineStreams.size());
3897 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3898 int32_t id = offlineStream.id;
3899 streams.push_back(id);
3900 // Verify buffer caches
3901 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3902 offlineStream.circulatingBufferIds.end());
3903 if (!verifyBufferIds(id, bufIds)) {
3904 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3905 return UNKNOWN_ERROR;
3906 }
3907 }
3908
3909 // Move buffer records
3910 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3911 bufferRecords->takeInflightBufferMap(mBufferRecords);
3912 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3913 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003914}
3915
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003916void Camera3Device::HalInterface::getInflightBufferKeys(
3917 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003918 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003919 return;
3920}
3921
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003922void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3923 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003924 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003925 return;
3926}
3927
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003928bool Camera3Device::HalInterface::verifyBufferIds(
3929 int32_t streamId, std::vector<uint64_t>& bufIds) {
3930 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003931}
3932
3933status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003934 int32_t frameNumber, int32_t streamId,
3935 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003936 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003937}
3938
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003939status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003940 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003941 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003942}
3943
3944// Find and pop a buffer_handle_t based on bufferId
3945status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003946 uint64_t bufferId,
3947 /*out*/ buffer_handle_t** buffer,
3948 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003949 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003950}
3951
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003952std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3953 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003954 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003955}
3956
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003957void Camera3Device::HalInterface::onBufferFreed(
3958 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003959 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3960 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3961 if (bufferId != BUFFER_ID_NO_BUFFER) {
3962 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003963 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003964}
3965
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003966void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003967 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3968 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3969 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003970 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3971 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003972}
3973
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003975 * RequestThread inner class methods
3976 */
3977
3978Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003979 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003980 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3981 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003982 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003983 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003984 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003985 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003986 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003987 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003988 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003989 mReconfigured(false),
3990 mDoPause(false),
3991 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003992 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003993 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003994 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003995 mCurrentAfTriggerId(0),
3996 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003997 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003998 mCameraMute(false),
3999 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004000 mRepeatingLastFrameNumber(
4001 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004002 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004003 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004004 mRequestLatency(kRequestLatencyBinSize),
4005 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004006 mLatestSessionParams(sessionParamKeys.size()),
4007 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004008 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004009}
4010
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004011Camera3Device::RequestThread::~RequestThread() {}
4012
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004013void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004014 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004015 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004016 Mutex::Autolock l(mRequestLock);
4017 mListener = listener;
4018}
4019
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004020void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004021 const CameraMetadata& sessionParams,
4022 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004023 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004024 Mutex::Autolock l(mRequestLock);
4025 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004026 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004027 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004028 // Prepare video stream for high speed recording.
4029 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004030 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004031}
4032
Jianing Wei90e59c92014-03-12 18:29:36 -07004033status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004034 List<sp<CaptureRequest> > &requests,
4035 /*out*/
4036 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004037 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004038 Mutex::Autolock l(mRequestLock);
4039 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4040 ++it) {
4041 mRequestQueue.push_back(*it);
4042 }
4043
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004044 if (lastFrameNumber != NULL) {
4045 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4046 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4047 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4048 *lastFrameNumber);
4049 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004050
Jianing Wei90e59c92014-03-12 18:29:36 -07004051 unpauseForNewRequests();
4052
4053 return OK;
4054}
4055
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004056
4057status_t Camera3Device::RequestThread::queueTrigger(
4058 RequestTrigger trigger[],
4059 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004060 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004061 Mutex::Autolock l(mTriggerMutex);
4062 status_t ret;
4063
4064 for (size_t i = 0; i < count; ++i) {
4065 ret = queueTriggerLocked(trigger[i]);
4066
4067 if (ret != OK) {
4068 return ret;
4069 }
4070 }
4071
4072 return OK;
4073}
4074
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004075const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4076 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004077 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004078 if (d != nullptr) return d->mId;
4079 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004080}
4081
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004082status_t Camera3Device::RequestThread::queueTriggerLocked(
4083 RequestTrigger trigger) {
4084
4085 uint32_t tag = trigger.metadataTag;
4086 ssize_t index = mTriggerMap.indexOfKey(tag);
4087
4088 switch (trigger.getTagType()) {
4089 case TYPE_BYTE:
4090 // fall-through
4091 case TYPE_INT32:
4092 break;
4093 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004094 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4095 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004096 return INVALID_OPERATION;
4097 }
4098
4099 /**
4100 * Collect only the latest trigger, since we only have 1 field
4101 * in the request settings per trigger tag, and can't send more than 1
4102 * trigger per request.
4103 */
4104 if (index != NAME_NOT_FOUND) {
4105 mTriggerMap.editValueAt(index) = trigger;
4106 } else {
4107 mTriggerMap.add(tag, trigger);
4108 }
4109
4110 return OK;
4111}
4112
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004113status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004114 const RequestList &requests,
4115 /*out*/
4116 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004117 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004118 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004119 if (lastFrameNumber != NULL) {
4120 *lastFrameNumber = mRepeatingLastFrameNumber;
4121 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004122 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004123 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004124 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4125 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004126
4127 unpauseForNewRequests();
4128
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004129 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004130 return OK;
4131}
4132
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004133bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004134 if (mRepeatingRequests.empty()) {
4135 return false;
4136 }
4137 int32_t requestId = requestIn->mResultExtras.requestId;
4138 const RequestList &repeatRequests = mRepeatingRequests;
4139 // All repeating requests are guaranteed to have same id so only check first quest
4140 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4141 return (firstRequest->mResultExtras.requestId == requestId);
4142}
4143
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004144status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004145 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004146 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004147 return clearRepeatingRequestsLocked(lastFrameNumber);
4148
4149}
4150
4151status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004153 if (lastFrameNumber != NULL) {
4154 *lastFrameNumber = mRepeatingLastFrameNumber;
4155 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004156 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004157 return OK;
4158}
4159
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004160status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004161 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004162 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004163 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004164 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004165
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004166 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004167
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004168 // Send errors for all requests pending in the request queue, including
4169 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004170 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004171 if (listener != NULL) {
4172 for (RequestList::iterator it = mRequestQueue.begin();
4173 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004174 // Abort the input buffers for reprocess requests.
4175 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004176 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004177 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004178 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004179 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004180 if (res != OK) {
4181 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4182 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4183 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004184 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004185 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4186 if (res != OK) {
4187 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4188 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4189 }
4190 }
4191 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004192 // Set the frame number this request would have had, if it
4193 // had been submitted; this frame number will not be reused.
4194 // The requestId and burstId fields were set when the request was
4195 // submitted originally (in convertMetadataListToRequestListLocked)
4196 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004197 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004198 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004199 }
4200 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004201 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004202
4203 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004204 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004205 if (lastFrameNumber != NULL) {
4206 *lastFrameNumber = mRepeatingLastFrameNumber;
4207 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004208 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004209 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004210 return OK;
4211}
4212
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004213status_t Camera3Device::RequestThread::flush() {
4214 ATRACE_CALL();
4215 Mutex::Autolock l(mFlushLock);
4216
Emilian Peev08dd2452017-04-06 16:55:14 +01004217 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004218}
4219
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004220void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004221 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004222 Mutex::Autolock l(mPauseLock);
4223 mDoPause = paused;
4224 mDoPauseSignal.signal();
4225}
4226
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004227status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4228 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004229 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004230 Mutex::Autolock l(mLatestRequestMutex);
4231 status_t res;
4232 while (mLatestRequestId != requestId) {
4233 nsecs_t startTime = systemTime();
4234
4235 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4236 if (res != OK) return res;
4237
4238 timeout -= (systemTime() - startTime);
4239 }
4240
4241 return OK;
4242}
4243
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004244void Camera3Device::RequestThread::requestExit() {
4245 // Call parent to set up shutdown
4246 Thread::requestExit();
4247 // The exit from any possible waits
4248 mDoPauseSignal.signal();
4249 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004250
4251 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4252 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004253}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004254
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004255void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004256 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004257 bool surfaceAbandoned = false;
4258 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004259 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004260 {
4261 Mutex::Autolock l(mRequestLock);
4262 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4263 // repeating requests.
4264 for (const auto& request : mRepeatingRequests) {
4265 for (const auto& s : request->mOutputStreams) {
4266 if (s->isAbandoned()) {
4267 surfaceAbandoned = true;
4268 clearRepeatingRequestsLocked(&lastFrameNumber);
4269 break;
4270 }
4271 }
4272 if (surfaceAbandoned) {
4273 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004274 }
4275 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004276 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004277 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004278
4279 if (listener != NULL && surfaceAbandoned) {
4280 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004281 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004282}
4283
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004284bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004285 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004286 status_t res;
4287 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004288 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004289 uint32_t numRequestProcessed = 0;
4290 for (size_t i = 0; i < batchSize; i++) {
4291 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004292 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004293 }
4294
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004295 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4296
4297 bool triggerRemoveFailed = false;
4298 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4299 for (size_t i = 0; i < numRequestProcessed; i++) {
4300 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4301 nextRequest.submitted = true;
4302
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004303 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004304
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004305 if (!triggerRemoveFailed) {
4306 // Remove any previously queued triggers (after unlock)
4307 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4308 if (removeTriggerRes != OK) {
4309 triggerRemoveFailed = true;
4310 triggerFailedRequest = nextRequest;
4311 }
4312 }
4313 }
4314
4315 if (triggerRemoveFailed) {
4316 SET_ERR("RequestThread: Unable to remove triggers "
4317 "(capture request %d, HAL device: %s (%d)",
4318 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4319 cleanUpFailedRequests(/*sendRequestError*/ false);
4320 return false;
4321 }
4322
4323 if (res != OK) {
4324 // Should only get a failure here for malformed requests or device-level
4325 // errors, so consider all errors fatal. Bad metadata failures should
4326 // come through notify.
4327 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4328 mNextRequests[numRequestProcessed].halRequest.frame_number,
4329 strerror(-res), res);
4330 cleanUpFailedRequests(/*sendRequestError*/ false);
4331 return false;
4332 }
4333 return true;
4334}
4335
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004336nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4337 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4338 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4339 find_camera_metadata_ro_entry(request,
4340 ANDROID_CONTROL_AE_MODE,
4341 &e);
4342 if (e.count == 0) return maxExpectedDuration;
4343
4344 switch (e.data.u8[0]) {
4345 case ANDROID_CONTROL_AE_MODE_OFF:
4346 find_camera_metadata_ro_entry(request,
4347 ANDROID_SENSOR_EXPOSURE_TIME,
4348 &e);
4349 if (e.count > 0) {
4350 maxExpectedDuration = e.data.i64[0];
4351 }
4352 find_camera_metadata_ro_entry(request,
4353 ANDROID_SENSOR_FRAME_DURATION,
4354 &e);
4355 if (e.count > 0) {
4356 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4357 }
4358 break;
4359 default:
4360 find_camera_metadata_ro_entry(request,
4361 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4362 &e);
4363 if (e.count > 1) {
4364 maxExpectedDuration = 1e9 / e.data.u8[0];
4365 }
4366 break;
4367 }
4368
4369 return maxExpectedDuration;
4370}
4371
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004372bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4373 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4374 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4375 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4376 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4377 return true;
4378 }
4379
4380 return false;
4381}
4382
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004383void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4384 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004385 camera_capture_request_t& halRequest = nextRequest.halRequest;
4386 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004387 Mutex::Autolock al(mLatestRequestMutex);
4388
Shuzhen Wang83bff122020-11-20 15:51:39 -08004389 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004390 mLatestRequest.acquire(cloned);
4391
4392 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004393 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4394 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4395 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004396 CameraMetadata(cloned));
4397 }
4398
4399 sp<Camera3Device> parent = mParent.promote();
4400 if (parent != NULL) {
4401 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004402 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004403 0, mLatestRequest, mLatestPhysicalRequest);
4404 }
4405 }
4406
Shuzhen Wang83bff122020-11-20 15:51:39 -08004407 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004408 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004409 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004410 }
4411
Shuzhen Wang83bff122020-11-20 15:51:39 -08004412 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004413}
4414
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004415bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4416 ATRACE_CALL();
4417 bool updatesDetected = false;
4418
Emilian Peev4ec17882019-01-24 17:16:58 -08004419 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004420 for (auto tag : mSessionParamKeys) {
4421 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004422 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004423
4424 if (entry.count > 0) {
4425 bool isDifferent = false;
4426 if (lastEntry.count > 0) {
4427 // Have a last value, compare to see if changed
4428 if (lastEntry.type == entry.type &&
4429 lastEntry.count == entry.count) {
4430 // Same type and count, compare values
4431 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4432 size_t entryBytes = bytesPerValue * lastEntry.count;
4433 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4434 if (cmp != 0) {
4435 isDifferent = true;
4436 }
4437 } else {
4438 // Count or type has changed
4439 isDifferent = true;
4440 }
4441 } else {
4442 // No last entry, so always consider to be different
4443 isDifferent = true;
4444 }
4445
4446 if (isDifferent) {
4447 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004448 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4449 updatesDetected = true;
4450 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004451 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004452 }
4453 } else if (lastEntry.count > 0) {
4454 // Value has been removed
4455 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004456 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004457 updatesDetected = true;
4458 }
4459 }
4460
Emilian Peev4ec17882019-01-24 17:16:58 -08004461 bool reconfigureRequired;
4462 if (updatesDetected) {
4463 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4464 updatedParams);
4465 mLatestSessionParams = updatedParams;
4466 } else {
4467 reconfigureRequired = false;
4468 }
4469
4470 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004471}
4472
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004473bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004474 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004475 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004476 // Any function called from threadLoop() must not hold mInterfaceLock since
4477 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4478 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479
4480 // Handle paused state.
4481 if (waitIfPaused()) {
4482 return true;
4483 }
4484
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004485 // Wait for the next batch of requests.
4486 waitForNextRequestBatch();
4487 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004488 return true;
4489 }
4490
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004491 // Get the latest request ID, if any
4492 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004493 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004494 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004495 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004496 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004497 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004498 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4499 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004500 }
4501
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004502 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4503 // or a single request from streaming or burst. In either case the first element
4504 // should contain the latest camera settings that we need to check for any session
4505 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004506 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004507 res = OK;
4508
4509 //Input stream buffers are already acquired at this point so an input stream
4510 //will not be able to move to idle state unless we force it.
4511 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4512 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4513 if (res != OK) {
4514 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4515 cleanUpFailedRequests(/*sendRequestError*/ false);
4516 return false;
4517 }
4518 }
4519
4520 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004521 sp<Camera3Device> parent = mParent.promote();
4522 if (parent != nullptr) {
4523 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004524 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004525 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004526
4527 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4528 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4529 if (res != OK) {
4530 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4531 cleanUpFailedRequests(/*sendRequestError*/ false);
4532 return false;
4533 }
4534 }
4535 }
4536 }
4537
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004538 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004539 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004540 if (res == TIMED_OUT) {
4541 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004542 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004543 // Check if any stream is abandoned.
4544 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004545 return true;
4546 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004547 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004548 return false;
4549 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004550
Zhijun Hecc27e112013-10-03 16:12:43 -07004551 // Inform waitUntilRequestProcessed thread of a new request ID
4552 {
4553 Mutex::Autolock al(mLatestRequestMutex);
4554
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004555 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004556 mLatestRequestSignal.signal();
4557 }
4558
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004559 // Submit a batch of requests to HAL.
4560 // Use flush lock only when submitting multilple requests in a batch.
4561 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4562 // which may take a long time to finish so synchronizing flush() and
4563 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4564 // For now, only synchronize for high speed recording and we should figure something out for
4565 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004566 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004567
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004568 if (useFlushLock) {
4569 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004570 }
4571
Zhijun Hef0645c12016-08-02 00:58:11 -07004572 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004573 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004574
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004575 sp<Camera3Device> parent = mParent.promote();
4576 if (parent != nullptr) {
4577 parent->mRequestBufferSM.onSubmittingRequest();
4578 }
4579
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004580 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004581 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004582 submitRequestSuccess = sendRequestsBatch();
4583
Shuzhen Wang686f6442017-06-20 16:16:04 -07004584 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4585 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004586
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004587 if (useFlushLock) {
4588 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004589 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004590
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004591 // Unset as current request
4592 {
4593 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004594 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004595 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004596 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004597
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004598 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004599}
4600
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004601status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004602 ATRACE_CALL();
4603
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004604 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004605 for (size_t i = 0; i < mNextRequests.size(); i++) {
4606 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004607 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004608 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4609 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004610
4611 // Prepare a request to HAL
4612 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4613
4614 // Insert any queued triggers (before metadata is locked)
4615 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004616 if (res < 0) {
4617 SET_ERR("RequestThread: Unable to insert triggers "
4618 "(capture request %d, HAL device: %s (%d)",
4619 halRequest->frame_number, strerror(-res), res);
4620 return INVALID_OPERATION;
4621 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004622
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004623 int triggerCount = res;
4624 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4625 mPrevTriggers = triggerCount;
4626
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004627 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004628 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004629
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004630 // If the request is the same as last, or we had triggers now or last time or
4631 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004632 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004633 (mPrevRequest != captureRequest || triggersMixedIn ||
4634 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004635 // Request settings are all the same within one batch, so only treat the first
4636 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004637 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004638 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004639 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004640 /**
4641 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004642 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004643 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004644 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004645 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004646 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004647 "(capture request %d, HAL device: %s (%d)",
4648 halRequest->frame_number, strerror(-res), res);
4649 return INVALID_OPERATION;
4650 }
4651
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004652 {
4653 // Correct metadata regions for distortion correction if enabled
4654 sp<Camera3Device> parent = mParent.promote();
4655 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004656 List<PhysicalCameraSettings>::iterator it;
4657 for (it = captureRequest->mSettingsList.begin();
4658 it != captureRequest->mSettingsList.end(); it++) {
4659 if (parent->mDistortionMappers.find(it->cameraId) ==
4660 parent->mDistortionMappers.end()) {
4661 continue;
4662 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004663
4664 if (!captureRequest->mDistortionCorrectionUpdated) {
4665 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4666 &(it->metadata));
4667 if (res != OK) {
4668 SET_ERR("RequestThread: Unable to correct capture requests "
4669 "for lens distortion for request %d: %s (%d)",
4670 halRequest->frame_number, strerror(-res), res);
4671 return INVALID_OPERATION;
4672 }
4673 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004674 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004675 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004676
4677 for (it = captureRequest->mSettingsList.begin();
4678 it != captureRequest->mSettingsList.end(); it++) {
4679 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4680 parent->mZoomRatioMappers.end()) {
4681 continue;
4682 }
4683
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004684 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004685 cameraIdsWithZoom.insert(it->cameraId);
4686 }
4687
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004688 if (!captureRequest->mZoomRatioUpdated) {
4689 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4690 &(it->metadata));
4691 if (res != OK) {
4692 SET_ERR("RequestThread: Unable to correct capture requests "
4693 "for zoom ratio for request %d: %s (%d)",
4694 halRequest->frame_number, strerror(-res), res);
4695 return INVALID_OPERATION;
4696 }
4697 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004698 }
4699 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004700 if (captureRequest->mRotateAndCropAuto &&
4701 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004702 for (it = captureRequest->mSettingsList.begin();
4703 it != captureRequest->mSettingsList.end(); it++) {
4704 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4705 if (mapper != parent->mRotateAndCropMappers.end()) {
4706 res = mapper->second.updateCaptureRequest(&(it->metadata));
4707 if (res != OK) {
4708 SET_ERR("RequestThread: Unable to correct capture requests "
4709 "for rotate-and-crop for request %d: %s (%d)",
4710 halRequest->frame_number, strerror(-res), res);
4711 return INVALID_OPERATION;
4712 }
4713 }
4714 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004715 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004716 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004717 }
4718 }
4719
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004720 /**
4721 * The request should be presorted so accesses in HAL
4722 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4723 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004724 captureRequest->mSettingsList.begin()->metadata.sort();
4725 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004727 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4729
4730 IF_ALOGV() {
4731 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4732 find_camera_metadata_ro_entry(
4733 halRequest->settings,
4734 ANDROID_CONTROL_AF_TRIGGER,
4735 &e
4736 );
4737 if (e.count > 0) {
4738 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4739 __FUNCTION__,
4740 halRequest->frame_number,
4741 e.data.u8[0]);
4742 }
4743 }
4744 } else {
4745 // leave request.settings NULL to indicate 'reuse latest given'
4746 ALOGVV("%s: Request settings are REUSED",
4747 __FUNCTION__);
4748 }
4749
Emilian Peevaebbe412018-01-15 13:53:24 +00004750 if (captureRequest->mSettingsList.size() > 1) {
4751 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4752 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004753 if (newRequest) {
4754 halRequest->physcam_settings =
4755 new const camera_metadata* [halRequest->num_physcam_settings];
4756 } else {
4757 halRequest->physcam_settings = nullptr;
4758 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004759 auto it = ++captureRequest->mSettingsList.begin();
4760 size_t i = 0;
4761 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4762 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004763 if (newRequest) {
4764 it->metadata.sort();
4765 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4766 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004767 }
4768 }
4769
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 uint32_t totalNumBuffers = 0;
4771
4772 // Fill in buffers
4773 if (captureRequest->mInputStream != NULL) {
4774 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004775
4776 halRequest->input_width = captureRequest->mInputBufferSize.width;
4777 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004778 totalNumBuffers += 1;
4779 } else {
4780 halRequest->input_buffer = NULL;
4781 }
4782
Emilian Peevf4816702020-04-03 15:44:51 -07004783 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004784 captureRequest->mOutputStreams.size());
4785 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004786 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004787
4788 sp<Camera3Device> parent = mParent.promote();
4789 if (parent == NULL) {
4790 // Should not happen, and nowhere to send errors to, so just log it
4791 CLOGE("RequestThread: Parent is gone");
4792 return INVALID_OPERATION;
4793 }
4794 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4795
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004796 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004797 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004798 sp<Camera3OutputStreamInterface> outputStream =
4799 captureRequest->mOutputStreams.editItemAt(j);
4800 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004801
4802 // Prepare video buffers for high speed recording on the first video request.
4803 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4804 // Only try to prepare video stream on the first video request.
4805 mPrepareVideoStream = false;
4806
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004807 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4808 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004809 while (res == NOT_ENOUGH_DATA) {
4810 res = outputStream->prepareNextBuffer();
4811 }
4812 if (res != OK) {
4813 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4814 __FUNCTION__, strerror(-res), res);
4815 outputStream->cancelPrepare();
4816 }
4817 }
4818
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004819 std::vector<size_t> uniqueSurfaceIds;
4820 res = outputStream->getUniqueSurfaceIds(
4821 captureRequest->mOutputSurfaces[streamId],
4822 &uniqueSurfaceIds);
4823 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4824 if (res != OK && res != INVALID_OPERATION) {
4825 ALOGE("%s: failed to query stream %d unique surface IDs",
4826 __FUNCTION__, streamId);
4827 return res;
4828 }
4829 if (res == OK) {
4830 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4831 }
4832
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004833 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004834 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004835 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004836 return TIMED_OUT;
4837 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004838 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004839 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004840 buffer.stream = outputStream->asHalStream();
4841 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004842 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004843 buffer.acquire_fence = -1;
4844 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004845 // Mark the output stream as unpreparable to block clients from calling
4846 // 'prepare' after this request reaches CameraHal and before the respective
4847 // buffers are requested.
4848 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004849 } else {
4850 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4851 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004852 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004853 if (res != OK) {
4854 // Can't get output buffer from gralloc queue - this could be due to
4855 // abandoned queue or other consumer misbehavior, so not a fatal
4856 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004857 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004858 " %s (%d)", strerror(-res), res);
4859
4860 return TIMED_OUT;
4861 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004862 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004863
4864 {
4865 sp<Camera3Device> parent = mParent.promote();
4866 if (parent != nullptr) {
4867 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4868 for (const auto& settings : captureRequest->mSettingsList) {
4869 if ((streamCameraId.isEmpty() &&
4870 parent->getId() == settings.cameraId.c_str()) ||
4871 streamCameraId == settings.cameraId.c_str()) {
4872 outputStream->fireBufferRequestForFrameNumber(
4873 captureRequest->mResultExtras.frameNumber,
4874 settings.metadata);
4875 }
4876 }
4877 }
4878 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004879
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004880 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08004881 int32_t streamGroupId = outputStream->getHalStreamGroupId();
4882 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
4883 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
4884 } else if (!physicalCameraId.isEmpty()) {
4885 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004886 }
4887 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004888 }
4889 totalNumBuffers += halRequest->num_output_buffers;
4890
4891 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004892 // If this request list is for constrained high speed recording (not
4893 // preview), and the current request is not the last one in the batch,
4894 // do not send callback to the app.
4895 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004896 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004897 hasCallback = false;
4898 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004899 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004900 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004901 const camera_metadata_t* settings = halRequest->settings;
4902 bool shouldUnlockSettings = false;
4903 if (settings == nullptr) {
4904 shouldUnlockSettings = true;
4905 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4906 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004907 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4908 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004909 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004910 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4911 isStillCapture = true;
4912 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4913 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004914
Emilian Peevaf8416e2021-02-04 17:52:43 -08004915 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004916 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004917 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4918 isZslCapture = true;
4919 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004920 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004921 res = parent->registerInFlight(halRequest->frame_number,
4922 totalNumBuffers, captureRequest->mResultExtras,
4923 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004924 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004925 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004926 requestedPhysicalCameras, isStillCapture, isZslCapture,
4927 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004928 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004929 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004930 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4931 ", burstId = %" PRId32 ".",
4932 __FUNCTION__,
4933 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4934 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004935
4936 if (shouldUnlockSettings) {
4937 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4938 }
4939
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004940 if (res != OK) {
4941 SET_ERR("RequestThread: Unable to register new in-flight request:"
4942 " %s (%d)", strerror(-res), res);
4943 return INVALID_OPERATION;
4944 }
4945 }
4946
4947 return OK;
4948}
4949
Igor Murashkin1e479c02013-09-06 16:55:14 -07004950CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004951 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004952 Mutex::Autolock al(mLatestRequestMutex);
4953
4954 ALOGV("RequestThread::%s", __FUNCTION__);
4955
4956 return mLatestRequest;
4957}
4958
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004959bool Camera3Device::RequestThread::isStreamPending(
4960 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004961 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004962 Mutex::Autolock l(mRequestLock);
4963
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004964 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004965 if (!nextRequest.submitted) {
4966 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4967 if (stream == s) return true;
4968 }
4969 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004970 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004971 }
4972
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004973 for (const auto& request : mRequestQueue) {
4974 for (const auto& s : request->mOutputStreams) {
4975 if (stream == s) return true;
4976 }
4977 if (stream == request->mInputStream) return true;
4978 }
4979
4980 for (const auto& request : mRepeatingRequests) {
4981 for (const auto& s : request->mOutputStreams) {
4982 if (stream == s) return true;
4983 }
4984 if (stream == request->mInputStream) return true;
4985 }
4986
4987 return false;
4988}
Jianing Weicb0652e2014-03-12 18:29:36 -07004989
Emilian Peev40ead602017-09-26 15:46:36 +01004990bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4991 ATRACE_CALL();
4992 Mutex::Autolock l(mRequestLock);
4993
4994 for (const auto& nextRequest : mNextRequests) {
4995 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4996 if (s.first == streamId) {
4997 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4998 if (it != s.second.end()) {
4999 return true;
5000 }
5001 }
5002 }
5003 }
5004
5005 for (const auto& request : mRequestQueue) {
5006 for (const auto& s : request->mOutputSurfaces) {
5007 if (s.first == streamId) {
5008 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5009 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005010 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005011 }
5012 }
5013 }
5014 }
5015
5016 for (const auto& request : mRepeatingRequests) {
5017 for (const auto& s : request->mOutputSurfaces) {
5018 if (s.first == streamId) {
5019 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5020 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005021 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005022 }
5023 }
5024 }
5025 }
5026
5027 return false;
5028}
5029
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005030void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5031 if (!mUseHalBufManager) {
5032 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5033 return;
5034 }
5035
5036 Mutex::Autolock pl(mPauseLock);
5037 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005038 mInterface->signalPipelineDrain(streamIds);
5039 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005040 }
5041 // If request thread is still busy, wait until paused then notify HAL
5042 mNotifyPipelineDrain = true;
5043 mStreamIdsToBeDrained = streamIds;
5044}
5045
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005046void Camera3Device::RequestThread::resetPipelineDrain() {
5047 Mutex::Autolock pl(mPauseLock);
5048 mNotifyPipelineDrain = false;
5049 mStreamIdsToBeDrained.clear();
5050}
5051
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005052void Camera3Device::RequestThread::clearPreviousRequest() {
5053 Mutex::Autolock l(mRequestLock);
5054 mPrevRequest.clear();
5055}
5056
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005057status_t Camera3Device::RequestThread::switchToOffline(
5058 const std::vector<int32_t>& streamsToKeep,
5059 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005060 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5061 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005062 Mutex::Autolock l(mRequestLock);
5063 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005065 // Wait until request thread is fully stopped
5066 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5067
5068 // We could also check for mRepeatingRequests.empty(), but the API interface
5069 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5070 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005071 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5072 while (!queueEmpty) {
5073 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5074 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005075 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005076 return res;
5077 } else if (res != OK) {
5078 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5079 __FUNCTION__, strerror(-res), res);
5080 return res;
5081 }
5082 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5083 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005084
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005085 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005086 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005087}
5088
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005089status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5090 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5091 ATRACE_CALL();
5092 Mutex::Autolock l(mTriggerMutex);
5093 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5094 return BAD_VALUE;
5095 }
5096 mRotateAndCropOverride = rotateAndCropValue;
5097 return OK;
5098}
5099
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005100status_t Camera3Device::RequestThread::setCameraMute(bool enabled) {
5101 ATRACE_CALL();
5102 Mutex::Autolock l(mTriggerMutex);
5103 if (enabled != mCameraMute) {
5104 mCameraMute = enabled;
5105 mCameraMuteChanged = true;
5106 }
5107 return OK;
5108}
5109
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005110nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005111 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005112 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005113 return mExpectedInflightDuration > kMinInflightDuration ?
5114 mExpectedInflightDuration : kMinInflightDuration;
5115}
5116
Emilian Peevaebbe412018-01-15 13:53:24 +00005117void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005118 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005119 if ((request == nullptr) || (halRequest == nullptr)) {
5120 ALOGE("%s: Invalid request!", __FUNCTION__);
5121 return;
5122 }
5123
5124 if (halRequest->num_physcam_settings > 0) {
5125 if (halRequest->physcam_id != nullptr) {
5126 delete [] halRequest->physcam_id;
5127 halRequest->physcam_id = nullptr;
5128 }
5129 if (halRequest->physcam_settings != nullptr) {
5130 auto it = ++(request->mSettingsList.begin());
5131 size_t i = 0;
5132 for (; it != request->mSettingsList.end(); it++, i++) {
5133 it->metadata.unlock(halRequest->physcam_settings[i]);
5134 }
5135 delete [] halRequest->physcam_settings;
5136 halRequest->physcam_settings = nullptr;
5137 }
5138 }
5139}
5140
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005141void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5142 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005143 return;
5144 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005145
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005146 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005147 // Skip the ones that have been submitted successfully.
5148 if (nextRequest.submitted) {
5149 continue;
5150 }
5151
5152 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005153 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5154 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005155
5156 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005157 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005158 }
5159
Emilian Peevaebbe412018-01-15 13:53:24 +00005160 cleanupPhysicalSettings(captureRequest, halRequest);
5161
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005162 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005163 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005164 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5165 }
5166
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005167 // No output buffer can be returned when using HAL buffer manager
5168 if (!mUseHalBufManager) {
5169 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5170 //Buffers that failed processing could still have
5171 //valid acquire fence.
5172 int acquireFence = (*outputBuffers)[i].acquire_fence;
5173 if (0 <= acquireFence) {
5174 close(acquireFence);
5175 outputBuffers->editItemAt(i).acquire_fence = -1;
5176 }
Emilian Peevf4816702020-04-03 15:44:51 -07005177 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005178 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5179 /*timestampIncreasing*/true, std::vector<size_t> (),
5180 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005181 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005182 }
5183
5184 if (sendRequestError) {
5185 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005186 sp<NotificationListener> listener = mListener.promote();
5187 if (listener != NULL) {
5188 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005189 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005190 captureRequest->mResultExtras);
5191 }
5192 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005193
5194 // Remove yet-to-be submitted inflight request from inflightMap
5195 {
5196 sp<Camera3Device> parent = mParent.promote();
5197 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005198 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005199 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5200 if (idx >= 0) {
5201 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5202 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5203 parent->removeInFlightMapEntryLocked(idx);
5204 }
5205 }
5206 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005207 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005208
5209 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005210 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005211}
5212
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005213void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005214 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005215 // Optimized a bit for the simple steady-state case (single repeating
5216 // request), to avoid putting that request in the queue temporarily.
5217 Mutex::Autolock l(mRequestLock);
5218
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005219 assert(mNextRequests.empty());
5220
5221 NextRequest nextRequest;
5222 nextRequest.captureRequest = waitForNextRequestLocked();
5223 if (nextRequest.captureRequest == nullptr) {
5224 return;
5225 }
5226
Emilian Peevf4816702020-04-03 15:44:51 -07005227 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005228 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005229 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005230
5231 // Wait for additional requests
5232 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5233
5234 for (size_t i = 1; i < batchSize; i++) {
5235 NextRequest additionalRequest;
5236 additionalRequest.captureRequest = waitForNextRequestLocked();
5237 if (additionalRequest.captureRequest == nullptr) {
5238 break;
5239 }
5240
Emilian Peevf4816702020-04-03 15:44:51 -07005241 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005242 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005243 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005244 }
5245
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005246 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005247 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005248 mNextRequests.size(), batchSize);
5249 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005250 }
5251
5252 return;
5253}
5254
5255sp<Camera3Device::CaptureRequest>
5256 Camera3Device::RequestThread::waitForNextRequestLocked() {
5257 status_t res;
5258 sp<CaptureRequest> nextRequest;
5259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005260 while (mRequestQueue.empty()) {
5261 if (!mRepeatingRequests.empty()) {
5262 // Always atomically enqueue all requests in a repeating request
5263 // list. Guarantees a complete in-sequence set of captures to
5264 // application.
5265 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005266 if (mFirstRepeating) {
5267 mFirstRepeating = false;
5268 } else {
5269 for (auto& request : requests) {
5270 // For repeating requests, override timestamp request using
5271 // the time a request is inserted into the request queue,
5272 // because the original repeating request will have an old
5273 // fixed timestamp.
5274 request->mRequestTimeNs = systemTime();
5275 }
5276 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005277 RequestList::const_iterator firstRequest =
5278 requests.begin();
5279 nextRequest = *firstRequest;
5280 mRequestQueue.insert(mRequestQueue.end(),
5281 ++firstRequest,
5282 requests.end());
5283 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005284
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005285 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005286
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005287 break;
5288 }
5289
5290 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5291
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005292 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5293 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005294 Mutex::Autolock pl(mPauseLock);
5295 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005296 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005297 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005298 if (mNotifyPipelineDrain) {
5299 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5300 mNotifyPipelineDrain = false;
5301 mStreamIdsToBeDrained.clear();
5302 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005303 // Let the tracker know
5304 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5305 if (statusTracker != 0) {
5306 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5307 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005308 sp<Camera3Device> parent = mParent.promote();
5309 if (parent != nullptr) {
5310 parent->mRequestBufferSM.onRequestThreadPaused();
5311 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005312 }
5313 // Stop waiting for now and let thread management happen
5314 return NULL;
5315 }
5316 }
5317
5318 if (nextRequest == NULL) {
5319 // Don't have a repeating request already in hand, so queue
5320 // must have an entry now.
5321 RequestList::iterator firstRequest =
5322 mRequestQueue.begin();
5323 nextRequest = *firstRequest;
5324 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005325 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5326 sp<NotificationListener> listener = mListener.promote();
5327 if (listener != NULL) {
5328 listener->notifyRequestQueueEmpty();
5329 }
5330 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005331 }
5332
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005333 // In case we've been unpaused by setPaused clearing mDoPause, need to
5334 // update internal pause state (capture/setRepeatingRequest unpause
5335 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005336 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005337 if (mPaused) {
5338 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5339 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5340 if (statusTracker != 0) {
5341 statusTracker->markComponentActive(mStatusId);
5342 }
5343 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005344 mPaused = false;
5345
5346 // Check if we've reconfigured since last time, and reset the preview
5347 // request if so. Can't use 'NULL request == repeat' across configure calls.
5348 if (mReconfigured) {
5349 mPrevRequest.clear();
5350 mReconfigured = false;
5351 }
5352
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005353 if (nextRequest != NULL) {
5354 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005355 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5356 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005357
5358 // Since RequestThread::clear() removes buffers from the input stream,
5359 // get the right buffer here before unlocking mRequestLock
5360 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005361 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5362 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005363 if (res != OK) {
5364 // Can't get input buffer from gralloc queue - this could be due to
5365 // disconnected queue or other producer misbehavior, so not a fatal
5366 // error
5367 ALOGE("%s: Can't get input buffer, skipping request:"
5368 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005369
5370 sp<NotificationListener> listener = mListener.promote();
5371 if (listener != NULL) {
5372 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005373 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005374 nextRequest->mResultExtras);
5375 }
5376 return NULL;
5377 }
5378 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005379 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005380
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005381 return nextRequest;
5382}
5383
5384bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005385 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005386 status_t res;
5387 Mutex::Autolock l(mPauseLock);
5388 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005389 if (mPaused == false) {
5390 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005391 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005392 if (mNotifyPipelineDrain) {
5393 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5394 mNotifyPipelineDrain = false;
5395 mStreamIdsToBeDrained.clear();
5396 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005397 // Let the tracker know
5398 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5399 if (statusTracker != 0) {
5400 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5401 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005402 sp<Camera3Device> parent = mParent.promote();
5403 if (parent != nullptr) {
5404 parent->mRequestBufferSM.onRequestThreadPaused();
5405 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005406 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005407
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005408 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005409 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005410 return true;
5411 }
5412 }
5413 // We don't set mPaused to false here, because waitForNextRequest needs
5414 // to further manage the paused state in case of starvation.
5415 return false;
5416}
5417
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005418void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005419 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005420 // With work to do, mark thread as unpaused.
5421 // If paused by request (setPaused), don't resume, to avoid
5422 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005423 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005424 Mutex::Autolock p(mPauseLock);
5425 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005426 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5427 if (mPaused) {
5428 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5429 if (statusTracker != 0) {
5430 statusTracker->markComponentActive(mStatusId);
5431 }
5432 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005433 mPaused = false;
5434 }
5435}
5436
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005437void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5438 sp<Camera3Device> parent = mParent.promote();
5439 if (parent != NULL) {
5440 va_list args;
5441 va_start(args, fmt);
5442
5443 parent->setErrorStateV(fmt, args);
5444
5445 va_end(args);
5446 }
5447}
5448
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005449status_t Camera3Device::RequestThread::insertTriggers(
5450 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005451 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005452 Mutex::Autolock al(mTriggerMutex);
5453
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005454 sp<Camera3Device> parent = mParent.promote();
5455 if (parent == NULL) {
5456 CLOGE("RequestThread: Parent is gone");
5457 return DEAD_OBJECT;
5458 }
5459
Emilian Peevaebbe412018-01-15 13:53:24 +00005460 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005461 size_t count = mTriggerMap.size();
5462
5463 for (size_t i = 0; i < count; ++i) {
5464 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005465 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005466
5467 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5468 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5469 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005470 if (isAeTrigger) {
5471 request->mResultExtras.precaptureTriggerId = triggerId;
5472 mCurrentPreCaptureTriggerId = triggerId;
5473 } else {
5474 request->mResultExtras.afTriggerId = triggerId;
5475 mCurrentAfTriggerId = triggerId;
5476 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005477 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005478 }
5479
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005480 camera_metadata_entry entry = metadata.find(tag);
5481
5482 if (entry.count > 0) {
5483 /**
5484 * Already has an entry for this trigger in the request.
5485 * Rewrite it with our requested trigger value.
5486 */
5487 RequestTrigger oldTrigger = trigger;
5488
5489 oldTrigger.entryValue = entry.data.u8[0];
5490
5491 mTriggerReplacedMap.add(tag, oldTrigger);
5492 } else {
5493 /**
5494 * More typical, no trigger entry, so we just add it
5495 */
5496 mTriggerRemovedMap.add(tag, trigger);
5497 }
5498
5499 status_t res;
5500
5501 switch (trigger.getTagType()) {
5502 case TYPE_BYTE: {
5503 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5504 res = metadata.update(tag,
5505 &entryValue,
5506 /*count*/1);
5507 break;
5508 }
5509 case TYPE_INT32:
5510 res = metadata.update(tag,
5511 &trigger.entryValue,
5512 /*count*/1);
5513 break;
5514 default:
5515 ALOGE("%s: Type not supported: 0x%x",
5516 __FUNCTION__,
5517 trigger.getTagType());
5518 return INVALID_OPERATION;
5519 }
5520
5521 if (res != OK) {
5522 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5523 ", value %d", __FUNCTION__, trigger.getTagName(),
5524 trigger.entryValue);
5525 return res;
5526 }
5527
5528 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5529 trigger.getTagName(),
5530 trigger.entryValue);
5531 }
5532
5533 mTriggerMap.clear();
5534
5535 return count;
5536}
5537
5538status_t Camera3Device::RequestThread::removeTriggers(
5539 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005540 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005541 Mutex::Autolock al(mTriggerMutex);
5542
Emilian Peevaebbe412018-01-15 13:53:24 +00005543 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005544
5545 /**
5546 * Replace all old entries with their old values.
5547 */
5548 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5549 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5550
5551 status_t res;
5552
5553 uint32_t tag = trigger.metadataTag;
5554 switch (trigger.getTagType()) {
5555 case TYPE_BYTE: {
5556 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5557 res = metadata.update(tag,
5558 &entryValue,
5559 /*count*/1);
5560 break;
5561 }
5562 case TYPE_INT32:
5563 res = metadata.update(tag,
5564 &trigger.entryValue,
5565 /*count*/1);
5566 break;
5567 default:
5568 ALOGE("%s: Type not supported: 0x%x",
5569 __FUNCTION__,
5570 trigger.getTagType());
5571 return INVALID_OPERATION;
5572 }
5573
5574 if (res != OK) {
5575 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5576 ", trigger value %d", __FUNCTION__,
5577 trigger.getTagName(), trigger.entryValue);
5578 return res;
5579 }
5580 }
5581 mTriggerReplacedMap.clear();
5582
5583 /**
5584 * Remove all new entries.
5585 */
5586 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5587 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5588 status_t res = metadata.erase(trigger.metadataTag);
5589
5590 if (res != OK) {
5591 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5592 ", trigger value %d", __FUNCTION__,
5593 trigger.getTagName(), trigger.entryValue);
5594 return res;
5595 }
5596 }
5597 mTriggerRemovedMap.clear();
5598
5599 return OK;
5600}
5601
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005602status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005603 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005604 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005605 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005606 status_t res;
5607
Emilian Peevaebbe412018-01-15 13:53:24 +00005608 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005609
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005610 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005611 // exists
5612 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5613 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5614 if (afTrigger.count > 0 &&
5615 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5616 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005617 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005618 if (res != OK) return res;
5619 }
5620
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005621 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005622 // if none already exists
5623 camera_metadata_entry pcTrigger =
5624 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5625 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5626 if (pcTrigger.count > 0 &&
5627 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5628 pcId.count == 0) {
5629 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005630 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005631 if (res != OK) return res;
5632 }
5633
5634 return OK;
5635}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005636
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005637bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5638 const sp<CaptureRequest> &request) {
5639 ATRACE_CALL();
5640
5641 if (request->mRotateAndCropAuto) {
5642 Mutex::Autolock l(mTriggerMutex);
5643 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5644
5645 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5646 if (rotateAndCropEntry.count > 0) {
5647 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5648 return false;
5649 } else {
5650 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5651 return true;
5652 }
5653 } else {
5654 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5655 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5656 &rotateAndCrop_u8, 1);
5657 return true;
5658 }
5659 }
5660 return false;
5661}
5662
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005663bool Camera3Device::RequestThread::overrideTestPattern(
5664 const sp<CaptureRequest> &request) {
5665 ATRACE_CALL();
5666
5667 Mutex::Autolock l(mTriggerMutex);
5668
5669 bool changed = false;
5670
5671 int32_t testPatternMode = request->mOriginalTestPatternMode;
5672 int32_t testPatternData[4] = {
5673 request->mOriginalTestPatternData[0],
5674 request->mOriginalTestPatternData[1],
5675 request->mOriginalTestPatternData[2],
5676 request->mOriginalTestPatternData[3]
5677 };
5678
5679 if (mCameraMute) {
5680 testPatternMode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
5681 testPatternData[0] = 0;
5682 testPatternData[1] = 0;
5683 testPatternData[2] = 0;
5684 testPatternData[3] = 0;
5685 }
5686
5687 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5688
5689 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5690 if (testPatternEntry.count > 0) {
5691 if (testPatternEntry.data.i32[0] != testPatternMode) {
5692 testPatternEntry.data.i32[0] = testPatternMode;
5693 changed = true;
5694 }
5695 } else {
5696 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5697 &testPatternMode, 1);
5698 changed = true;
5699 }
5700
5701 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5702 if (testPatternColor.count > 0) {
5703 for (size_t i = 0; i < 4; i++) {
5704 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5705 testPatternColor.data.i32[i] = testPatternData[i];
5706 changed = true;
5707 }
5708 }
5709 } else {
5710 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5711 (int32_t*)testPatternData, 4);
5712 changed = true;
5713 }
5714
5715 return changed;
5716}
5717
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005718/**
5719 * PreparerThread inner class methods
5720 */
5721
5722Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005723 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005724 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005725}
5726
5727Camera3Device::PreparerThread::~PreparerThread() {
5728 Thread::requestExitAndWait();
5729 if (mCurrentStream != nullptr) {
5730 mCurrentStream->cancelPrepare();
5731 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5732 mCurrentStream.clear();
5733 }
5734 clear();
5735}
5736
Ruben Brunkc78ac262015-08-13 17:58:46 -07005737status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005738 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005739 status_t res;
5740
5741 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005742 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005743
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005744 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005745 if (res == OK) {
5746 // No preparation needed, fire listener right off
5747 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005748 if (listener != NULL) {
5749 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005750 }
5751 return OK;
5752 } else if (res != NOT_ENOUGH_DATA) {
5753 return res;
5754 }
5755
5756 // Need to prepare, start up thread if necessary
5757 if (!mActive) {
5758 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5759 // isn't running
5760 Thread::requestExitAndWait();
5761 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5762 if (res != OK) {
5763 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005764 if (listener != NULL) {
5765 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005766 }
5767 return res;
5768 }
5769 mCancelNow = false;
5770 mActive = true;
5771 ALOGV("%s: Preparer stream started", __FUNCTION__);
5772 }
5773
5774 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005775 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005776 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5777
5778 return OK;
5779}
5780
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005781void Camera3Device::PreparerThread::pause() {
5782 ATRACE_CALL();
5783
5784 Mutex::Autolock l(mLock);
5785
5786 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5787 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5788 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5789 int currentMaxCount = mCurrentMaxCount;
5790 mPendingStreams.clear();
5791 mCancelNow = true;
5792 while (mActive) {
5793 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5794 if (res == TIMED_OUT) {
5795 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5796 return;
5797 } else if (res != OK) {
5798 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5799 return;
5800 }
5801 }
5802
5803 //Check whether the prepare thread was able to complete the current
5804 //stream. In case work is still pending emplace it along with the rest
5805 //of the streams in the pending list.
5806 if (currentStream != nullptr) {
5807 if (!mCurrentPrepareComplete) {
5808 pendingStreams.emplace(currentMaxCount, currentStream);
5809 }
5810 }
5811
5812 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5813 for (const auto& it : mPendingStreams) {
5814 it.second->cancelPrepare();
5815 }
5816}
5817
5818status_t Camera3Device::PreparerThread::resume() {
5819 ATRACE_CALL();
5820 status_t res;
5821
5822 Mutex::Autolock l(mLock);
5823 sp<NotificationListener> listener = mListener.promote();
5824
5825 if (mActive) {
5826 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5827 return NO_INIT;
5828 }
5829
5830 auto it = mPendingStreams.begin();
5831 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005832 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005833 if (res == OK) {
5834 if (listener != NULL) {
5835 listener->notifyPrepared(it->second->getId());
5836 }
5837 it = mPendingStreams.erase(it);
5838 } else if (res != NOT_ENOUGH_DATA) {
5839 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5840 res, strerror(-res));
5841 it = mPendingStreams.erase(it);
5842 } else {
5843 it++;
5844 }
5845 }
5846
5847 if (mPendingStreams.empty()) {
5848 return OK;
5849 }
5850
5851 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5852 if (res != OK) {
5853 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5854 __FUNCTION__, res, strerror(-res));
5855 return res;
5856 }
5857 mCancelNow = false;
5858 mActive = true;
5859 ALOGV("%s: Preparer stream started", __FUNCTION__);
5860
5861 return OK;
5862}
5863
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005864status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005865 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005866 Mutex::Autolock l(mLock);
5867
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005868 for (const auto& it : mPendingStreams) {
5869 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005870 }
5871 mPendingStreams.clear();
5872 mCancelNow = true;
5873
5874 return OK;
5875}
5876
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005877void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005878 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005879 Mutex::Autolock l(mLock);
5880 mListener = listener;
5881}
5882
5883bool Camera3Device::PreparerThread::threadLoop() {
5884 status_t res;
5885 {
5886 Mutex::Autolock l(mLock);
5887 if (mCurrentStream == nullptr) {
5888 // End thread if done with work
5889 if (mPendingStreams.empty()) {
5890 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5891 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5892 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5893 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005894 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005895 return false;
5896 }
5897
5898 // Get next stream to prepare
5899 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005900 mCurrentStream = it->second;
5901 mCurrentMaxCount = it->first;
5902 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005903 mPendingStreams.erase(it);
5904 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5905 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5906 } else if (mCancelNow) {
5907 mCurrentStream->cancelPrepare();
5908 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5909 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5910 mCurrentStream.clear();
5911 mCancelNow = false;
5912 return true;
5913 }
5914 }
5915
5916 res = mCurrentStream->prepareNextBuffer();
5917 if (res == NOT_ENOUGH_DATA) return true;
5918 if (res != OK) {
5919 // Something bad happened; try to recover by cancelling prepare and
5920 // signalling listener anyway
5921 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5922 mCurrentStream->getId(), res, strerror(-res));
5923 mCurrentStream->cancelPrepare();
5924 }
5925
5926 // This stream has finished, notify listener
5927 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005928 sp<NotificationListener> listener = mListener.promote();
5929 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005930 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5931 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005932 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005933 }
5934
5935 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5936 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005937 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005938
5939 return true;
5940}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005941
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005942status_t Camera3Device::RequestBufferStateMachine::initialize(
5943 sp<camera3::StatusTracker> statusTracker) {
5944 if (statusTracker == nullptr) {
5945 ALOGE("%s: statusTracker is null", __FUNCTION__);
5946 return BAD_VALUE;
5947 }
5948
5949 std::lock_guard<std::mutex> lock(mLock);
5950 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005951 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005952 return OK;
5953}
5954
5955bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5956 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005957 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005958 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005959 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005960 return true;
5961 }
5962 return false;
5963}
5964
5965void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5966 std::lock_guard<std::mutex> lock(mLock);
5967 if (!mRequestBufferOngoing) {
5968 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5969 return;
5970 }
5971 mRequestBufferOngoing = false;
5972 if (mStatus == RB_STATUS_PENDING_STOP) {
5973 checkSwitchToStopLocked();
5974 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005975 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005976}
5977
5978void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5979 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005980 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005981 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005982 return;
5983}
5984
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005985void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005986 std::lock_guard<std::mutex> lock(mLock);
5987 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005988 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5989 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005990 mInflightMapEmpty = false;
5991 if (mStatus == RB_STATUS_STOPPED) {
5992 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005993 }
5994 return;
5995}
5996
5997void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5998 std::lock_guard<std::mutex> lock(mLock);
5999 mRequestThreadPaused = true;
6000 if (mStatus == RB_STATUS_PENDING_STOP) {
6001 checkSwitchToStopLocked();
6002 }
6003 return;
6004}
6005
6006void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6007 std::lock_guard<std::mutex> lock(mLock);
6008 mInflightMapEmpty = true;
6009 if (mStatus == RB_STATUS_PENDING_STOP) {
6010 checkSwitchToStopLocked();
6011 }
6012 return;
6013}
6014
6015void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6016 std::lock_guard<std::mutex> lock(mLock);
6017 if (!checkSwitchToStopLocked()) {
6018 mStatus = RB_STATUS_PENDING_STOP;
6019 }
6020 return;
6021}
6022
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006023bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6024 std::lock_guard<std::mutex> lock(mLock);
6025 if (mRequestBufferOngoing) {
6026 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6027 __FUNCTION__);
6028 return false;
6029 }
6030 mSwitchedToOffline = true;
6031 mInflightMapEmpty = true;
6032 mRequestThreadPaused = true;
6033 mStatus = RB_STATUS_STOPPED;
6034 return true;
6035}
6036
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006037void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6038 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6039 if (statusTracker != nullptr) {
6040 if (active) {
6041 statusTracker->markComponentActive(mRequestBufferStatusId);
6042 } else {
6043 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6044 }
6045 }
6046}
6047
6048bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6049 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6050 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006051 return true;
6052 }
6053 return false;
6054}
6055
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006056bool Camera3Device::startRequestBuffer() {
6057 return mRequestBufferSM.startRequestBuffer();
6058}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006059
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006060void Camera3Device::endRequestBuffer() {
6061 mRequestBufferSM.endRequestBuffer();
6062}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006064nsecs_t Camera3Device::getWaitDuration() {
6065 return kBaseGetBufferWait + getExpectedInFlightDuration();
6066}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006068void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6069 mInterface->getInflightBufferKeys(out);
6070}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006071
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006072void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6073 mInterface->getInflightRequestBufferKeys(out);
6074}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006075
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006076std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6077 std::vector<sp<Camera3StreamInterface>> ret;
6078 bool hasInputStream = mInputStream != nullptr;
6079 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6080 if (hasInputStream) {
6081 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006082 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006083 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6084 ret.push_back(mOutputStreams[i]);
6085 }
6086 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6087 ret.push_back(mDeletedStreams[i]);
6088 }
6089 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006090}
6091
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006092status_t Camera3Device::switchToOffline(
6093 const std::vector<int32_t>& streamsToKeep,
6094 /*out*/ sp<CameraOfflineSessionBase>* session) {
6095 ATRACE_CALL();
6096 if (session == nullptr) {
6097 ALOGE("%s: session must not be null", __FUNCTION__);
6098 return BAD_VALUE;
6099 }
6100
6101 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006102
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006103 bool hasInputStream = mInputStream != nullptr;
6104 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6105 bool inputStreamSupportsOffline = hasInputStream ?
6106 mInputStream->getOfflineProcessingSupport() : false;
6107 auto outputStreamIds = mOutputStreams.getStreamIds();
6108 auto streamIds = outputStreamIds;
6109 if (hasInputStream) {
6110 streamIds.push_back(mInputStream->getId());
6111 }
6112
6113 // Check all streams in streamsToKeep supports offline mode
6114 for (auto id : streamsToKeep) {
6115 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6116 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6117 return BAD_VALUE;
6118 } else if (id == inputStreamId) {
6119 if (!inputStreamSupportsOffline) {
6120 ALOGE("%s: input stream %d cannot be switched to offline",
6121 __FUNCTION__, id);
6122 return BAD_VALUE;
6123 }
6124 } else {
6125 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6126 if (!stream->getOfflineProcessingSupport()) {
6127 ALOGE("%s: output stream %d cannot be switched to offline",
6128 __FUNCTION__, id);
6129 return BAD_VALUE;
6130 }
6131 }
6132 }
6133
6134 // TODO: block surface sharing and surface group streams until we can support them
6135
6136 // Stop repeating request, wait until all remaining requests are submitted, then call into
6137 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006138 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6139 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006140 camera3::BufferRecords bufferRecords;
6141 status_t ret = mRequestThread->switchToOffline(
6142 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006143
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006144 if (ret != OK) {
6145 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6146 return ret;
6147 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006148
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006149 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6150 if (!succ) {
6151 SET_ERR("HAL must not be calling requestStreamBuffers call");
6152 // TODO: block ALL callbacks from HAL till app configured new streams?
6153 return UNKNOWN_ERROR;
6154 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006155
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006156 // Verify offlineSessionInfo
6157 std::vector<int32_t> offlineStreamIds;
6158 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6159 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6160 // verify stream IDs
6161 int32_t id = offlineStream.id;
6162 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6163 SET_ERR("stream ID %d not found!", id);
6164 return UNKNOWN_ERROR;
6165 }
6166
6167 // When not using HAL buf manager, only allow streams requested by app to be preserved
6168 if (!mUseHalBufManager) {
6169 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6170 SET_ERR("stream ID %d must not be switched to offline!", id);
6171 return UNKNOWN_ERROR;
6172 }
6173 }
6174
6175 offlineStreamIds.push_back(id);
6176 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6177 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6178 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6179 // Verify number of outstanding buffers
6180 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6181 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6182 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6183 return UNKNOWN_ERROR;
6184 }
6185 }
6186
6187 // Verify all streams to be deleted don't have any outstanding buffers
6188 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6189 inputStreamId) == offlineStreamIds.end()) {
6190 if (mInputStream->hasOutstandingBuffers()) {
6191 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6192 inputStreamId, mInputStream->getOutstandingBuffersCount());
6193 return UNKNOWN_ERROR;
6194 }
6195 }
6196
6197 for (const auto& outStreamId : outputStreamIds) {
6198 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6199 outStreamId) == offlineStreamIds.end()) {
6200 auto outStream = mOutputStreams.get(outStreamId);
6201 if (outStream->hasOutstandingBuffers()) {
6202 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6203 outStreamId, outStream->getOutstandingBuffersCount());
6204 return UNKNOWN_ERROR;
6205 }
6206 }
6207 }
6208
6209 InFlightRequestMap offlineReqs;
6210 // Verify inflight requests and their pending buffers
6211 {
6212 std::lock_guard<std::mutex> l(mInFlightLock);
6213 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6214 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6215 if (idx == NAME_NOT_FOUND) {
6216 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6217 return UNKNOWN_ERROR;
6218 }
6219
6220 const auto& inflightReq = mInFlightMap.valueAt(idx);
6221 // TODO: check specific stream IDs
6222 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6223 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6224 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6225 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6226 return UNKNOWN_ERROR;
6227 }
6228 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6229 }
6230 }
6231
6232 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006233 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006234 camera3::StreamSet offlineStreamSet;
6235 sp<camera3::Camera3Stream> inputStream;
6236 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6237 int32_t id = offlineStream.id;
6238 if (mInputStream != nullptr && id == mInputStream->getId()) {
6239 inputStream = mInputStream;
6240 } else {
6241 offlineStreamSet.add(id, mOutputStreams.get(id));
6242 }
6243 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006244
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006245 // TODO: check if we need to lock before copying states
6246 // though technically no other thread should be talking to Camera3Device at this point
6247 Camera3OfflineStates offlineStates(
6248 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006249 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6250 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6251 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6252 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6253 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6254 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6255 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006256
6257 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6258 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6259
6260 // Delete all streams that has been transferred to offline session
6261 Mutex::Autolock l(mLock);
6262 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6263 int32_t id = offlineStream.id;
6264 if (mInputStream != nullptr && id == mInputStream->getId()) {
6265 mInputStream.clear();
6266 } else {
6267 mOutputStreams.remove(id);
6268 }
6269 }
6270
6271 // disconnect all other streams and switch to UNCONFIGURED state
6272 if (mInputStream != nullptr) {
6273 ret = mInputStream->disconnect();
6274 if (ret != OK) {
6275 SET_ERR_L("disconnect input stream failed!");
6276 return UNKNOWN_ERROR;
6277 }
6278 }
6279
6280 for (auto streamId : mOutputStreams.getStreamIds()) {
6281 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6282 ret = stream->disconnect();
6283 if (ret != OK) {
6284 SET_ERR_L("disconnect output stream %d failed!", streamId);
6285 return UNKNOWN_ERROR;
6286 }
6287 }
6288
6289 mInputStream.clear();
6290 mOutputStreams.clear();
6291 mNeedConfig = true;
6292 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6293 mOperatingMode = NO_MODE;
6294 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006295 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006296
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006297 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006298 // TO be done by CameraDeviceClient/Camera3OfflineSession
6299 // register the offline client to camera service
6300 // Setup result passthing threads etc
6301 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6302 // TODO: check how many onIdle callback will be sent
6303 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006304}
6305
Emilian Peevcc0b7952020-01-07 13:54:47 -08006306void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6307 ATRACE_CALL();
6308
6309 if (offlineStreamIds == nullptr) {
6310 return;
6311 }
6312
6313 Mutex::Autolock il(mInterfaceLock);
6314
6315 auto streamIds = mOutputStreams.getStreamIds();
6316 bool hasInputStream = mInputStream != nullptr;
6317 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6318 offlineStreamIds->push_back(mInputStream->getId());
6319 }
6320
6321 for (const auto & streamId : streamIds) {
6322 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6323 // Streams that use the camera buffer manager are currently not supported in
6324 // offline mode
6325 if (stream->getOfflineProcessingSupport() &&
6326 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6327 offlineStreamIds->push_back(streamId);
6328 }
6329 }
6330}
6331
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006332status_t Camera3Device::setRotateAndCropAutoBehavior(
6333 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6334 ATRACE_CALL();
6335 Mutex::Autolock il(mInterfaceLock);
6336 Mutex::Autolock l(mLock);
6337 if (mRequestThread == nullptr) {
6338 return INVALID_OPERATION;
6339 }
6340 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6341}
6342
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006343bool Camera3Device::supportsCameraMute() {
6344 Mutex::Autolock il(mInterfaceLock);
6345 Mutex::Autolock l(mLock);
6346
6347 return mSupportCameraMute;
6348}
6349
6350status_t Camera3Device::setCameraMute(bool enabled) {
6351 ATRACE_CALL();
6352 Mutex::Autolock il(mInterfaceLock);
6353 Mutex::Autolock l(mLock);
6354
6355 if (mRequestThread == nullptr || !mSupportCameraMute) {
6356 return INVALID_OPERATION;
6357 }
6358 return mRequestThread->setCameraMute(enabled);
6359}
6360
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006361}; // namespace android