blob: 18696a3600902246fe91b3d4300c2c2f6e3496f2 [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
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080086 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070088 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070091 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000093 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010094 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070095 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070096 mNeedFixupMonochromeTags(false),
97 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080098{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
103Camera3Device::~Camera3Device()
104{
105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700107 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108}
109
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800111 return mId;
112}
113
Emilian Peevbd8c5032018-02-14 23:05:40 +0000114status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 ATRACE_CALL();
116 Mutex::Autolock il(mInterfaceLock);
117 Mutex::Autolock l(mLock);
118
119 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
120 if (mStatus != STATUS_UNINITIALIZED) {
121 CLOGE("Already initialized!");
122 return INVALID_OPERATION;
123 }
124 if (manager == nullptr) return INVALID_OPERATION;
125
126 sp<ICameraDeviceSession> session;
127 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800128 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 /*out*/ &session);
130 ATRACE_END();
131 if (res != OK) {
132 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
133 return res;
134 }
135
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700136 res = manager->getCameraCharacteristics(mId.string(), mOverrideForPerfClass, &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800137 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800139 session->close();
140 return res;
141 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800142 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800143
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700145 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (isLogical) {
147 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700148 // Do not override characteristics for physical cameras
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700149 res = manager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700150 physicalId, /*overrideForPerfClass*/false, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700151 if (res != OK) {
152 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
153 physicalId.c_str(), strerror(-res), res);
154 session->close();
155 return res;
156 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800158 bool usePrecorrectArray =
159 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
160 if (usePrecorrectArray) {
161 res = mDistortionMappers[physicalId].setupStaticInfo(
162 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700163 if (res != OK) {
164 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
165 "correction", physicalId.c_str());
166 session->close();
167 return res;
168 }
169 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800170
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800171 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800172 &mPhysicalDeviceInfoMap[physicalId],
173 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700174 }
175 }
176
Yifan Hongf79b5542017-04-11 14:44:25 -0700177 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700178 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
179 [&queue](const auto& descriptor) {
180 queue = std::make_shared<RequestMetadataQueue>(descriptor);
181 if (!queue->isValid() || queue->availableToWrite() <= 0) {
182 ALOGE("HAL returns empty request metadata fmq, not use it");
183 queue = nullptr;
184 // don't use the queue onwards.
185 }
186 });
187 if (!requestQueueRet.isOk()) {
188 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
189 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700190 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700191 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192
193 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700195 [&resQueue](const auto& descriptor) {
196 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
197 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700198 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700199 resQueue = nullptr;
200 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 }
202 });
203 if (!resultQueueRet.isOk()) {
204 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
205 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700206 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700207 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 IF_ALOGV() {
209 session->interfaceChain([](
210 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
211 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800212 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700213 ALOGV(" %s", iface.c_str());
214 }
215 });
216 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700217
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800218 camera_metadata_entry bufMgrMode =
219 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
220 if (bufMgrMode.count > 0) {
221 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
222 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
223 }
224
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700225 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
226 for (size_t i = 0; i < capabilities.count; i++) {
227 uint8_t capability = capabilities.data.u8[i];
228 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
229 mSupportOfflineProcessing = true;
230 }
231 }
232
233 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000234 std::string providerType;
235 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000236 mTagMonitor.initialize(mVendorTagId);
237 if (!monitorTags.isEmpty()) {
238 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
239 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800240
Shuzhen Wang268a1362018-10-16 16:32:59 -0700241 // Metadata tags needs fixup for monochrome camera device version less
242 // than 3.5.
243 hardware::hidl_version maxVersion{0,0};
244 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
245 if (res != OK) {
246 ALOGE("%s: Error in getting camera device version id: %s (%d)",
247 __FUNCTION__, strerror(-res), res);
248 return res;
249 }
250 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
251 maxVersion.get_major(), maxVersion.get_minor());
252
253 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700254 for (size_t i = 0; i < capabilities.count; i++) {
255 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700256 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
257 isMonochrome = true;
258 }
259 }
260 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
261
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 return initializeCommonLocked();
263}
264
265status_t Camera3Device::initializeCommonLocked() {
266
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 /** Start up status tracker thread */
268 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800269 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270 if (res != OK) {
271 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
272 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800273 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 mStatusTracker.clear();
275 return res;
276 }
277
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700278 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700279 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700280
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700281 if (mUseHalBufManager) {
282 res = mRequestBufferSM.initialize(mStatusTracker);
283 if (res != OK) {
284 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
285 strerror(-res), res);
286 mInterface->close();
287 mStatusTracker.clear();
288 return res;
289 }
290 }
291
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800292 /** Create buffer manager */
293 mBufferManager = new Camera3BufferManager();
294
295 Vector<int32_t> sessionParamKeys;
296 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
297 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
298 if (sessionKeysEntry.count > 0) {
299 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
300 }
301
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700302 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700303 mRequestThread = new RequestThread(
304 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800305 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700307 SET_ERR_L("Unable to start request queue thread: %s (%d)",
308 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800309 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800311 return res;
312 }
313
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700314 mPreparerThread = new PreparerThread();
315
Ruben Brunk183f0562015-08-12 12:55:02 -0700316 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800317 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400318 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700319 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800321 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800322
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800323 // Measure the clock domain offset between camera and video/hw_composer
324 camera_metadata_entry timestampSource =
325 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
326 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
327 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
328 mTimestampOffset = getMonoToBoottimeOffset();
329 }
330
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100332 camera_metadata_entry partialResultsCount =
333 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
334 if (partialResultsCount.count > 0) {
335 mNumPartialResults = partialResultsCount.data.i32[0];
336 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700337 }
338
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800339 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
340 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700341 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700342 if (res != OK) {
343 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
344 return res;
345 }
346 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800348 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800349 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800351 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
352 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
353 }
354
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800355 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
356 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
357 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700358 if (availableTestPatternModes.data.i32[i] ==
359 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800360 mSupportCameraMute = true;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700361 mSupportTestPatternSolidColor = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800362 break;
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -0700363 } else if (availableTestPatternModes.data.i32[i] ==
364 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
365 mSupportCameraMute = true;
366 mSupportTestPatternSolidColor = false;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -0800367 }
368 }
369
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800370 mInjectionMethods = new Camera3DeviceInjectionMethods(this);
371
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800372 return OK;
373}
374
375status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700376 return disconnectImpl();
377}
378
379status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800380 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700381 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800382
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700383 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700384 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800386 Mutex::Autolock il(mInterfaceLock);
387 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
388 {
389 Mutex::Autolock l(mLock);
390 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800392 if (mStatus == STATUS_ACTIVE ||
393 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
394 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700395 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800396 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 } else {
399 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
400 if (res != OK) {
401 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
402 maxExpectedDuration);
403 // Continue to close device even in case of error
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700406 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 if (mStatus == STATUS_ERROR) {
409 CLOGE("Shutting down in an error state");
410 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700411
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800412 if (mStatusTracker != NULL) {
413 mStatusTracker->requestExit();
414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800416 if (mRequestThread != NULL) {
417 mRequestThread->requestExit();
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800420 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
421 for (size_t i = 0; i < mOutputStreams.size(); i++) {
422 streams.push_back(mOutputStreams[i]);
423 }
424 if (mInputStream != nullptr) {
425 streams.push_back(mInputStream);
426 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700427 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700428 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800429 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
430 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700431 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
432 // HAL may be in a bad state, so waiting for request thread
433 // (which may be stuck in the HAL processCaptureRequest call)
434 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800435 // give up mInterfaceLock here and then lock it again. Could this lead
436 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700437 mRequestThread->join();
438 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700439 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 Mutex::Autolock il(mInterfaceLock);
441 if (mStatusTracker != NULL) {
442 mStatusTracker->join();
443 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800444
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800445 if (mInjectionMethods->isInjecting()) {
446 mInjectionMethods->stopInjection();
447 }
448
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800449 HalInterface* interface;
450 {
451 Mutex::Autolock l(mLock);
452 mRequestThread.clear();
453 Mutex::Autolock stLock(mTrackerLock);
454 mStatusTracker.clear();
455 interface = mInterface.get();
456 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700457
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800458 // Call close without internal mutex held, as the HAL close may need to
459 // wait on assorted callbacks,etc, to complete before it can return.
460 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700461
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800462 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800463
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800464 {
465 Mutex::Autolock l(mLock);
466 mInterface->clear();
467 mOutputStreams.clear();
468 mInputStream.clear();
469 mDeletedStreams.clear();
470 mBufferManager.clear();
471 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
472 }
473
474 for (auto& weakStream : streams) {
475 sp<Camera3StreamInterface> stream = weakStream.promote();
476 if (stream != nullptr) {
477 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
478 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
479 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700480 }
481 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700482 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700483 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800484}
485
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700486// For dumping/debugging only -
487// try to acquire a lock a few times, eventually give up to proceed with
488// debug/dump operations
489bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
490 bool gotLock = false;
491 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
492 if (lock.tryLock() == NO_ERROR) {
493 gotLock = true;
494 break;
495 } else {
496 usleep(kDumpSleepDuration);
497 }
498 }
499 return gotLock;
500}
501
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800502nsecs_t Camera3Device::getMonoToBoottimeOffset() {
503 // try three times to get the clock offset, choose the one
504 // with the minimum gap in measurements.
505 const int tries = 3;
506 nsecs_t bestGap, measured;
507 for (int i = 0; i < tries; ++i) {
508 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
509 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
510 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
511 const nsecs_t gap = tmono2 - tmono;
512 if (i == 0 || gap < bestGap) {
513 bestGap = gap;
514 measured = tbase - ((tmono + tmono2) >> 1);
515 }
516 }
517 return measured;
518}
519
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800520hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
521 int frameworkFormat) {
522 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
523}
524
525DataspaceFlags Camera3Device::mapToHidlDataspace(
526 android_dataspace dataSpace) {
527 return dataSpace;
528}
529
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700530BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100531 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700532 return usage;
533}
534
Emilian Peevf4816702020-04-03 15:44:51 -0700535StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700537 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800538 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700539 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800540 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700541 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800542 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700543 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800544 return StreamRotation::ROTATION_270;
545 }
546 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
547 return StreamRotation::ROTATION_0;
548}
549
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800550status_t Camera3Device::mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -0700551 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800552 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700553 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800554 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700555 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800556 *mode = StreamConfigurationMode::NORMAL_MODE;
557 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700558 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800559 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
560 break;
561 default:
562 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
563 return BAD_VALUE;
564 }
565 } else {
566 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800567 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800569}
570
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800571int Camera3Device::mapToFrameworkFormat(
572 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
573 return static_cast<uint32_t>(pixelFormat);
574}
575
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700576android_dataspace Camera3Device::mapToFrameworkDataspace(
577 DataspaceFlags dataSpace) {
578 return static_cast<android_dataspace>(dataSpace);
579}
580
Emilian Peev050f5dc2017-05-18 14:43:56 +0100581uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700582 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700583 return usage;
584}
585
Emilian Peev050f5dc2017-05-18 14:43:56 +0100586uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700587 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700588 return usage;
589}
590
Zhijun Hef7da0962014-04-24 13:27:56 -0700591ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700592 // Get max jpeg size (area-wise) for default sensor pixel mode
593 camera3::Size maxDefaultJpegResolution =
594 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
595 /*isUltraHighResolutionSensor*/false);
596 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
597 // not ultra high res sensor
598 camera3::Size uhrMaxJpegResolution =
599 SessionConfigurationUtils::getMaxJpegResolution(mDeviceInfo,
600 /*isUltraHighResolution*/true);
601 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
603 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700604 return BAD_VALUE;
605 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700606 bool useMaxSensorPixelModeThreshold = false;
607 if (uhrMaxJpegResolution.width != 0 &&
608 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
609 // Use the ultra high res max jpeg size and max jpeg buffer size
610 useMaxSensorPixelModeThreshold = true;
611 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700612
Zhijun Hef7da0962014-04-24 13:27:56 -0700613 // Get max jpeg buffer size
614 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700615 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
616 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
618 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700621 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700622
623 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
624 if (useMaxSensorPixelModeThreshold) {
625 maxJpegBufferSize =
626 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
627 maxDefaultJpegResolution, maxJpegBufferSize);
628 chosenMaxJpegResolution = uhrMaxJpegResolution;
629 }
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)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700634 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.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 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 return jpegBufferSize;
643}
644
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700645ssize_t Camera3Device::getPointCloudBufferSize() const {
646 const int FLOATS_PER_POINT=4;
647 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
648 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800649 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
650 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700651 return BAD_VALUE;
652 }
653 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
654 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
655 return maxBytesForPointCloud;
656}
657
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800658ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height,
659 bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800660 const int PER_CONFIGURATION_SIZE = 3;
661 const int WIDTH_OFFSET = 0;
662 const int HEIGHT_OFFSET = 1;
663 const int SIZE_OFFSET = 2;
664 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800665 mDeviceInfo.find(
666 camera3::SessionConfigurationUtils::getAppropriateModeTag(
667 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
668 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800669 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800670 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
672 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 return BAD_VALUE;
674 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700675
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800676 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
677 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
678 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
679 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
680 }
681 }
682
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800683 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
684 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800685 return BAD_VALUE;
686}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700687
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800688status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
689 ATRACE_CALL();
690 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691
692 // Try to lock, but continue in case of failure (to avoid blocking in
693 // deadlocks)
694 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
695 bool gotLock = tryLockSpinRightRound(mLock);
696
697 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800698 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
699 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700700 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800701 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
702 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700703
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800704 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700705
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800706 String16 templatesOption("-t");
707 int n = args.size();
708 for (int i = 0; i < n; i++) {
709 if (args[i] == templatesOption) {
710 dumpTemplates = true;
711 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000712 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700713 if (i + 1 < n) {
714 String8 monitorTags = String8(args[i + 1]);
715 if (monitorTags == "off") {
716 mTagMonitor.disableMonitoring();
717 } else {
718 mTagMonitor.parseTagsToMonitor(monitorTags);
719 }
720 } else {
721 mTagMonitor.disableMonitoring();
722 }
723 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800724 }
725
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800726 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800727
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 const char *status =
729 mStatus == STATUS_ERROR ? "ERROR" :
730 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700731 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
732 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800733 mStatus == STATUS_ACTIVE ? "ACTIVE" :
734 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700735
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800736 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700737 if (mStatus == STATUS_ERROR) {
738 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
739 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800741 const char *mode =
742 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
743 mOperatingMode == static_cast<int>(
744 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
745 "CUSTOM";
746 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800747
748 if (mInputStream != NULL) {
749 write(fd, lines.string(), lines.size());
750 mInputStream->dump(fd, args);
751 } else {
752 lines.appendFormat(" No input stream.\n");
753 write(fd, lines.string(), lines.size());
754 }
755 for (size_t i = 0; i < mOutputStreams.size(); i++) {
756 mOutputStreams[i]->dump(fd,args);
757 }
758
Zhijun He431503c2016-03-07 17:30:16 -0800759 if (mBufferManager != NULL) {
760 lines = String8(" Camera3 Buffer Manager:\n");
761 write(fd, lines.string(), lines.size());
762 mBufferManager->dump(fd, args);
763 }
Zhijun He125684a2015-12-26 15:07:30 -0800764
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700765 lines = String8(" In-flight requests:\n");
766 if (mInFlightMap.size() == 0) {
767 lines.append(" None\n");
768 } else {
769 for (size_t i = 0; i < mInFlightMap.size(); i++) {
770 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700771 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000772 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800773 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000774 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700775 }
776 }
777 write(fd, lines.string(), lines.size());
778
Shuzhen Wang686f6442017-06-20 16:16:04 -0700779 if (mRequestThread != NULL) {
780 mRequestThread->dumpCaptureRequestLatency(fd,
781 " ProcessCaptureRequest latency histogram:");
782 }
783
Igor Murashkin1e479c02013-09-06 16:55:14 -0700784 {
785 lines = String8(" Last request sent:\n");
786 write(fd, lines.string(), lines.size());
787
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700788 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700789 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
790 }
791
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800792 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700793 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 "TEMPLATE_PREVIEW",
795 "TEMPLATE_STILL_CAPTURE",
796 "TEMPLATE_VIDEO_RECORD",
797 "TEMPLATE_VIDEO_SNAPSHOT",
798 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800799 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800800 };
801
Emilian Peevf4816702020-04-03 15:44:51 -0700802 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800803 camera_metadata_t *templateRequest = nullptr;
804 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700805 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800806 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800807 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800808 lines.append(" Not supported\n");
809 write(fd, lines.string(), lines.size());
810 } else {
811 write(fd, lines.string(), lines.size());
812 dump_indented_camera_metadata(templateRequest,
813 fd, /*verbosity*/2, /*indentation*/8);
814 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800815 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800816 }
817 }
818
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700819 mTagMonitor.dumpMonitoredMetadata(fd);
820
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800821 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800822 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800824 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800825 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800826
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700827 if (gotLock) mLock.unlock();
828 if (gotInterfaceLock) mInterfaceLock.unlock();
829
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800830 return OK;
831}
832
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800833const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800834 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800835 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
836 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700837 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800838 mStatus == STATUS_ERROR ?
839 "when in error state" : "before init");
840 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700841 if (physicalId.isEmpty()) {
842 return mDeviceInfo;
843 } else {
844 std::string id(physicalId.c_str());
845 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
846 return mPhysicalDeviceInfoMap.at(id);
847 } else {
848 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
849 return mDeviceInfo;
850 }
851 }
852}
853
854const CameraMetadata& Camera3Device::info() const {
855 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800856 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800857}
858
Jianing Wei90e59c92014-03-12 18:29:36 -0700859status_t Camera3Device::checkStatusOkToCaptureLocked() {
860 switch (mStatus) {
861 case STATUS_ERROR:
862 CLOGE("Device has encountered a serious error");
863 return INVALID_OPERATION;
864 case STATUS_UNINITIALIZED:
865 CLOGE("Device not initialized");
866 return INVALID_OPERATION;
867 case STATUS_UNCONFIGURED:
868 case STATUS_CONFIGURED:
869 case STATUS_ACTIVE:
870 // OK
871 break;
872 default:
873 SET_ERR_L("Unexpected status: %d", mStatus);
874 return INVALID_OPERATION;
875 }
876 return OK;
877}
878
879status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000880 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700881 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700882 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700883 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 if (requestList == NULL) {
885 CLOGE("requestList cannot be NULL.");
886 return BAD_VALUE;
887 }
888
Jianing Weicb0652e2014-03-12 18:29:36 -0700889 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000890 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700891 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
892 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
893 ++metadataIt, ++surfaceMapIt) {
894 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700895 if (newRequest == 0) {
896 CLOGE("Can't create capture request");
897 return BAD_VALUE;
898 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700899
Shuzhen Wang9d066012016-09-30 11:30:20 -0700900 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700901 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700902
Jianing Weicb0652e2014-03-12 18:29:36 -0700903 // Setup burst Id and request Id
904 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800905 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
906 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700907 CLOGE("RequestID does not exist in metadata");
908 return BAD_VALUE;
909 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800910 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700911
Jianing Wei90e59c92014-03-12 18:29:36 -0700912 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700913
914 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700915 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700916 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
917 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
918 return BAD_VALUE;
919 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700920
921 // Setup batch size if this is a high speed video recording request.
922 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
923 auto firstRequest = requestList->begin();
924 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
925 if (outputStream->isVideoStream()) {
926 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800927 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700928 break;
929 }
930 }
931 }
932
Jianing Wei90e59c92014-03-12 18:29:36 -0700933 return OK;
934}
935
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800936status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800937 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800938
Emilian Peevaebbe412018-01-15 13:53:24 +0000939 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000941 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700942
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800943 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700944}
945
Emilian Peevaebbe412018-01-15 13:53:24 +0000946void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700947 std::list<const SurfaceMap>& surfaceMaps,
948 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000949 PhysicalCameraSettingsList requestList;
950 requestList.push_back({std::string(getId().string()), request});
951 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700952
953 SurfaceMap surfaceMap;
954 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
955 // With no surface list passed in, stream and surface will have 1-to-1
956 // mapping. So the surface index is 0 for each stream in the surfaceMap.
957 for (size_t i = 0; i < streams.count; i++) {
958 surfaceMap[streams.data.i32[i]].push_back(0);
959 }
960 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800961}
962
Jianing Wei90e59c92014-03-12 18:29:36 -0700963status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000964 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700965 const std::list<const SurfaceMap> &surfaceMaps,
966 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700967 /*out*/
968 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700969 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700970 nsecs_t requestTimeNs = systemTime();
971
Jianing Wei90e59c92014-03-12 18:29:36 -0700972 Mutex::Autolock il(mInterfaceLock);
973 Mutex::Autolock l(mLock);
974
975 status_t res = checkStatusOkToCaptureLocked();
976 if (res != OK) {
977 // error logged by previous call
978 return res;
979 }
980
981 RequestList requestList;
982
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700984 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700985 if (res != OK) {
986 // error logged by previous call
987 return res;
988 }
989
990 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700993 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700994 }
995
996 if (res == OK) {
997 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
998 if (res != OK) {
999 SET_ERR_L("Can't transition to active in %f seconds!",
1000 kActiveTimeout/1e9);
1001 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001002 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001003 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001004 } else {
1005 CLOGE("Cannot queue request. Impossible.");
1006 return BAD_VALUE;
1007 }
1008
1009 return res;
1010}
1011
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001012hardware::Return<void> Camera3Device::requestStreamBuffers(
1013 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1014 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001015 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001016 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001017 *this, *mInterface, *this};
1018 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001019 return hardware::Void();
1020}
1021
1022hardware::Return<void> Camera3Device::returnStreamBuffers(
1023 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001024 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001025 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001026 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001027 return hardware::Void();
1028}
1029
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001030hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001031 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001032 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001033 // Ideally we should grab mLock, but that can lead to deadlock, and
1034 // it's not super important to get up to date value of mStatus for this
1035 // warning print, hence skipping the lock here
1036 if (mStatus == STATUS_ERROR) {
1037 // Per API contract, HAL should act as closed after device error
1038 // But mStatus can be set to error by framework as well, so just log
1039 // a warning here.
1040 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001041 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001042
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001043 sp<NotificationListener> listener;
1044 {
1045 std::lock_guard<std::mutex> l(mOutputLock);
1046 listener = mListener.promote();
1047 }
1048
Yifan Honga640c5a2017-04-12 16:30:31 -07001049 if (mProcessCaptureResultLock.tryLock() != OK) {
1050 // This should never happen; it indicates a wrong client implementation
1051 // that doesn't follow the contract. But, we can be tolerant here.
1052 ALOGE("%s: callback overlapped! waiting 1s...",
1053 __FUNCTION__);
1054 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1055 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1056 __FUNCTION__);
1057 // really don't know what to do, so bail out.
1058 return hardware::Void();
1059 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001060 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 CaptureOutputStates states {
1062 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001063 mInFlightLock, mLastCompletedRegularFrameNumber,
1064 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1065 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 mNextShutterFrameNumber,
1067 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1068 mNextResultFrameNumber,
1069 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1070 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1071 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001072 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001073 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1074 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001075 };
1076
Yifan Honga640c5a2017-04-12 16:30:31 -07001077 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001078 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001079 }
1080 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001081 return hardware::Void();
1082}
1083
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001084// Only one processCaptureResult should be called at a time, so
1085// the locks won't block. The locks are present here simply to enforce this.
1086hardware::Return<void> Camera3Device::processCaptureResult(
1087 const hardware::hidl_vec<
1088 hardware::camera::device::V3_2::CaptureResult>& results) {
1089 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1090
1091 // Ideally we should grab mLock, but that can lead to deadlock, and
1092 // it's not super important to get up to date value of mStatus for this
1093 // warning print, hence skipping the lock here
1094 if (mStatus == STATUS_ERROR) {
1095 // Per API contract, HAL should act as closed after device error
1096 // But mStatus can be set to error by framework as well, so just log
1097 // a warning here.
1098 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1099 }
1100
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001101 sp<NotificationListener> listener;
1102 {
1103 std::lock_guard<std::mutex> l(mOutputLock);
1104 listener = mListener.promote();
1105 }
1106
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001107 if (mProcessCaptureResultLock.tryLock() != OK) {
1108 // This should never happen; it indicates a wrong client implementation
1109 // that doesn't follow the contract. But, we can be tolerant here.
1110 ALOGE("%s: callback overlapped! waiting 1s...",
1111 __FUNCTION__);
1112 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1113 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1114 __FUNCTION__);
1115 // really don't know what to do, so bail out.
1116 return hardware::Void();
1117 }
1118 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001119
1120 CaptureOutputStates states {
1121 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001122 mInFlightLock, mLastCompletedRegularFrameNumber,
1123 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1124 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001125 mNextShutterFrameNumber,
1126 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1127 mNextResultFrameNumber,
1128 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1129 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1130 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001131 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001132 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1133 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001134 };
1135
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001136 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001137 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001138 }
1139 mProcessCaptureResultLock.unlock();
1140 return hardware::Void();
1141}
1142
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001143hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001144 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001145 // Ideally we should grab mLock, but that can lead to deadlock, and
1146 // it's not super important to get up to date value of mStatus for this
1147 // warning print, hence skipping the lock here
1148 if (mStatus == STATUS_ERROR) {
1149 // Per API contract, HAL should act as closed after device error
1150 // But mStatus can be set to error by framework as well, so just log
1151 // a warning here.
1152 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001153 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001154
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 sp<NotificationListener> listener;
1156 {
1157 std::lock_guard<std::mutex> l(mOutputLock);
1158 listener = mListener.promote();
1159 }
1160
1161 CaptureOutputStates states {
1162 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001163 mInFlightLock, mLastCompletedRegularFrameNumber,
1164 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1165 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001166 mNextShutterFrameNumber,
1167 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1168 mNextResultFrameNumber,
1169 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1170 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1171 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001172 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001173 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1174 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001175 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001176 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001177 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 }
1179 return hardware::Void();
1180}
1181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001184 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001185 ATRACE_CALL();
1186
Emilian Peevaebbe412018-01-15 13:53:24 +00001187 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001188}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001189
Jianing Weicb0652e2014-03-12 18:29:36 -07001190status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1191 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001192 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001193
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001195 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001196 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001197
Emilian Peevaebbe412018-01-15 13:53:24 +00001198 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001199 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200}
1201
Emilian Peevaebbe412018-01-15 13:53:24 +00001202status_t Camera3Device::setStreamingRequestList(
1203 const List<const PhysicalCameraSettingsList> &requestsList,
1204 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001205 ATRACE_CALL();
1206
Emilian Peevaebbe412018-01-15 13:53:24 +00001207 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001208}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209
1210sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001211 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 status_t res;
1213
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001214 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001215 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1216 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001217 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001218 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001219 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001221 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001223 } else if (mStatus == STATUS_UNCONFIGURED) {
1224 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 CLOGE("No streams configured");
1226 return NULL;
1227 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 }
1229
Shuzhen Wang0129d522016-10-30 22:43:41 -07001230 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001232}
1233
Jianing Weicb0652e2014-03-12 18:29:36 -07001234status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001235 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 switch (mStatus) {
1240 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001244 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 case STATUS_UNCONFIGURED:
1247 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 case STATUS_ACTIVE:
1249 // OK
1250 break;
1251 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001252 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 return INVALID_OPERATION;
1254 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001255 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001256
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001257 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001258}
1259
1260status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1261 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001264 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001265}
1266
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001267status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001268 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001269 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001270 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001271 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001272 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001273 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1274 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275
1276 status_t res;
1277 bool wasActive = false;
1278
1279 switch (mStatus) {
1280 case STATUS_ERROR:
1281 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1282 return INVALID_OPERATION;
1283 case STATUS_UNINITIALIZED:
1284 ALOGE("%s: Device not initialized", __FUNCTION__);
1285 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001286 case STATUS_UNCONFIGURED:
1287 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288 // OK
1289 break;
1290 case STATUS_ACTIVE:
1291 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001292 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001294 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001295 return res;
1296 }
1297 wasActive = true;
1298 break;
1299 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301 return INVALID_OPERATION;
1302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304
1305 if (mInputStream != 0) {
1306 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1307 return INVALID_OPERATION;
1308 }
1309
1310 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1311 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313
1314 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001315 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316
1317 *id = mNextStreamId++;
1318
1319 // Continue captures if active at start
1320 if (wasActive) {
1321 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001322 // Reuse current operating mode and session parameters for new stream config
1323 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001324 if (res != OK) {
1325 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1326 __FUNCTION__, mNextStreamId, strerror(-res), res);
1327 return res;
1328 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001329 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001330 }
1331
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001332 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001333 return OK;
1334}
1335
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001336status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001337 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001338 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001340 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1341 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1342 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001343 ATRACE_CALL();
1344
1345 if (consumer == nullptr) {
1346 ALOGE("%s: consumer must not be null", __FUNCTION__);
1347 return BAD_VALUE;
1348 }
1349
1350 std::vector<sp<Surface>> consumers;
1351 consumers.push_back(consumer);
1352
1353 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001354 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1355 streamSetId, isShared, isMultiResolution, consumerUsage);
1356}
1357
1358static bool isRawFormat(int format) {
1359 switch (format) {
1360 case HAL_PIXEL_FORMAT_RAW16:
1361 case HAL_PIXEL_FORMAT_RAW12:
1362 case HAL_PIXEL_FORMAT_RAW10:
1363 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1364 return true;
1365 default:
1366 return false;
1367 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001368}
1369
1370status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1371 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001372 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001373 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001374 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1375 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001376 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001377
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001379 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001381 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001382 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1383 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1384 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386 status_t res;
1387 bool wasActive = false;
1388
1389 switch (mStatus) {
1390 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
1393 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001394 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001396 case STATUS_UNCONFIGURED:
1397 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001398 // OK
1399 break;
1400 case STATUS_ACTIVE:
1401 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001402 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001404 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405 return res;
1406 }
1407 wasActive = true;
1408 break;
1409 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001410 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411 return INVALID_OPERATION;
1412 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001413 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001414
1415 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001416
Shuzhen Wang0129d522016-10-30 22:43:41 -07001417 if (consumers.size() == 0 && !hasDeferredConsumer) {
1418 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1419 return BAD_VALUE;
1420 }
Zhijun He5d677d12016-05-29 16:52:39 -07001421
Shuzhen Wang0129d522016-10-30 22:43:41 -07001422 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001423 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1424 return BAD_VALUE;
1425 }
1426
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001427 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1428 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1429 // be found in only one sensor pixel mode.
1430 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1431 return BAD_VALUE;
1432 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001434 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001435 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001436 blobBufferSize = getPointCloudBufferSize();
1437 if (blobBufferSize <= 0) {
1438 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1439 return BAD_VALUE;
1440 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001441 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1442 blobBufferSize = width * height;
1443 } else {
1444 blobBufferSize = getJpegBufferSize(width, height);
1445 if (blobBufferSize <= 0) {
1446 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1447 return BAD_VALUE;
1448 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001449 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001450 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001451 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001452 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1453 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001454 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001455 bool maxResolution =
1456 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1457 sensorPixelModesUsed.end();
1458 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001459 if (rawOpaqueBufferSize <= 0) {
1460 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1461 return BAD_VALUE;
1462 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001463 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001464 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001465 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1466 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001467 } else if (isShared) {
1468 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1469 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001470 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1471 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001472 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001473 newStream = new Camera3OutputStream(mNextStreamId,
1474 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001475 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1476 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001478 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001479 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001480 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1481 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 }
Emilian Peev40ead602017-09-26 15:46:36 +01001483
1484 size_t consumerCount = consumers.size();
1485 for (size_t i = 0; i < consumerCount; i++) {
1486 int id = newStream->getSurfaceId(consumers[i]);
1487 if (id < 0) {
1488 SET_ERR_L("Invalid surface id");
1489 return BAD_VALUE;
1490 }
1491 if (surfaceIds != nullptr) {
1492 surfaceIds->push_back(id);
1493 }
1494 }
1495
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497
Emilian Peev08dd2452017-04-06 16:55:14 +01001498 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001499
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001500 newStream->setImageDumpMask(mImageDumpMask);
1501
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 res = mOutputStreams.add(mNextStreamId, newStream);
1503 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return res;
1506 }
1507
Shuzhen Wang316781a2020-08-18 18:11:01 -07001508 mSessionStatsBuilder.addStream(mNextStreamId);
1509
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001511 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512
1513 // Continue captures if active at start
1514 if (wasActive) {
1515 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001516 // Reuse current operating mode and session parameters for new stream config
1517 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001519 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1520 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return res;
1522 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001525 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527}
1528
Emilian Peev710c1422017-08-30 11:19:38 +01001529status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001530 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001531 if (nullptr == streamInfo) {
1532 return BAD_VALUE;
1533 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001534 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001536
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 switch (mStatus) {
1538 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001539 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 return INVALID_OPERATION;
1541 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001542 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 case STATUS_UNCONFIGURED:
1545 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 case STATUS_ACTIVE:
1547 // OK
1548 break;
1549 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001550 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 return INVALID_OPERATION;
1552 }
1553
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001554 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1555 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001557 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 }
1559
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001560 streamInfo->width = stream->getWidth();
1561 streamInfo->height = stream->getHeight();
1562 streamInfo->format = stream->getFormat();
1563 streamInfo->dataSpace = stream->getDataSpace();
1564 streamInfo->formatOverridden = stream->isFormatOverridden();
1565 streamInfo->originalFormat = stream->getOriginalFormat();
1566 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1567 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001569}
1570
1571status_t Camera3Device::setStreamTransform(int id,
1572 int transform) {
1573 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 switch (mStatus) {
1578 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001579 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 return INVALID_OPERATION;
1581 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001582 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 case STATUS_UNCONFIGURED:
1585 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 case STATUS_ACTIVE:
1587 // OK
1588 break;
1589 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001590 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 return INVALID_OPERATION;
1592 }
1593
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001594 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1595 if (stream == nullptr) {
1596 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 return BAD_VALUE;
1598 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001599 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001600}
1601
1602status_t Camera3Device::deleteStream(int id) {
1603 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 Mutex::Autolock l(mLock);
1606 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001608 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001609
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 // CameraDevice semantics require device to already be idle before
1611 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001613 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001614 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 }
1616
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001617 if (mStatus == STATUS_ERROR) {
1618 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1619 __FUNCTION__, mId.string());
1620 return -EBUSY;
1621 }
1622
Igor Murashkin2fba5842013-04-22 14:03:54 -07001623 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001624 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001625 if (mInputStream != NULL && id == mInputStream->getId()) {
1626 deletedStream = mInputStream;
1627 mInputStream.clear();
1628 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001629 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001630 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001631 return BAD_VALUE;
1632 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001633 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001634 }
1635
1636 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001637 if (stream != nullptr) {
1638 deletedStream = stream;
1639 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001640 }
1641
1642 // Free up the stream endpoint so that it can be used by some other stream
1643 res = deletedStream->disconnect();
1644 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001645 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001646 // fall through since we want to still list the stream as deleted.
1647 }
1648 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001649 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001650
1651 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652}
1653
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001654status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001655 ATRACE_CALL();
1656 ALOGV("%s: E", __FUNCTION__);
1657
1658 Mutex::Autolock il(mInterfaceLock);
1659 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001660
Emilian Peev811d2952018-05-25 11:08:40 +01001661 // In case the client doesn't include any session parameter, try a
1662 // speculative configuration using the values from the last cached
1663 // default request.
1664 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001665 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001666 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1667 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1668 mLastTemplateId);
1669 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1670 operatingMode);
1671 }
1672
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001673 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1674}
1675
1676status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1677 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001678 //Filter out any incoming session parameters
1679 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001680 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1681 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001682 CameraMetadata filteredParams(availableSessionKeys.count);
1683 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1684 filteredParams.getAndLock());
1685 set_camera_metadata_vendor_id(meta, mVendorTagId);
1686 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001687 if (availableSessionKeys.count > 0) {
1688 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1689 camera_metadata_ro_entry entry = params.find(
1690 availableSessionKeys.data.i32[i]);
1691 if (entry.count > 0) {
1692 filteredParams.update(entry);
1693 }
1694 }
1695 }
1696
1697 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001698}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001699
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001700status_t Camera3Device::getInputBufferProducer(
1701 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001702 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001703 Mutex::Autolock il(mInterfaceLock);
1704 Mutex::Autolock l(mLock);
1705
1706 if (producer == NULL) {
1707 return BAD_VALUE;
1708 } else if (mInputStream == NULL) {
1709 return INVALID_OPERATION;
1710 }
1711
1712 return mInputStream->getInputBufferProducer(producer);
1713}
1714
Emilian Peevf4816702020-04-03 15:44:51 -07001715status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716 CameraMetadata *request) {
1717 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001718 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001719
Emilian Peevf4816702020-04-03 15:44:51 -07001720 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001721 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001722 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001723 return BAD_VALUE;
1724 }
1725
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001727
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001728 {
1729 Mutex::Autolock l(mLock);
1730 switch (mStatus) {
1731 case STATUS_ERROR:
1732 CLOGE("Device has encountered a serious error");
1733 return INVALID_OPERATION;
1734 case STATUS_UNINITIALIZED:
1735 CLOGE("Device is not initialized!");
1736 return INVALID_OPERATION;
1737 case STATUS_UNCONFIGURED:
1738 case STATUS_CONFIGURED:
1739 case STATUS_ACTIVE:
1740 // OK
1741 break;
1742 default:
1743 SET_ERR_L("Unexpected status: %d", mStatus);
1744 return INVALID_OPERATION;
1745 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001747 if (!mRequestTemplateCache[templateId].isEmpty()) {
1748 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001749 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001750 return OK;
1751 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001752 }
1753
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001754 camera_metadata_t *rawRequest;
1755 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001756 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001757
1758 {
1759 Mutex::Autolock l(mLock);
1760 if (res == BAD_VALUE) {
1761 ALOGI("%s: template %d is not supported on this camera device",
1762 __FUNCTION__, templateId);
1763 return res;
1764 } else if (res != OK) {
1765 CLOGE("Unable to construct request template %d: %s (%d)",
1766 templateId, strerror(-res), res);
1767 return res;
1768 }
1769
1770 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1771 mRequestTemplateCache[templateId].acquire(rawRequest);
1772
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001773 // Override the template request with zoomRatioMapper
1774 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1775 &mRequestTemplateCache[templateId]);
1776 if (res != OK) {
1777 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1778 templateId, strerror(-res), res);
1779 return res;
1780 }
1781
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001782 // Fill in JPEG_QUALITY if not available
1783 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1784 static const uint8_t kDefaultJpegQuality = 95;
1785 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1786 &kDefaultJpegQuality, 1);
1787 }
1788
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001789 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001790 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001791 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001792 return OK;
1793}
1794
1795status_t Camera3Device::waitUntilDrained() {
1796 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001797 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001798 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001799 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001800
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001801 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001802}
1803
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001804status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805 switch (mStatus) {
1806 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001808 ALOGV("%s: Already idle", __FUNCTION__);
1809 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 case STATUS_CONFIGURED:
1811 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001812 case STATUS_ERROR:
1813 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001815 break;
1816 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001817 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001818 return INVALID_OPERATION;
1819 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001820 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1821 maxExpectedDuration);
1822 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001823 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001824 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001825 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1826 res);
1827 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 return res;
1829}
1830
Ruben Brunk183f0562015-08-12 12:55:02 -07001831void Camera3Device::internalUpdateStatusLocked(Status status) {
1832 mStatus = status;
1833 mRecentStatusUpdates.add(mStatus);
1834 mStatusChanged.broadcast();
1835}
1836
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001837// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001838status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001839 if (mRequestThread.get() != nullptr) {
1840 mRequestThread->setPaused(true);
1841 } else {
1842 return NO_INIT;
1843 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001845 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1846 maxExpectedDuration);
1847 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001848 if (res != OK) {
1849 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001850 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 }
1852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853 return res;
1854}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001855
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856// Resume after internalPauseAndWaitLocked
1857status_t Camera3Device::internalResumeLocked() {
1858 status_t res;
1859
1860 mRequestThread->setPaused(false);
1861
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001862 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1863 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1865 if (res != OK) {
1866 SET_ERR_L("Can't transition to active in %f seconds!",
1867 kActiveTimeout/1e9);
1868 }
1869 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001871}
1872
Ruben Brunk183f0562015-08-12 12:55:02 -07001873status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001875
1876 size_t startIndex = 0;
1877 if (mStatusWaiters == 0) {
1878 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1879 // this status list
1880 mRecentStatusUpdates.clear();
1881 } else {
1882 // If other threads are waiting on updates to this status list, set the position of the
1883 // first element that this list will check rather than clearing the list.
1884 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001885 }
1886
Ruben Brunk183f0562015-08-12 12:55:02 -07001887 mStatusWaiters++;
1888
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001889 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001890 if (!active && mUseHalBufManager) {
1891 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001892 if (mStatus == STATUS_ACTIVE) {
1893 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001894 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001895 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001896 mRequestBufferSM.onWaitUntilIdle();
1897 }
1898
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 bool stateSeen = false;
1900 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001901 if (active == (mStatus == STATUS_ACTIVE)) {
1902 // Desired state is current
1903 break;
1904 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001905
1906 res = mStatusChanged.waitRelative(mLock, timeout);
1907 if (res != OK) break;
1908
Ruben Brunk183f0562015-08-12 12:55:02 -07001909 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1910 // transitions.
1911 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1912 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1913 __FUNCTION__);
1914
1915 // Encountered desired state since we began waiting
1916 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001917 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1918 stateSeen = true;
1919 break;
1920 }
1921 }
1922 } while (!stateSeen);
1923
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001924 if (signalPipelineDrain) {
1925 mRequestThread->resetPipelineDrain();
1926 }
1927
Ruben Brunk183f0562015-08-12 12:55:02 -07001928 mStatusWaiters--;
1929
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001930 return res;
1931}
1932
1933
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001934status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001935 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001936 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001937
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001938 if (listener != NULL && mListener != NULL) {
1939 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1940 }
1941 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001942 mRequestThread->setNotificationListener(listener);
1943 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001944
1945 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001946}
1947
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001948bool Camera3Device::willNotify3A() {
1949 return false;
1950}
1951
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001952status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001953 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001954 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001956 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001957 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1958 if (st == std::cv_status::timeout) {
1959 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001960 }
1961 }
1962 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963}
1964
Jianing Weicb0652e2014-03-12 18:29:36 -07001965status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001966 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001967 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001969 if (mResultQueue.empty()) {
1970 return NOT_ENOUGH_DATA;
1971 }
1972
Jianing Weicb0652e2014-03-12 18:29:36 -07001973 if (frame == NULL) {
1974 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1975 return BAD_VALUE;
1976 }
1977
1978 CaptureResult &result = *(mResultQueue.begin());
1979 frame->mResultExtras = result.mResultExtras;
1980 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001981 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001982 mResultQueue.erase(mResultQueue.begin());
1983
1984 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985}
1986
1987status_t Camera3Device::triggerAutofocus(uint32_t id) {
1988 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001989 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001991 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1992 // Mix-in this trigger into the next request and only the next request.
1993 RequestTrigger trigger[] = {
1994 {
1995 ANDROID_CONTROL_AF_TRIGGER,
1996 ANDROID_CONTROL_AF_TRIGGER_START
1997 },
1998 {
1999 ANDROID_CONTROL_AF_TRIGGER_ID,
2000 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002001 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002002 };
2003
2004 return mRequestThread->queueTrigger(trigger,
2005 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006}
2007
2008status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2009 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002010 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002011
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002012 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2013 // Mix-in this trigger into the next request and only the next request.
2014 RequestTrigger trigger[] = {
2015 {
2016 ANDROID_CONTROL_AF_TRIGGER,
2017 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2018 },
2019 {
2020 ANDROID_CONTROL_AF_TRIGGER_ID,
2021 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002022 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002023 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002024
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002025 return mRequestThread->queueTrigger(trigger,
2026 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002027}
2028
2029status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2030 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002032
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002033 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2034 // Mix-in this trigger into the next request and only the next request.
2035 RequestTrigger trigger[] = {
2036 {
2037 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2038 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2039 },
2040 {
2041 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2042 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002043 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002044 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002046 return mRequestThread->queueTrigger(trigger,
2047 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002048}
2049
Jianing Weicb0652e2014-03-12 18:29:36 -07002050status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002051 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002052 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002053 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002054
Zhijun He7ef20392014-04-21 16:04:17 -07002055 {
2056 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002057
2058 // b/116514106 "disconnect()" can get called twice for the same device. The
2059 // camera device will not be initialized during the second run.
2060 if (mStatus == STATUS_UNINITIALIZED) {
2061 return OK;
2062 }
2063
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002064 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002065
2066 // Stop session and stream counter
2067 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002068 }
2069
Emilian Peev08dd2452017-04-06 16:55:14 +01002070 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002071}
2072
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002073status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002074 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2075}
2076
2077status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002078 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002079 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002080 Mutex::Autolock il(mInterfaceLock);
2081 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002082
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002083 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2084 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002085 CLOGE("Stream %d does not exist", streamId);
2086 return BAD_VALUE;
2087 }
2088
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002089 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002090 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002091 return BAD_VALUE;
2092 }
2093
2094 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002095 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002096 return BAD_VALUE;
2097 }
2098
Ruben Brunkc78ac262015-08-13 17:58:46 -07002099 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002100}
2101
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002102status_t Camera3Device::tearDown(int streamId) {
2103 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002104 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002105 Mutex::Autolock il(mInterfaceLock);
2106 Mutex::Autolock l(mLock);
2107
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002108 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2109 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002110 CLOGE("Stream %d does not exist", streamId);
2111 return BAD_VALUE;
2112 }
2113
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002114 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2115 CLOGE("Stream %d is a target of a in-progress request", streamId);
2116 return BAD_VALUE;
2117 }
2118
2119 return stream->tearDown();
2120}
2121
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002122status_t Camera3Device::addBufferListenerForStream(int streamId,
2123 wp<Camera3StreamBufferListener> listener) {
2124 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002125 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002126 Mutex::Autolock il(mInterfaceLock);
2127 Mutex::Autolock l(mLock);
2128
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2130 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002131 CLOGE("Stream %d does not exist", streamId);
2132 return BAD_VALUE;
2133 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002134 stream->addBufferListener(listener);
2135
2136 return OK;
2137}
2138
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002140 * Methods called by subclasses
2141 */
2142
2143void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002144 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002145 std::vector<int> streamIds;
2146 std::vector<hardware::CameraStreamStats> streamStats;
2147
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 {
2149 // Need mLock to safely update state and synchronize to current
2150 // state of methods in flight.
2151 Mutex::Autolock l(mLock);
2152 // We can get various system-idle notices from the status tracker
2153 // while starting up. Only care about them if we've actually sent
2154 // in some requests recently.
2155 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2156 return;
2157 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002158 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2159 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002160 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002161
2162 // Skip notifying listener if we're doing some user-transparent
2163 // state changes
2164 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002165
2166 // Populate stream statistics in case of Idle
2167 if (idle) {
2168 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2169 auto stream = mOutputStreams[i];
2170 if (stream.get() == nullptr) continue;
2171 streamIds.push_back(stream->getId());
2172 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2173 int64_t usage = 0LL;
2174 if (camera3Stream != nullptr) {
2175 usage = camera3Stream->getUsage();
2176 }
2177 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2178 stream->getFormat(), stream->getDataSpace(), usage,
2179 stream->getMaxHalBuffers(),
2180 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2181 }
2182 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002184
2185 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002186 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002187 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002188 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002190 status_t res = OK;
2191 if (listener != nullptr) {
2192 if (idle) {
2193 // 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;
2206 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());
2214 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002215 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002216 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2217 } else {
2218 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002219 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002220 }
2221 if (res != OK) {
2222 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2223 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224 }
2225}
2226
Shuzhen Wang758c2152017-01-10 18:26:18 -08002227status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002228 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002229 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002230 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2231 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002232
2233 if (surfaceIds == nullptr) {
2234 return BAD_VALUE;
2235 }
2236
Zhijun He5d677d12016-05-29 16:52:39 -07002237 Mutex::Autolock il(mInterfaceLock);
2238 Mutex::Autolock l(mLock);
2239
Shuzhen Wang758c2152017-01-10 18:26:18 -08002240 if (consumers.size() == 0) {
2241 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002242 return BAD_VALUE;
2243 }
2244
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002245 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2246 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002247 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002248 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002249 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002250
2251 // isConsumerConfigurationDeferred will be off after setConsumers
2252 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002253 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002254 if (res != OK) {
2255 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2256 return res;
2257 }
2258
Emilian Peev40ead602017-09-26 15:46:36 +01002259 for (auto &consumer : consumers) {
2260 int id = stream->getSurfaceId(consumer);
2261 if (id < 0) {
2262 CLOGE("Invalid surface id!");
2263 return BAD_VALUE;
2264 }
2265 surfaceIds->push_back(id);
2266 }
2267
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002268 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002269 if (!stream->isConfiguring()) {
2270 CLOGE("Stream %d was already fully configured.", streamId);
2271 return INVALID_OPERATION;
2272 }
Zhijun He5d677d12016-05-29 16:52:39 -07002273
Shuzhen Wang0129d522016-10-30 22:43:41 -07002274 res = stream->finishConfiguration();
2275 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002276 // If finishConfiguration fails due to abandoned surface, do not set
2277 // device to error state.
2278 bool isSurfaceAbandoned =
2279 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2280 if (!isSurfaceAbandoned) {
2281 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2282 stream->getId(), strerror(-res), res);
2283 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002284 return res;
2285 }
Zhijun He5d677d12016-05-29 16:52:39 -07002286 }
2287
2288 return OK;
2289}
2290
Emilian Peev40ead602017-09-26 15:46:36 +01002291status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2292 const std::vector<OutputStreamInfo> &outputInfo,
2293 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2294 Mutex::Autolock il(mInterfaceLock);
2295 Mutex::Autolock l(mLock);
2296
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002297 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2298 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002299 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002300 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002301 }
2302
2303 for (const auto &it : removedSurfaceIds) {
2304 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2305 CLOGE("Shared surface still part of a pending request!");
2306 return -EBUSY;
2307 }
2308 }
2309
Emilian Peev40ead602017-09-26 15:46:36 +01002310 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2311 if (res != OK) {
2312 CLOGE("Stream %d failed to update stream (error %d %s) ",
2313 streamId, res, strerror(-res));
2314 if (res == UNKNOWN_ERROR) {
2315 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2316 __FUNCTION__);
2317 }
2318 return res;
2319 }
2320
2321 return res;
2322}
2323
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002324status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2325 Mutex::Autolock il(mInterfaceLock);
2326 Mutex::Autolock l(mLock);
2327
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002328 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2329 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002330 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2331 return BAD_VALUE;
2332 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002333
2334 if (dropping) {
2335 mSessionStatsBuilder.stopCounter(streamId);
2336 } else {
2337 mSessionStatsBuilder.startCounter(streamId);
2338 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002339 return stream->dropBuffers(dropping);
2340}
2341
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002342/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343 * Camera3Device private methods
2344 */
2345
2346sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002347 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002348 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002349
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002350 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002351 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002352
2353 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002354 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002355 if (inputStreams.count > 0) {
2356 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002357 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002358 CLOGE("Request references unknown input stream %d",
2359 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 return NULL;
2361 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002362
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002364 SET_ERR_L("%s: input stream %d is not configured!",
2365 __FUNCTION__, mInputStream->getId());
2366 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002368 // Check if stream prepare is blocking requests.
2369 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002370 CLOGE("Request references an input stream that's being prepared!");
2371 return NULL;
2372 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
2374 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002375 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376 }
2377
2378 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002379 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002381 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 return NULL;
2383 }
2384
2385 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002386 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2387 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002388 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002389 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 return NULL;
2391 }
Zhijun He5d677d12016-05-29 16:52:39 -07002392 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002393 auto iter = surfaceMap.find(streams.data.i32[i]);
2394 if (iter != surfaceMap.end()) {
2395 const std::vector<size_t>& surfaces = iter->second;
2396 for (const auto& surface : surfaces) {
2397 if (stream->isConsumerConfigurationDeferred(surface)) {
2398 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2399 "due to deferred consumer", stream->getId(), surface);
2400 return NULL;
2401 }
2402 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002403 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002404 }
2405
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002407 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2408 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002410 // Check if stream prepare is blocking requests.
2411 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002412 CLOGE("Request references an output stream that's being prepared!");
2413 return NULL;
2414 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002415
2416 newRequest->mOutputStreams.push(stream);
2417 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002418 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002419 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002421 auto rotateAndCropEntry =
2422 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2423 if (rotateAndCropEntry.count > 0 &&
2424 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2425 newRequest->mRotateAndCropAuto = true;
2426 } else {
2427 newRequest->mRotateAndCropAuto = false;
2428 }
2429
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002430 auto zoomRatioEntry =
2431 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2432 if (zoomRatioEntry.count > 0 &&
2433 zoomRatioEntry.data.f[0] == 1.0f) {
2434 newRequest->mZoomRatioIs1x = true;
2435 } else {
2436 newRequest->mZoomRatioIs1x = false;
2437 }
2438
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002439 if (mSupportCameraMute) {
2440 auto testPatternModeEntry =
2441 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2442 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2443 testPatternModeEntry.data.i32[0] :
2444 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2445
2446 auto testPatternDataEntry =
2447 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2448 if (testPatternDataEntry.count > 0) {
2449 memcpy(newRequest->mOriginalTestPatternData, testPatternModeEntry.data.i32,
2450 sizeof(newRequest->mOriginalTestPatternData));
2451 } else {
2452 newRequest->mOriginalTestPatternData[0] = 0;
2453 newRequest->mOriginalTestPatternData[1] = 0;
2454 newRequest->mOriginalTestPatternData[2] = 0;
2455 newRequest->mOriginalTestPatternData[3] = 0;
2456 }
2457 }
2458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002460}
2461
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002462void Camera3Device::cancelStreamsConfigurationLocked() {
2463 int res = OK;
2464 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2465 res = mInputStream->cancelConfiguration();
2466 if (res != OK) {
2467 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2468 mInputStream->getId(), strerror(-res), res);
2469 }
2470 }
2471
2472 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002473 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002474 if (outputStream->isConfiguring()) {
2475 res = outputStream->cancelConfiguration();
2476 if (res != OK) {
2477 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2478 outputStream->getId(), strerror(-res), res);
2479 }
2480 }
2481 }
2482
2483 // Return state to that at start of call, so that future configures
2484 // properly clean things up
2485 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2486 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002487
2488 res = mPreparerThread->resume();
2489 if (res != OK) {
2490 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2491 }
2492}
2493
Emilian Peev0d0191e2020-04-21 17:01:18 -07002494bool Camera3Device::checkAbandonedStreamsLocked() {
2495 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2496 return true;
2497 }
2498
2499 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2500 auto stream = mOutputStreams[i];
2501 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2502 return true;
2503 }
2504 }
2505
2506 return false;
2507}
2508
Emilian Peev3bead5f2020-05-28 17:29:08 -07002509bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002510 ATRACE_CALL();
2511 bool ret = false;
2512
Shuzhen Wang316781a2020-08-18 18:11:01 -07002513 nsecs_t startTime = systemTime();
2514
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002515 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002516 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2517
2518 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002519 if (checkAbandonedStreamsLocked()) {
2520 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2521 __FUNCTION__);
2522 return true;
2523 }
2524
Emilian Peev3bead5f2020-05-28 17:29:08 -07002525 status_t rc = NO_ERROR;
2526 bool markClientActive = false;
2527 if (mStatus == STATUS_ACTIVE) {
2528 markClientActive = true;
2529 mPauseStateNotify = true;
2530 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2531
2532 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2533 }
2534
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002535 if (rc == NO_ERROR) {
2536 mNeedConfig = true;
2537 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2538 if (rc == NO_ERROR) {
2539 ret = true;
2540 mPauseStateNotify = false;
2541 //Moving to active state while holding 'mLock' is important.
2542 //There could be pending calls to 'create-/deleteStream' which
2543 //will trigger another stream configuration while the already
2544 //present streams end up with outstanding buffers that will
2545 //not get drained.
2546 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002547 } else if (rc == DEAD_OBJECT) {
2548 // DEAD_OBJECT can be returned if either the consumer surface is
2549 // abandoned, or the HAL has died.
2550 // - If the HAL has died, configureStreamsLocked call will set
2551 // device to error state,
2552 // - If surface is abandoned, we should not set device to error
2553 // state.
2554 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002555 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002556 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002557 }
2558 } else {
2559 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2560 }
2561
Shuzhen Wang316781a2020-08-18 18:11:01 -07002562 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2563 ns2ms(systemTime() - startTime));
2564
Emilian Peev3bead5f2020-05-28 17:29:08 -07002565 if (markClientActive) {
2566 mStatusTracker->markComponentActive(clientStatusId);
2567 }
2568
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002569 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002570}
2571
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002572status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002573 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002574 ATRACE_CALL();
2575 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002576
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002577 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002578 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 return INVALID_OPERATION;
2580 }
2581
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002582 if (operatingMode < 0) {
2583 CLOGE("Invalid operating mode: %d", operatingMode);
2584 return BAD_VALUE;
2585 }
2586
2587 bool isConstrainedHighSpeed =
2588 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2589 operatingMode;
2590
2591 if (mOperatingMode != operatingMode) {
2592 mNeedConfig = true;
2593 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2594 mOperatingMode = operatingMode;
2595 }
2596
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002597 // In case called from configureStreams, abort queued input buffers not belonging to
2598 // any pending requests.
2599 if (mInputStream != NULL && notifyRequestThread) {
2600 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002601 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002602 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002603 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002604 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002605 if (res != OK) {
2606 // Exhausted acquiring all input buffers.
2607 break;
2608 }
2609
Emilian Peevf4816702020-04-03 15:44:51 -07002610 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002611 res = mInputStream->returnInputBuffer(inputBuffer);
2612 if (res != OK) {
2613 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2614 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2615 }
2616 }
2617 }
2618
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002619 if (!mNeedConfig) {
2620 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2621 return OK;
2622 }
2623
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002625 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002626 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2627 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002628 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002629 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002630 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002631 }
2632
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002634 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002635
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002636 mPreparerThread->pause();
2637
Emilian Peevf4816702020-04-03 15:44:51 -07002638 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002639 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002641 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002642
Emilian Peevf4816702020-04-03 15:44:51 -07002643 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002645 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002646
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647
2648 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002649 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650 inputStream = mInputStream->startConfiguration();
2651 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002652 CLOGE("Can't start input stream configuration");
2653 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 return INVALID_OPERATION;
2655 }
2656 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002657
2658 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659 }
2660
Shuzhen Wang99080502021-03-07 21:08:20 -08002661 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002663
2664 // Don't configure bidi streams twice, nor add them twice to the list
2665 if (mOutputStreams[i].get() ==
2666 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2667
2668 config.num_streams--;
2669 continue;
2670 }
2671
Emilian Peevf4816702020-04-03 15:44:51 -07002672 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002673 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002674 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002675 CLOGE("Can't start output stream configuration");
2676 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 return INVALID_OPERATION;
2678 }
2679 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002680
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002681 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002682 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2683 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002684 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2685 bufferSizes[k] = static_cast<uint32_t>(
2686 getJpegBufferSize(outputStream->width, outputStream->height));
2687 } else if (outputStream->data_space ==
2688 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2689 bufferSizes[k] = outputStream->width * outputStream->height;
2690 } else {
2691 ALOGW("%s: Blob dataSpace %d not supported",
2692 __FUNCTION__, outputStream->data_space);
2693 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002694 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002695
2696 if (mOutputStreams[i]->isMultiResolution()) {
2697 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2698 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2699 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2700 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002701 }
2702
2703 config.streams = streams.editArray();
2704
2705 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002706 // max_buffers, usage, and priv fields, as well as data_space and format
2707 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002708
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002709 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002710 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002711 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002712
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002713 if (res == BAD_VALUE) {
2714 // HAL rejected this set of streams as unsupported, clean up config
2715 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002716 CLOGE("Set of requested inputs/outputs not supported by HAL");
2717 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002718 return BAD_VALUE;
2719 } else if (res != OK) {
2720 // Some other kind of error from configure_streams - this is not
2721 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002722 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2723 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002724 return res;
2725 }
2726
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002727 // Finish all stream configuration immediately.
2728 // TODO: Try to relax this later back to lazy completion, which should be
2729 // faster
2730
Igor Murashkin073f8572013-05-02 14:59:28 -07002731 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002732 bool streamReConfigured = false;
2733 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002734 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002735 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002736 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002737 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002738 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2739 return DEAD_OBJECT;
2740 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002741 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002742 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002743 if (streamReConfigured) {
2744 mInterface->onStreamReConfigured(mInputStream->getId());
2745 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002746 }
2747
2748 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002749 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002750 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002751 bool streamReConfigured = false;
2752 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002753 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002754 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002755 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002756 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002757 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2758 return DEAD_OBJECT;
2759 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002760 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002761 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002762 if (streamReConfigured) {
2763 mInterface->onStreamReConfigured(outputStream->getId());
2764 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002765 }
2766 }
2767
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002768 // Request thread needs to know to avoid using repeat-last-settings protocol
2769 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002770 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002771 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2772 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002773 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002774
Zhijun He90f7c372016-08-16 16:19:43 -07002775 char value[PROPERTY_VALUE_MAX];
2776 property_get("camera.fifo.disable", value, "0");
2777 int32_t disableFifo = atoi(value);
2778 if (disableFifo != 1) {
2779 // Boost priority of request thread to SCHED_FIFO.
2780 pid_t requestThreadTid = mRequestThread->getTid();
2781 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002782 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002783 if (res != OK) {
2784 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2785 strerror(-res), res);
2786 } else {
2787 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2788 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002789 }
2790
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002791 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002792 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2793 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2794 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2795 sessionParams.unlock(newSessionParams);
2796 mSessionParams.unlock(currentSessionParams);
2797 if (updateSessionParams) {
2798 mSessionParams = sessionParams;
2799 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002800
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002801 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002803 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002804 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002805
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002806 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002807
Zhijun He0a210512014-07-24 13:45:15 -07002808 // tear down the deleted streams after configure streams.
2809 mDeletedStreams.clear();
2810
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002811 auto rc = mPreparerThread->resume();
2812 if (rc != OK) {
2813 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2814 return rc;
2815 }
2816
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002817 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002818 mRequestBufferSM.onStreamsConfigured();
2819 }
2820
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002821 // Since the streams configuration of the injection camera is based on the internal camera, we
2822 // must wait until the internal camera configure streams before calling injectCamera() to
2823 // configure the injection streams.
2824 if (mInjectionMethods->isInjecting()) {
2825 ALOGV("%s: Injection camera %s: Start to configure streams.",
2826 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2827 res = mInjectionMethods->injectCamera(config, bufferSizes);
2828 if (res != OK) {
2829 ALOGE("Can't finish inject camera process!");
2830 return res;
2831 }
2832 }
2833
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002834 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002835}
2836
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002837status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002838 ATRACE_CALL();
2839 status_t res;
2840
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002841 if (mFakeStreamId != NO_STREAM) {
2842 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002843 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002844 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002845 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002846 return INVALID_OPERATION;
2847 }
2848
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002849 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002850
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002851 sp<Camera3OutputStreamInterface> fakeStream =
2852 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002853
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002854 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002855 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002856 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002857 return res;
2858 }
2859
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002860 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002861 mNextStreamId++;
2862
2863 return OK;
2864}
2865
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002866status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002867 ATRACE_CALL();
2868 status_t res;
2869
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002870 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 if (mOutputStreams.size() == 1) return OK;
2872
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002873 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002874
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002875 // Ok, have a fake stream and there's at least one other output stream,
2876 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002879 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002881 return INVALID_OPERATION;
2882 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002884
2885 // Free up the stream endpoint so that it can be used by some other stream
2886 res = deletedStream->disconnect();
2887 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 // fall through since we want to still list the stream as deleted.
2890 }
2891 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002892 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002893
2894 return res;
2895}
2896
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002897void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002898 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002899 Mutex::Autolock l(mLock);
2900 va_list args;
2901 va_start(args, fmt);
2902
2903 setErrorStateLockedV(fmt, args);
2904
2905 va_end(args);
2906}
2907
2908void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002909 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002910 Mutex::Autolock l(mLock);
2911 setErrorStateLockedV(fmt, args);
2912}
2913
2914void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2915 va_list args;
2916 va_start(args, fmt);
2917
2918 setErrorStateLockedV(fmt, args);
2919
2920 va_end(args);
2921}
2922
2923void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002924 // Print out all error messages to log
2925 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002926 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002927
2928 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002929 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002930
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002931 mErrorCause = errorCause;
2932
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002933 if (mRequestThread != nullptr) {
2934 mRequestThread->setPaused(true);
2935 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002936 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002937
2938 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002939 sp<NotificationListener> listener = mListener.promote();
2940 if (listener != NULL) {
2941 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002942 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002943 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002944 }
2945
2946 // Save stack trace. View by dumping it later.
2947 CameraTraces::saveTrace();
2948 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002949}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002950
2951/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952 * In-flight request management
2953 */
2954
Jianing Weicb0652e2014-03-12 18:29:36 -07002955status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002956 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002957 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002958 const std::set<std::set<String8>>& physicalCameraIds,
2959 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2960 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002961 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002962 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002963 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002964
2965 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002966 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002967 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002968 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002969 if (res < 0) return res;
2970
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002971 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002972 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2973 // avoid a deadlock during reprocess requests.
2974 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002975 if (mStatusTracker != nullptr) {
2976 mStatusTracker->markComponentActive(mInFlightStatusId);
2977 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002978 }
2979
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002980 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002981 return OK;
2982}
2983
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002984void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002985 // Indicate idle inFlightMap to the status tracker
2986 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002987 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002988 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2989 // avoid a deadlock during reprocess requests.
2990 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002991 if (mStatusTracker != nullptr) {
2992 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2993 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002994 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002995 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002996}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002997
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002998void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002999 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003000 // something has likely gone wrong. This might still be legit only if application send in
3001 // a long burst of long exposure requests.
3002 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3003 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3004 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3005 mInFlightMap.size(), mExpectedInflightDuration);
3006 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3007 kInFlightWarnLimitHighSpeed) {
3008 CLOGW("In-flight list too large for high speed configuration: %zu,"
3009 "total inflight duration %" PRIu64,
3010 mInFlightMap.size(), mExpectedInflightDuration);
3011 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012 }
3013}
3014
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003015void Camera3Device::onInflightMapFlushedLocked() {
3016 mExpectedInflightDuration = 0;
3017}
3018
3019void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003020 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003021 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3022 mInFlightMap.removeItemsAt(idx, 1);
3023
3024 onInflightEntryRemovedLocked(duration);
3025}
3026
3027
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003028void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003029 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003030 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003031 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003032 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003033 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003034 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003035
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003036 FlushInflightReqStates states {
3037 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003038 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003039
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003040 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003041}
3042
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003043CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003044 ALOGV("%s", __FUNCTION__);
3045
Igor Murashkin1e479c02013-09-06 16:55:14 -07003046 CameraMetadata retVal;
3047
3048 if (mRequestThread != NULL) {
3049 retVal = mRequestThread->getLatestRequest();
3050 }
3051
Igor Murashkin1e479c02013-09-06 16:55:14 -07003052 return retVal;
3053}
3054
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003055void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003056 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3057 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3058
3059 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3060 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003061}
3062
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003063/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003064 * HalInterface inner class methods
3065 */
3066
Yifan Hongf79b5542017-04-11 14:44:25 -07003067Camera3Device::HalInterface::HalInterface(
3068 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003069 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003070 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003071 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003072 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003073 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003074 mIsReconfigurationQuerySupported(true),
3075 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003076 // Check with hardware service manager if we can downcast these interfaces
3077 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003078 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3079 if (castResult_3_7.isOk()) {
3080 mHidlSession_3_7 = castResult_3_7;
3081 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003082 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3083 if (castResult_3_6.isOk()) {
3084 mHidlSession_3_6 = castResult_3_6;
3085 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003086 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3087 if (castResult_3_5.isOk()) {
3088 mHidlSession_3_5 = castResult_3_5;
3089 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003090 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3091 if (castResult_3_4.isOk()) {
3092 mHidlSession_3_4 = castResult_3_4;
3093 }
3094 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3095 if (castResult_3_3.isOk()) {
3096 mHidlSession_3_3 = castResult_3_3;
3097 }
3098}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003099
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003100Camera3Device::HalInterface::HalInterface() :
3101 mUseHalBufManager(false),
3102 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003103
3104Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003105 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003106 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003107 mUseHalBufManager(other.mUseHalBufManager),
3108 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003109
3110bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003111 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003112}
3113
3114void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003115 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003116 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003117 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003118 mHidlSession_3_4.clear();
3119 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003120 mHidlSession.clear();
3121}
3122
3123status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003124 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125 /*out*/ camera_metadata_t **requestTemplate) {
3126 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3127 if (!valid()) return INVALID_OPERATION;
3128 status_t res = OK;
3129
Emilian Peev31abd0a2017-05-11 18:37:46 +01003130 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003131
3132 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003133 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003134 status = s;
3135 if (status == common::V1_0::Status::OK) {
3136 const camera_metadata *r =
3137 reinterpret_cast<const camera_metadata_t*>(request.data());
3138 size_t expectedSize = request.size();
3139 int ret = validate_camera_metadata_structure(r, &expectedSize);
3140 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3141 *requestTemplate = clone_camera_metadata(r);
3142 if (*requestTemplate == nullptr) {
3143 ALOGE("%s: Unable to clone camera metadata received from HAL",
3144 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003145 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003146 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003147 } else {
3148 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3149 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003150 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003151 }
3152 };
3153 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003154 RequestTemplate id;
3155 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003156 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003157 id = RequestTemplate::PREVIEW;
3158 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003159 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003160 id = RequestTemplate::STILL_CAPTURE;
3161 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003162 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003163 id = RequestTemplate::VIDEO_RECORD;
3164 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003165 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003166 id = RequestTemplate::VIDEO_SNAPSHOT;
3167 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003168 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003169 id = RequestTemplate::ZERO_SHUTTER_LAG;
3170 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003171 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003172 id = RequestTemplate::MANUAL;
3173 break;
3174 default:
3175 // Unknown template ID, or this HAL is too old to support it
3176 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003177 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003178 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003179
Emilian Peev31abd0a2017-05-11 18:37:46 +01003180 if (!err.isOk()) {
3181 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3182 res = DEAD_OBJECT;
3183 } else {
3184 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003185 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003186
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003187 return res;
3188}
3189
Emilian Peev4ec17882019-01-24 17:16:58 -08003190bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3191 CameraMetadata& newSessionParams) {
3192 // We do reconfiguration by default;
3193 bool ret = true;
3194 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3195 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3196 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3197 oldSessionParams.getAndLock());
3198 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3199 newSessionParams.getAndLock());
3200 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3201 get_camera_metadata_size(oldSessioMeta));
3202 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3203 get_camera_metadata_size(newSessioMeta));
3204 hardware::camera::common::V1_0::Status callStatus;
3205 bool required;
3206 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3207 bool requiredFlag) {
3208 callStatus = s;
3209 required = requiredFlag;
3210 };
3211 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3212 oldSessionParams.unlock(oldSessioMeta);
3213 newSessionParams.unlock(newSessioMeta);
3214 if (err.isOk()) {
3215 switch (callStatus) {
3216 case hardware::camera::common::V1_0::Status::OK:
3217 ret = required;
3218 break;
3219 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3220 mIsReconfigurationQuerySupported = false;
3221 ret = true;
3222 break;
3223 default:
3224 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3225 ret = true;
3226 }
3227 } else {
3228 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3229 ret = true;
3230 }
3231 }
3232
3233 return ret;
3234}
3235
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003236status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003237 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003238 ATRACE_NAME("CameraHal::configureStreams");
3239 if (!valid()) return INVALID_OPERATION;
3240 status_t res = OK;
3241
Shuzhen Wang83bff122020-11-20 15:51:39 -08003242 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3243 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3244 return BAD_VALUE;
3245 }
3246
Emilian Peev31abd0a2017-05-11 18:37:46 +01003247 // Convert stream config to HIDL
3248 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003249 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3250 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003251 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003252 requestedConfiguration3_2.streams.resize(config->num_streams);
3253 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003254 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003255 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003256 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3257 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003258 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003259 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003260
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3262 cam3stream->setBufferFreedListener(this);
3263 int streamId = cam3stream->getId();
3264 StreamType streamType;
3265 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003266 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003267 streamType = StreamType::OUTPUT;
3268 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003269 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003270 streamType = StreamType::INPUT;
3271 break;
3272 default:
3273 ALOGE("%s: Stream %d: Unsupported stream type %d",
3274 __FUNCTION__, streamId, config->streams[i]->stream_type);
3275 return BAD_VALUE;
3276 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 dst3_2.id = streamId;
3278 dst3_2.streamType = streamType;
3279 dst3_2.width = src->width;
3280 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003281 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003282 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003283 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003284 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003285 if (mHidlSession_3_5 != nullptr) {
3286 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3287 cam3stream->getOriginalFormat() : src->format);
3288 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3289 cam3stream->getOriginalDataSpace() : src->data_space);
3290 } else {
3291 dst3_2.format = mapToPixelFormat(src->format);
3292 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3293 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003294 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003295 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003296 if (src->physical_camera_id != nullptr) {
3297 dst3_4.physicalCameraId = src->physical_camera_id;
3298 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003299 dst3_7.v3_4 = dst3_4;
3300 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003301 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3302 size_t j = 0;
3303 for (int mode : src->sensor_pixel_modes_used) {
3304 dst3_7.sensorPixelModesUsed[j++] =
3305 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3306 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003307 activeStreams.insert(streamId);
3308 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003309 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003310 }
3311 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003312 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003314 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003315 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003316 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003317 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003318 if (res != OK) {
3319 return res;
3320 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003321 requestedConfiguration3_2.operationMode = operationMode;
3322 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003323 requestedConfiguration3_7.operationMode = operationMode;
3324 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003325 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003326 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003327 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003328 requestedConfiguration3_7.operationMode = operationMode;
3329 requestedConfiguration3_7.sessionParams.setToExternal(
3330 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003331 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003332
Emilian Peev31abd0a2017-05-11 18:37:46 +01003333 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003334 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003335 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003336 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003337 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003338
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003339 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003340 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3341 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003342 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003343 };
3344
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003345 auto configStream36Cb = [&status, &finalConfiguration3_6]
3346 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3347 finalConfiguration3_6 = halConfiguration;
3348 status = s;
3349 };
3350
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003351 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3352 (hardware::Return<void>& err) -> status_t {
3353 if (!err.isOk()) {
3354 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3355 return DEAD_OBJECT;
3356 }
3357 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3358 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3359 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3360 }
3361 return OK;
3362 };
3363
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003364 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3365 (hardware::Return<void>& err) -> status_t {
3366 if (!err.isOk()) {
3367 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3368 return DEAD_OBJECT;
3369 }
3370 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3371 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3372 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3373 }
3374 return OK;
3375 };
3376
Shuzhen Wang92653952019-05-07 15:11:43 -07003377 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003378 if (mHidlSession_3_7 != nullptr) {
3379 ALOGV("%s: v3.7 device found", __FUNCTION__);
3380 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3381 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3382 auto err = mHidlSession_3_7->configureStreams_3_7(
3383 requestedConfiguration3_7, configStream36Cb);
3384 res = postprocConfigStream36(err);
3385 if (res != OK) {
3386 return res;
3387 }
3388 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003389 ALOGV("%s: v3.6 device found", __FUNCTION__);
3390 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3391 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3392 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3393 auto err = mHidlSession_3_6->configureStreams_3_6(
3394 requestedConfiguration3_5, configStream36Cb);
3395 res = postprocConfigStream36(err);
3396 if (res != OK) {
3397 return res;
3398 }
3399 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003400 ALOGV("%s: v3.5 device found", __FUNCTION__);
3401 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3402 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3403 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3404 auto err = mHidlSession_3_5->configureStreams_3_5(
3405 requestedConfiguration3_5, configStream34Cb);
3406 res = postprocConfigStream34(err);
3407 if (res != OK) {
3408 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003409 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003410 } else if (mHidlSession_3_4 != nullptr) {
3411 // We do; use v3.4 for the call
3412 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003413 auto err = mHidlSession_3_4->configureStreams_3_4(
3414 requestedConfiguration3_4, configStream34Cb);
3415 res = postprocConfigStream34(err);
3416 if (res != OK) {
3417 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003418 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003419 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003420 // We do; use v3.3 for the call
3421 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003422 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003423 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003424 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003425 finalConfiguration = halConfiguration;
3426 status = s;
3427 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003428 if (!err.isOk()) {
3429 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3430 return DEAD_OBJECT;
3431 }
3432 } else {
3433 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3434 ALOGV("%s: v3.2 device found", __FUNCTION__);
3435 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003436 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003437 [&status, &finalConfiguration_3_2]
3438 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3439 finalConfiguration_3_2 = halConfiguration;
3440 status = s;
3441 });
3442 if (!err.isOk()) {
3443 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3444 return DEAD_OBJECT;
3445 }
3446 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3447 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3448 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3449 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003450 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003451 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003452 }
3453
3454 if (status != common::V1_0::Status::OK ) {
3455 return CameraProviderManager::mapToStatusT(status);
3456 }
3457
3458 // And convert output stream configuration from HIDL
3459
3460 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003461 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003462 int streamId = Camera3Stream::cast(dst)->getId();
3463
3464 // Start scan at i, with the assumption that the stream order matches
3465 size_t realIdx = i;
3466 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003467 size_t halStreamCount = finalConfiguration.streams.size();
3468 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003469 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003470 found = true;
3471 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003472 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003473 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003474 }
3475 if (!found) {
3476 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3477 __FUNCTION__, streamId);
3478 return INVALID_OPERATION;
3479 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003480 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003481 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003482
Emilian Peev710c1422017-08-30 11:19:38 +01003483 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003484 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3485 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3486
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003487 if (mHidlSession_3_6 != nullptr) {
3488 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3489 }
3490
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003491 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003492 dstStream->setFormatOverride(false);
3493 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003494 if (dst->format != overrideFormat) {
3495 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3496 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003497 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003498 if (dst->data_space != overrideDataSpace) {
3499 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3500 streamId, dst->format);
3501 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003503 bool needFormatOverride =
3504 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3505 bool needDataspaceOverride =
3506 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003507 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003508 dstStream->setFormatOverride(needFormatOverride);
3509 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003510 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003511 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003512 }
3513
Emilian Peevf4816702020-04-03 15:44:51 -07003514 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003515 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003516 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003517 __FUNCTION__, streamId);
3518 return INVALID_OPERATION;
3519 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003520 dstStream->setUsage(
3521 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003522 } else {
3523 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003524 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003525 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3526 __FUNCTION__, streamId);
3527 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003528 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 dstStream->setUsage(
3530 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003531 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003532 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003533 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003534
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003535 return res;
3536}
3537
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003538status_t Camera3Device::HalInterface::configureInjectedStreams(
3539 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3540 const std::vector<uint32_t>& bufferSizes,
3541 const CameraMetadata& cameraCharacteristics) {
3542 ATRACE_NAME("InjectionCameraHal::configureStreams");
3543 if (!valid()) return INVALID_OPERATION;
3544 status_t res = OK;
3545
3546 if (config->input_is_multi_resolution) {
3547 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3548 "stream", __FUNCTION__);
3549 return BAD_VALUE;
3550 }
3551
3552 // Convert stream config to HIDL
3553 std::set<int> activeStreams;
3554 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3555 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3556 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3557 requestedConfiguration3_2.streams.resize(config->num_streams);
3558 requestedConfiguration3_4.streams.resize(config->num_streams);
3559 requestedConfiguration3_7.streams.resize(config->num_streams);
3560 for (size_t i = 0; i < config->num_streams; i++) {
3561 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3562 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3563 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3564 camera3::camera_stream_t* src = config->streams[i];
3565
3566 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3567 cam3stream->setBufferFreedListener(this);
3568 int streamId = cam3stream->getId();
3569 StreamType streamType;
3570 switch (src->stream_type) {
3571 case CAMERA_STREAM_OUTPUT:
3572 streamType = StreamType::OUTPUT;
3573 break;
3574 case CAMERA_STREAM_INPUT:
3575 streamType = StreamType::INPUT;
3576 break;
3577 default:
3578 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3579 streamId, config->streams[i]->stream_type);
3580 return BAD_VALUE;
3581 }
3582 dst3_2.id = streamId;
3583 dst3_2.streamType = streamType;
3584 dst3_2.width = src->width;
3585 dst3_2.height = src->height;
3586 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3587 dst3_2.rotation =
3588 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3589 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3590 // to HAL are original, not the overridden ones.
3591 if (mHidlSession_3_5 != nullptr) {
3592 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3593 ? cam3stream->getOriginalFormat()
3594 : src->format);
3595 dst3_2.dataSpace =
3596 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3597 ? cam3stream->getOriginalDataSpace()
3598 : src->data_space);
3599 } else {
3600 dst3_2.format = mapToPixelFormat(src->format);
3601 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3602 }
3603 dst3_4.v3_2 = dst3_2;
3604 dst3_4.bufferSize = bufferSizes[i];
3605 if (src->physical_camera_id != nullptr) {
3606 dst3_4.physicalCameraId = src->physical_camera_id;
3607 }
3608 dst3_7.v3_4 = dst3_4;
3609 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3610 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3611 size_t j = 0;
3612 for (int mode : src->sensor_pixel_modes_used) {
3613 dst3_7.sensorPixelModesUsed[j++] =
3614 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3615 }
3616 activeStreams.insert(streamId);
3617 // Create Buffer ID map if necessary
3618 mBufferRecords.tryCreateBufferCache(streamId);
3619 }
3620 // remove BufferIdMap for deleted streams
3621 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3622
3623 StreamConfigurationMode operationMode;
3624 res = mapToStreamConfigurationMode(
3625 (camera_stream_configuration_mode_t)config->operation_mode,
3626 /*out*/ &operationMode);
3627 if (res != OK) {
3628 return res;
3629 }
3630 requestedConfiguration3_7.operationMode = operationMode;
3631 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3632 requestedConfiguration3_7.operationMode = operationMode;
3633 requestedConfiguration3_7.sessionParams.setToExternal(
3634 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3635 sessionParamSize);
3636
3637 // See which version of HAL we have
3638 if (mHidlSession_3_7 != nullptr) {
3639 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3640 requestedConfiguration3_7.multiResolutionInputImage =
3641 config->input_is_multi_resolution;
3642
3643 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3644 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3645 hidlChars.setToExternal(
3646 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3647 get_camera_metadata_size(rawMetadata));
3648 cameraCharacteristics.unlock(rawMetadata);
3649
3650 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3651 hidlInjectionSession_3_7;
3652 auto castInjectionResult_3_7 =
3653 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3654 if (castInjectionResult_3_7.isOk()) {
3655 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3656 } else {
3657 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3658 castInjectionResult_3_7.description().c_str());
3659 return DEAD_OBJECT;
3660 }
3661
3662 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3663 requestedConfiguration3_7, hidlChars);
3664 if (!err.isOk()) {
3665 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3666 err.description().c_str());
3667 return DEAD_OBJECT;
3668 }
3669 } else {
3670 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3671 "session is 3.7", __FUNCTION__);
3672 return DEAD_OBJECT;
3673 }
3674
3675 return res;
3676}
3677
Emilian Peevf4816702020-04-03 15:44:51 -07003678status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003679 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003680 /*out*/std::vector<native_handle_t*>* handlesCreated,
3681 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003682 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003683 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3684 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3685 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003686 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003687 }
3688
3689 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003690
3691 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003692
3693 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003694 if (request->input_buffer != nullptr) {
3695 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3696 buffer_handle_t buf = *(request->input_buffer->buffer);
3697 auto pair = getBufferId(buf, streamId);
3698 bool isNewBuffer = pair.first;
3699 uint64_t bufferId = pair.second;
3700 captureRequest->inputBuffer.streamId = streamId;
3701 captureRequest->inputBuffer.bufferId = bufferId;
3702 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3703 captureRequest->inputBuffer.status = BufferStatus::OK;
3704 native_handle_t *acquireFence = nullptr;
3705 if (request->input_buffer->acquire_fence != -1) {
3706 acquireFence = native_handle_create(1,0);
3707 acquireFence->data[0] = request->input_buffer->acquire_fence;
3708 handlesCreated->push_back(acquireFence);
3709 }
3710 captureRequest->inputBuffer.acquireFence = acquireFence;
3711 captureRequest->inputBuffer.releaseFence = nullptr;
3712
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003713 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003714 request->input_buffer->buffer);
3715 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003716 } else {
3717 captureRequest->inputBuffer.streamId = -1;
3718 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3719 }
3720
3721 captureRequest->outputBuffers.resize(request->num_output_buffers);
3722 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003723 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003724 StreamBuffer &dst = captureRequest->outputBuffers[i];
3725 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003726 if (src->buffer != nullptr) {
3727 buffer_handle_t buf = *(src->buffer);
3728 auto pair = getBufferId(buf, streamId);
3729 bool isNewBuffer = pair.first;
3730 dst.bufferId = pair.second;
3731 dst.buffer = isNewBuffer ? buf : nullptr;
3732 native_handle_t *acquireFence = nullptr;
3733 if (src->acquire_fence != -1) {
3734 acquireFence = native_handle_create(1,0);
3735 acquireFence->data[0] = src->acquire_fence;
3736 handlesCreated->push_back(acquireFence);
3737 }
3738 dst.acquireFence = acquireFence;
3739 } else if (mUseHalBufManager) {
3740 // HAL buffer management path
3741 dst.bufferId = BUFFER_ID_NO_BUFFER;
3742 dst.buffer = nullptr;
3743 dst.acquireFence = nullptr;
3744 } else {
3745 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3746 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003747 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003748 dst.streamId = streamId;
3749 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003750 dst.releaseFence = nullptr;
3751
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003752 // Output buffers are empty when using HAL buffer manager
3753 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003754 mBufferRecords.pushInflightBuffer(
3755 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003756 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003757 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003758 }
3759 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003760 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003761}
3762
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003763void Camera3Device::HalInterface::cleanupNativeHandles(
3764 std::vector<native_handle_t*> *handles, bool closeFd) {
3765 if (handles == nullptr) {
3766 return;
3767 }
3768 if (closeFd) {
3769 for (auto& handle : *handles) {
3770 native_handle_close(handle);
3771 }
3772 }
3773 for (auto& handle : *handles) {
3774 native_handle_delete(handle);
3775 }
3776 handles->clear();
3777 return;
3778}
3779
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003780status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003781 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003782 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3783 if (!valid()) return INVALID_OPERATION;
3784
Emilian Peevaebbe412018-01-15 13:53:24 +00003785 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003786 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3787 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3788 if (castResult_3_7.isOk()) {
3789 hidlSession_3_7 = castResult_3_7;
3790 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003791 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3792 if (castResult_3_4.isOk()) {
3793 hidlSession_3_4 = castResult_3_4;
3794 }
3795
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003796 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003797 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003798 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003799 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003800 if (hidlSession_3_7 != nullptr) {
3801 captureRequests_3_7.resize(batchSize);
3802 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003803 captureRequests_3_4.resize(batchSize);
3804 } else {
3805 captureRequests.resize(batchSize);
3806 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003807 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003808 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003809
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003810 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003811 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003812 if (hidlSession_3_7 != nullptr) {
3813 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3814 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3815 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003816 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003817 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003818 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003819 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3820 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003821 }
3822 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003823 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003824 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003825 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003826 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 }
3828
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003829 std::vector<device::V3_2::BufferCache> cachesToRemove;
3830 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003831 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003832 for (auto& pair : mFreedBuffers) {
3833 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003834 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003835 cachesToRemove.push_back({pair.first, pair.second});
3836 }
3837 }
3838 mFreedBuffers.clear();
3839 }
3840
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003841 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3842 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003843
3844 // Write metadata to FMQ.
3845 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003846 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003847 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003848 if (hidlSession_3_7 != nullptr) {
3849 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3850 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 captureRequest = &captureRequests_3_4[i].v3_2;
3852 } else {
3853 captureRequest = &captureRequests[i];
3854 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003855
3856 if (request->settings != nullptr) {
3857 size_t settingsSize = get_camera_metadata_size(request->settings);
3858 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3859 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3860 captureRequest->settings.resize(0);
3861 captureRequest->fmqSettingsSize = settingsSize;
3862 } else {
3863 if (mRequestMetadataQueue != nullptr) {
3864 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3865 }
3866 captureRequest->settings.setToExternal(
3867 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3868 get_camera_metadata_size(request->settings));
3869 captureRequest->fmqSettingsSize = 0u;
3870 }
3871 } else {
3872 // A null request settings maps to a size-0 CameraMetadata
3873 captureRequest->settings.resize(0);
3874 captureRequest->fmqSettingsSize = 0u;
3875 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003876
Shuzhen Wang83bff122020-11-20 15:51:39 -08003877 // hidl session 3.7 specific handling.
3878 if (hidlSession_3_7 != nullptr) {
3879 captureRequests_3_7[i].inputWidth = request->input_width;
3880 captureRequests_3_7[i].inputHeight = request->input_height;
3881 }
3882
3883 // hidl session 3.7 and 3.4 specific handling.
3884 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3885 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3886 (hidlSession_3_7 != nullptr) ?
3887 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3888 captureRequests_3_4[i].physicalCameraSettings;
3889 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003890 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003891 if (request->physcam_settings != nullptr) {
3892 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3893 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3894 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3895 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003896 physicalCameraSettings[j].settings.resize(0);
3897 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003898 } else {
3899 if (mRequestMetadataQueue != nullptr) {
3900 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3901 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003902 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003903 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3904 request->physcam_settings[j])),
3905 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003906 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003907 }
Emilian Peev00420d22018-02-05 21:33:13 +00003908 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003909 physicalCameraSettings[j].fmqSettingsSize = 0u;
3910 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003911 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003912 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003913 }
3914 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003915 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003916
3917 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003918 auto resultCallback =
3919 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3920 status = s;
3921 *numRequestProcessed = n;
3922 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003923 if (hidlSession_3_7 != nullptr) {
3924 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3925 resultCallback);
3926 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003927 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003928 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003929 } else {
3930 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003931 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003933 if (!err.isOk()) {
3934 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003935 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003936 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003937
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003938 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3939 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3940 __FUNCTION__, *numRequestProcessed, batchSize);
3941 status = common::V1_0::Status::INTERNAL_ERROR;
3942 }
3943
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003944 res = CameraProviderManager::mapToStatusT(status);
3945 if (res == OK) {
3946 if (mHidlSession->isRemote()) {
3947 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3948 // sent to camera HAL processes)
3949 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3950 } else {
3951 // In passthrough mode the FDs are now owned by HAL
3952 cleanupNativeHandles(&handlesCreated);
3953 }
3954 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003955 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003956 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003957 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003958 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003959}
3960
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003961status_t Camera3Device::HalInterface::flush() {
3962 ATRACE_NAME("CameraHal::flush");
3963 if (!valid()) return INVALID_OPERATION;
3964 status_t res = OK;
3965
Emilian Peev31abd0a2017-05-11 18:37:46 +01003966 auto err = mHidlSession->flush();
3967 if (!err.isOk()) {
3968 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3969 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003970 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003971 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003973
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974 return res;
3975}
3976
Emilian Peev31abd0a2017-05-11 18:37:46 +01003977status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978 ATRACE_NAME("CameraHal::dump");
3979 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003980
Emilian Peev31abd0a2017-05-11 18:37:46 +01003981 // Handled by CameraProviderManager::dump
3982
3983 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003984}
3985
3986status_t Camera3Device::HalInterface::close() {
3987 ATRACE_NAME("CameraHal::close()");
3988 if (!valid()) return INVALID_OPERATION;
3989 status_t res = OK;
3990
Emilian Peev31abd0a2017-05-11 18:37:46 +01003991 auto err = mHidlSession->close();
3992 // Interface will be dead shortly anyway, so don't log errors
3993 if (!err.isOk()) {
3994 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003995 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997 return res;
3998}
3999
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004000void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4001 ATRACE_NAME("CameraHal::signalPipelineDrain");
4002 if (!valid() || mHidlSession_3_5 == nullptr) {
4003 ALOGE("%s called on invalid camera!", __FUNCTION__);
4004 return;
4005 }
4006
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004007 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004008 if (!err.isOk()) {
4009 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4010 return;
4011 }
4012}
4013
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004014status_t Camera3Device::HalInterface::switchToOffline(
4015 const std::vector<int32_t>& streamsToKeep,
4016 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004017 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4018 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004019 ATRACE_NAME("CameraHal::switchToOffline");
4020 if (!valid() || mHidlSession_3_6 == nullptr) {
4021 ALOGE("%s called on invalid camera!", __FUNCTION__);
4022 return INVALID_OPERATION;
4023 }
4024
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004025 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4026 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004027 return INVALID_OPERATION;
4028 }
4029
4030 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004031 auto resultCallback =
4032 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4033 status = s;
4034 *offlineSessionInfo = info;
4035 *offlineSession = session;
4036 };
4037 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4038
4039 if (!err.isOk()) {
4040 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4041 return DEAD_OBJECT;
4042 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004043
4044 status_t ret = CameraProviderManager::mapToStatusT(status);
4045 if (ret != OK) {
4046 return ret;
4047 }
4048
4049 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4050 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4051 // returns from switchToOffline.
4052
4053
4054 // Validate buffer caches
4055 std::vector<int32_t> streams;
4056 streams.reserve(offlineSessionInfo->offlineStreams.size());
4057 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4058 int32_t id = offlineStream.id;
4059 streams.push_back(id);
4060 // Verify buffer caches
4061 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4062 offlineStream.circulatingBufferIds.end());
4063 if (!verifyBufferIds(id, bufIds)) {
4064 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4065 return UNKNOWN_ERROR;
4066 }
4067 }
4068
4069 // Move buffer records
4070 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4071 bufferRecords->takeInflightBufferMap(mBufferRecords);
4072 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4073 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004074}
4075
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004076void Camera3Device::HalInterface::getInflightBufferKeys(
4077 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004078 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004079 return;
4080}
4081
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004082void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4083 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004084 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004085 return;
4086}
4087
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004088bool Camera3Device::HalInterface::verifyBufferIds(
4089 int32_t streamId, std::vector<uint64_t>& bufIds) {
4090 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004091}
4092
4093status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004094 int32_t frameNumber, int32_t streamId,
4095 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004096 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004097}
4098
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004099status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004100 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004101 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004102}
4103
4104// Find and pop a buffer_handle_t based on bufferId
4105status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004106 uint64_t bufferId,
4107 /*out*/ buffer_handle_t** buffer,
4108 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004109 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004110}
4111
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004112std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4113 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004114 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004115}
4116
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004117void Camera3Device::HalInterface::onBufferFreed(
4118 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4120 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4121 if (bufferId != BUFFER_ID_NO_BUFFER) {
4122 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004123 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004124}
4125
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004126void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004127 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4128 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4129 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004130 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4131 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004132}
4133
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004134/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004135 * RequestThread inner class methods
4136 */
4137
4138Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004139 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004140 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4141 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004142 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004143 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004144 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004145 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004146 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004147 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004148 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004149 mReconfigured(false),
4150 mDoPause(false),
4151 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004152 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004153 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004154 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004155 mCurrentAfTriggerId(0),
4156 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004157 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004158 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004159 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004160 mRepeatingLastFrameNumber(
4161 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004162 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004163 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004164 mRequestLatency(kRequestLatencyBinSize),
4165 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004166 mLatestSessionParams(sessionParamKeys.size()),
4167 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004168 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004169}
4170
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004171Camera3Device::RequestThread::~RequestThread() {}
4172
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004173void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004174 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004175 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004176 Mutex::Autolock l(mRequestLock);
4177 mListener = listener;
4178}
4179
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004180void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004181 const CameraMetadata& sessionParams,
4182 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004183 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004184 Mutex::Autolock l(mRequestLock);
4185 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004186 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004187 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004188 // Prepare video stream for high speed recording.
4189 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004190 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004191}
4192
Jianing Wei90e59c92014-03-12 18:29:36 -07004193status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004194 List<sp<CaptureRequest> > &requests,
4195 /*out*/
4196 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004197 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004198 Mutex::Autolock l(mRequestLock);
4199 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4200 ++it) {
4201 mRequestQueue.push_back(*it);
4202 }
4203
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004204 if (lastFrameNumber != NULL) {
4205 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4206 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4207 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4208 *lastFrameNumber);
4209 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004210
Jianing Wei90e59c92014-03-12 18:29:36 -07004211 unpauseForNewRequests();
4212
4213 return OK;
4214}
4215
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004216
4217status_t Camera3Device::RequestThread::queueTrigger(
4218 RequestTrigger trigger[],
4219 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004220 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004221 Mutex::Autolock l(mTriggerMutex);
4222 status_t ret;
4223
4224 for (size_t i = 0; i < count; ++i) {
4225 ret = queueTriggerLocked(trigger[i]);
4226
4227 if (ret != OK) {
4228 return ret;
4229 }
4230 }
4231
4232 return OK;
4233}
4234
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004235const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4236 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004237 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004238 if (d != nullptr) return d->mId;
4239 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004240}
4241
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004242status_t Camera3Device::RequestThread::queueTriggerLocked(
4243 RequestTrigger trigger) {
4244
4245 uint32_t tag = trigger.metadataTag;
4246 ssize_t index = mTriggerMap.indexOfKey(tag);
4247
4248 switch (trigger.getTagType()) {
4249 case TYPE_BYTE:
4250 // fall-through
4251 case TYPE_INT32:
4252 break;
4253 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004254 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4255 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004256 return INVALID_OPERATION;
4257 }
4258
4259 /**
4260 * Collect only the latest trigger, since we only have 1 field
4261 * in the request settings per trigger tag, and can't send more than 1
4262 * trigger per request.
4263 */
4264 if (index != NAME_NOT_FOUND) {
4265 mTriggerMap.editValueAt(index) = trigger;
4266 } else {
4267 mTriggerMap.add(tag, trigger);
4268 }
4269
4270 return OK;
4271}
4272
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004273status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004274 const RequestList &requests,
4275 /*out*/
4276 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004277 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004278 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004279 if (lastFrameNumber != NULL) {
4280 *lastFrameNumber = mRepeatingLastFrameNumber;
4281 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004282 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004283 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004284 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4285 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004286
4287 unpauseForNewRequests();
4288
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004289 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004290 return OK;
4291}
4292
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004293bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004294 if (mRepeatingRequests.empty()) {
4295 return false;
4296 }
4297 int32_t requestId = requestIn->mResultExtras.requestId;
4298 const RequestList &repeatRequests = mRepeatingRequests;
4299 // All repeating requests are guaranteed to have same id so only check first quest
4300 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4301 return (firstRequest->mResultExtras.requestId == requestId);
4302}
4303
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004304status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004305 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004307 return clearRepeatingRequestsLocked(lastFrameNumber);
4308
4309}
4310
4311status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004313 if (lastFrameNumber != NULL) {
4314 *lastFrameNumber = mRepeatingLastFrameNumber;
4315 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004316 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 return OK;
4318}
4319
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004320status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004321 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004322 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004323 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004324 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004325
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004326 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004327
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004328 // Send errors for all requests pending in the request queue, including
4329 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004330 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004331 if (listener != NULL) {
4332 for (RequestList::iterator it = mRequestQueue.begin();
4333 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004334 // Abort the input buffers for reprocess requests.
4335 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004336 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004337 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004338 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004339 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004340 if (res != OK) {
4341 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4342 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4343 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004344 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004345 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4346 if (res != OK) {
4347 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4348 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4349 }
4350 }
4351 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004352 // Set the frame number this request would have had, if it
4353 // had been submitted; this frame number will not be reused.
4354 // The requestId and burstId fields were set when the request was
4355 // submitted originally (in convertMetadataListToRequestListLocked)
4356 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004357 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004358 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004359 }
4360 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004361 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004362
4363 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004364 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004365 if (lastFrameNumber != NULL) {
4366 *lastFrameNumber = mRepeatingLastFrameNumber;
4367 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004368 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004369 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004370 return OK;
4371}
4372
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004373status_t Camera3Device::RequestThread::flush() {
4374 ATRACE_CALL();
4375 Mutex::Autolock l(mFlushLock);
4376
Emilian Peev08dd2452017-04-06 16:55:14 +01004377 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004378}
4379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004381 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004382 Mutex::Autolock l(mPauseLock);
4383 mDoPause = paused;
4384 mDoPauseSignal.signal();
4385}
4386
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004387status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4388 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004389 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004390 Mutex::Autolock l(mLatestRequestMutex);
4391 status_t res;
4392 while (mLatestRequestId != requestId) {
4393 nsecs_t startTime = systemTime();
4394
4395 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4396 if (res != OK) return res;
4397
4398 timeout -= (systemTime() - startTime);
4399 }
4400
4401 return OK;
4402}
4403
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004404void Camera3Device::RequestThread::requestExit() {
4405 // Call parent to set up shutdown
4406 Thread::requestExit();
4407 // The exit from any possible waits
4408 mDoPauseSignal.signal();
4409 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004410
4411 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4412 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004413}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004414
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004415void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004416 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004417 bool surfaceAbandoned = false;
4418 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004419 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004420 {
4421 Mutex::Autolock l(mRequestLock);
4422 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4423 // repeating requests.
4424 for (const auto& request : mRepeatingRequests) {
4425 for (const auto& s : request->mOutputStreams) {
4426 if (s->isAbandoned()) {
4427 surfaceAbandoned = true;
4428 clearRepeatingRequestsLocked(&lastFrameNumber);
4429 break;
4430 }
4431 }
4432 if (surfaceAbandoned) {
4433 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004434 }
4435 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004436 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004437 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004438
4439 if (listener != NULL && surfaceAbandoned) {
4440 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004441 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004442}
4443
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004444bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004445 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004446 status_t res;
4447 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004448 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004449 uint32_t numRequestProcessed = 0;
4450 for (size_t i = 0; i < batchSize; i++) {
4451 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004452 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004453 }
4454
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004455 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4456
4457 bool triggerRemoveFailed = false;
4458 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4459 for (size_t i = 0; i < numRequestProcessed; i++) {
4460 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4461 nextRequest.submitted = true;
4462
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004463 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004464
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004465 if (!triggerRemoveFailed) {
4466 // Remove any previously queued triggers (after unlock)
4467 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4468 if (removeTriggerRes != OK) {
4469 triggerRemoveFailed = true;
4470 triggerFailedRequest = nextRequest;
4471 }
4472 }
4473 }
4474
4475 if (triggerRemoveFailed) {
4476 SET_ERR("RequestThread: Unable to remove triggers "
4477 "(capture request %d, HAL device: %s (%d)",
4478 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4479 cleanUpFailedRequests(/*sendRequestError*/ false);
4480 return false;
4481 }
4482
4483 if (res != OK) {
4484 // Should only get a failure here for malformed requests or device-level
4485 // errors, so consider all errors fatal. Bad metadata failures should
4486 // come through notify.
4487 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4488 mNextRequests[numRequestProcessed].halRequest.frame_number,
4489 strerror(-res), res);
4490 cleanUpFailedRequests(/*sendRequestError*/ false);
4491 return false;
4492 }
4493 return true;
4494}
4495
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004496nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4497 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4498 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4499 find_camera_metadata_ro_entry(request,
4500 ANDROID_CONTROL_AE_MODE,
4501 &e);
4502 if (e.count == 0) return maxExpectedDuration;
4503
4504 switch (e.data.u8[0]) {
4505 case ANDROID_CONTROL_AE_MODE_OFF:
4506 find_camera_metadata_ro_entry(request,
4507 ANDROID_SENSOR_EXPOSURE_TIME,
4508 &e);
4509 if (e.count > 0) {
4510 maxExpectedDuration = e.data.i64[0];
4511 }
4512 find_camera_metadata_ro_entry(request,
4513 ANDROID_SENSOR_FRAME_DURATION,
4514 &e);
4515 if (e.count > 0) {
4516 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4517 }
4518 break;
4519 default:
4520 find_camera_metadata_ro_entry(request,
4521 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4522 &e);
4523 if (e.count > 1) {
4524 maxExpectedDuration = 1e9 / e.data.u8[0];
4525 }
4526 break;
4527 }
4528
4529 return maxExpectedDuration;
4530}
4531
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004532bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4533 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4534 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4535 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4536 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4537 return true;
4538 }
4539
4540 return false;
4541}
4542
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004543void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4544 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004545 camera_capture_request_t& halRequest = nextRequest.halRequest;
4546 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004547 Mutex::Autolock al(mLatestRequestMutex);
4548
Shuzhen Wang83bff122020-11-20 15:51:39 -08004549 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004550 mLatestRequest.acquire(cloned);
4551
4552 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004553 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4554 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4555 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004556 CameraMetadata(cloned));
4557 }
4558
4559 sp<Camera3Device> parent = mParent.promote();
4560 if (parent != NULL) {
4561 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004562 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004563 0, mLatestRequest, mLatestPhysicalRequest);
4564 }
4565 }
4566
Shuzhen Wang83bff122020-11-20 15:51:39 -08004567 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004568 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004569 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004570 }
4571
Shuzhen Wang83bff122020-11-20 15:51:39 -08004572 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004573}
4574
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004575bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4576 ATRACE_CALL();
4577 bool updatesDetected = false;
4578
Emilian Peev4ec17882019-01-24 17:16:58 -08004579 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004580 for (auto tag : mSessionParamKeys) {
4581 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004582 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004583
4584 if (entry.count > 0) {
4585 bool isDifferent = false;
4586 if (lastEntry.count > 0) {
4587 // Have a last value, compare to see if changed
4588 if (lastEntry.type == entry.type &&
4589 lastEntry.count == entry.count) {
4590 // Same type and count, compare values
4591 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4592 size_t entryBytes = bytesPerValue * lastEntry.count;
4593 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4594 if (cmp != 0) {
4595 isDifferent = true;
4596 }
4597 } else {
4598 // Count or type has changed
4599 isDifferent = true;
4600 }
4601 } else {
4602 // No last entry, so always consider to be different
4603 isDifferent = true;
4604 }
4605
4606 if (isDifferent) {
4607 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004608 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4609 updatesDetected = true;
4610 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004611 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004612 }
4613 } else if (lastEntry.count > 0) {
4614 // Value has been removed
4615 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004616 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004617 updatesDetected = true;
4618 }
4619 }
4620
Emilian Peev4ec17882019-01-24 17:16:58 -08004621 bool reconfigureRequired;
4622 if (updatesDetected) {
4623 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4624 updatedParams);
4625 mLatestSessionParams = updatedParams;
4626 } else {
4627 reconfigureRequired = false;
4628 }
4629
4630 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004631}
4632
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004633bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004634 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004635 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004636 // Any function called from threadLoop() must not hold mInterfaceLock since
4637 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4638 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004639
4640 // Handle paused state.
4641 if (waitIfPaused()) {
4642 return true;
4643 }
4644
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004645 // Wait for the next batch of requests.
4646 waitForNextRequestBatch();
4647 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004648 return true;
4649 }
4650
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004651 // Get the latest request ID, if any
4652 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004653 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004654 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004655 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004656 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004657 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004658 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4659 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004660 }
4661
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004662 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4663 // or a single request from streaming or burst. In either case the first element
4664 // should contain the latest camera settings that we need to check for any session
4665 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004666 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004667 res = OK;
4668
4669 //Input stream buffers are already acquired at this point so an input stream
4670 //will not be able to move to idle state unless we force it.
4671 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4672 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4673 if (res != OK) {
4674 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4675 cleanUpFailedRequests(/*sendRequestError*/ false);
4676 return false;
4677 }
4678 }
4679
4680 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004681 sp<Camera3Device> parent = mParent.promote();
4682 if (parent != nullptr) {
4683 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004684 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004685 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004686
4687 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4688 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4689 if (res != OK) {
4690 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4691 cleanUpFailedRequests(/*sendRequestError*/ false);
4692 return false;
4693 }
4694 }
4695 }
4696 }
4697
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004698 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004699 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004700 if (res == TIMED_OUT) {
4701 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004702 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004703 // Check if any stream is abandoned.
4704 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004705 return true;
4706 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004708 return false;
4709 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004710
Zhijun Hecc27e112013-10-03 16:12:43 -07004711 // Inform waitUntilRequestProcessed thread of a new request ID
4712 {
4713 Mutex::Autolock al(mLatestRequestMutex);
4714
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004715 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004716 mLatestRequestSignal.signal();
4717 }
4718
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004719 // Submit a batch of requests to HAL.
4720 // Use flush lock only when submitting multilple requests in a batch.
4721 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4722 // which may take a long time to finish so synchronizing flush() and
4723 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4724 // For now, only synchronize for high speed recording and we should figure something out for
4725 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004726 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004727
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 if (useFlushLock) {
4729 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004730 }
4731
Zhijun Hef0645c12016-08-02 00:58:11 -07004732 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004733 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004734
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004735 sp<Camera3Device> parent = mParent.promote();
4736 if (parent != nullptr) {
4737 parent->mRequestBufferSM.onSubmittingRequest();
4738 }
4739
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004740 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004741 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004742 submitRequestSuccess = sendRequestsBatch();
4743
Shuzhen Wang686f6442017-06-20 16:16:04 -07004744 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4745 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004746
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004747 if (useFlushLock) {
4748 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004749 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004750
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004751 // Unset as current request
4752 {
4753 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004754 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004755 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004756 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004757
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004758 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004759}
4760
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004761status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004762 ATRACE_CALL();
4763
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004764 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004765 for (size_t i = 0; i < mNextRequests.size(); i++) {
4766 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004767 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004768 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4769 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770
4771 // Prepare a request to HAL
4772 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4773
4774 // Insert any queued triggers (before metadata is locked)
4775 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004776 if (res < 0) {
4777 SET_ERR("RequestThread: Unable to insert triggers "
4778 "(capture request %d, HAL device: %s (%d)",
4779 halRequest->frame_number, strerror(-res), res);
4780 return INVALID_OPERATION;
4781 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004782
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004783 int triggerCount = res;
4784 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4785 mPrevTriggers = triggerCount;
4786
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004787 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004788 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004789
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004790 // If the request is the same as last, or we had triggers now or last time or
4791 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004792 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004793 (mPrevRequest != captureRequest || triggersMixedIn ||
4794 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004795 // Request settings are all the same within one batch, so only treat the first
4796 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004797 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004798 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004799 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004800 /**
4801 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004802 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004803 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004804 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004805 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004806 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004807 "(capture request %d, HAL device: %s (%d)",
4808 halRequest->frame_number, strerror(-res), res);
4809 return INVALID_OPERATION;
4810 }
4811
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004812 {
4813 // Correct metadata regions for distortion correction if enabled
4814 sp<Camera3Device> parent = mParent.promote();
4815 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004816 List<PhysicalCameraSettings>::iterator it;
4817 for (it = captureRequest->mSettingsList.begin();
4818 it != captureRequest->mSettingsList.end(); it++) {
4819 if (parent->mDistortionMappers.find(it->cameraId) ==
4820 parent->mDistortionMappers.end()) {
4821 continue;
4822 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004823
4824 if (!captureRequest->mDistortionCorrectionUpdated) {
4825 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4826 &(it->metadata));
4827 if (res != OK) {
4828 SET_ERR("RequestThread: Unable to correct capture requests "
4829 "for lens distortion for request %d: %s (%d)",
4830 halRequest->frame_number, strerror(-res), res);
4831 return INVALID_OPERATION;
4832 }
4833 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004834 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004835 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004836
4837 for (it = captureRequest->mSettingsList.begin();
4838 it != captureRequest->mSettingsList.end(); it++) {
4839 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4840 parent->mZoomRatioMappers.end()) {
4841 continue;
4842 }
4843
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004844 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004845 cameraIdsWithZoom.insert(it->cameraId);
4846 }
4847
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004848 if (!captureRequest->mZoomRatioUpdated) {
4849 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4850 &(it->metadata));
4851 if (res != OK) {
4852 SET_ERR("RequestThread: Unable to correct capture requests "
4853 "for zoom ratio for request %d: %s (%d)",
4854 halRequest->frame_number, strerror(-res), res);
4855 return INVALID_OPERATION;
4856 }
4857 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004858 }
4859 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004860 if (captureRequest->mRotateAndCropAuto &&
4861 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004862 for (it = captureRequest->mSettingsList.begin();
4863 it != captureRequest->mSettingsList.end(); it++) {
4864 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4865 if (mapper != parent->mRotateAndCropMappers.end()) {
4866 res = mapper->second.updateCaptureRequest(&(it->metadata));
4867 if (res != OK) {
4868 SET_ERR("RequestThread: Unable to correct capture requests "
4869 "for rotate-and-crop for request %d: %s (%d)",
4870 halRequest->frame_number, strerror(-res), res);
4871 return INVALID_OPERATION;
4872 }
4873 }
4874 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004875 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004876 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004877 }
4878 }
4879
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004880 /**
4881 * The request should be presorted so accesses in HAL
4882 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4883 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004884 captureRequest->mSettingsList.begin()->metadata.sort();
4885 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004886 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004887 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004888 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4889
4890 IF_ALOGV() {
4891 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4892 find_camera_metadata_ro_entry(
4893 halRequest->settings,
4894 ANDROID_CONTROL_AF_TRIGGER,
4895 &e
4896 );
4897 if (e.count > 0) {
4898 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4899 __FUNCTION__,
4900 halRequest->frame_number,
4901 e.data.u8[0]);
4902 }
4903 }
4904 } else {
4905 // leave request.settings NULL to indicate 'reuse latest given'
4906 ALOGVV("%s: Request settings are REUSED",
4907 __FUNCTION__);
4908 }
4909
Emilian Peevaebbe412018-01-15 13:53:24 +00004910 if (captureRequest->mSettingsList.size() > 1) {
4911 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4912 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004913 if (newRequest) {
4914 halRequest->physcam_settings =
4915 new const camera_metadata* [halRequest->num_physcam_settings];
4916 } else {
4917 halRequest->physcam_settings = nullptr;
4918 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004919 auto it = ++captureRequest->mSettingsList.begin();
4920 size_t i = 0;
4921 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4922 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004923 if (newRequest) {
4924 it->metadata.sort();
4925 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4926 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004927 }
4928 }
4929
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004930 uint32_t totalNumBuffers = 0;
4931
4932 // Fill in buffers
4933 if (captureRequest->mInputStream != NULL) {
4934 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004935
4936 halRequest->input_width = captureRequest->mInputBufferSize.width;
4937 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004938 totalNumBuffers += 1;
4939 } else {
4940 halRequest->input_buffer = NULL;
4941 }
4942
Emilian Peevf4816702020-04-03 15:44:51 -07004943 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004944 captureRequest->mOutputStreams.size());
4945 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004946 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004947
4948 sp<Camera3Device> parent = mParent.promote();
4949 if (parent == NULL) {
4950 // Should not happen, and nowhere to send errors to, so just log it
4951 CLOGE("RequestThread: Parent is gone");
4952 return INVALID_OPERATION;
4953 }
4954 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4955
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004956 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004957 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004958 sp<Camera3OutputStreamInterface> outputStream =
4959 captureRequest->mOutputStreams.editItemAt(j);
4960 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004961
4962 // Prepare video buffers for high speed recording on the first video request.
4963 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4964 // Only try to prepare video stream on the first video request.
4965 mPrepareVideoStream = false;
4966
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004967 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4968 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004969 while (res == NOT_ENOUGH_DATA) {
4970 res = outputStream->prepareNextBuffer();
4971 }
4972 if (res != OK) {
4973 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4974 __FUNCTION__, strerror(-res), res);
4975 outputStream->cancelPrepare();
4976 }
4977 }
4978
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004979 std::vector<size_t> uniqueSurfaceIds;
4980 res = outputStream->getUniqueSurfaceIds(
4981 captureRequest->mOutputSurfaces[streamId],
4982 &uniqueSurfaceIds);
4983 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4984 if (res != OK && res != INVALID_OPERATION) {
4985 ALOGE("%s: failed to query stream %d unique surface IDs",
4986 __FUNCTION__, streamId);
4987 return res;
4988 }
4989 if (res == OK) {
4990 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4991 }
4992
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004993 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004994 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004995 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004996 return TIMED_OUT;
4997 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004998 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004999 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005000 buffer.stream = outputStream->asHalStream();
5001 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005002 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005003 buffer.acquire_fence = -1;
5004 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005005 // Mark the output stream as unpreparable to block clients from calling
5006 // 'prepare' after this request reaches CameraHal and before the respective
5007 // buffers are requested.
5008 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005009 } else {
5010 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5011 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005012 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005013 if (res != OK) {
5014 // Can't get output buffer from gralloc queue - this could be due to
5015 // abandoned queue or other consumer misbehavior, so not a fatal
5016 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005017 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005018 " %s (%d)", strerror(-res), res);
5019
5020 return TIMED_OUT;
5021 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005022 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005023
5024 {
5025 sp<Camera3Device> parent = mParent.promote();
5026 if (parent != nullptr) {
5027 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5028 for (const auto& settings : captureRequest->mSettingsList) {
5029 if ((streamCameraId.isEmpty() &&
5030 parent->getId() == settings.cameraId.c_str()) ||
5031 streamCameraId == settings.cameraId.c_str()) {
5032 outputStream->fireBufferRequestForFrameNumber(
5033 captureRequest->mResultExtras.frameNumber,
5034 settings.metadata);
5035 }
5036 }
5037 }
5038 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005039
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005040 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005041 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5042 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5043 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5044 } else if (!physicalCameraId.isEmpty()) {
5045 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005046 }
5047 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005048 }
5049 totalNumBuffers += halRequest->num_output_buffers;
5050
5051 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005052 // If this request list is for constrained high speed recording (not
5053 // preview), and the current request is not the last one in the batch,
5054 // do not send callback to the app.
5055 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005056 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005057 hasCallback = false;
5058 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005059 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005060 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005061 const camera_metadata_t* settings = halRequest->settings;
5062 bool shouldUnlockSettings = false;
5063 if (settings == nullptr) {
5064 shouldUnlockSettings = true;
5065 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5066 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005067 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5068 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005069 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005070 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5071 isStillCapture = true;
5072 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5073 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005074
Emilian Peevaf8416e2021-02-04 17:52:43 -08005075 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005076 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005077 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5078 isZslCapture = true;
5079 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005080 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005081 res = parent->registerInFlight(halRequest->frame_number,
5082 totalNumBuffers, captureRequest->mResultExtras,
5083 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005084 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005085 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005086 requestedPhysicalCameras, isStillCapture, isZslCapture,
5087 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005088 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005089 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005090 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5091 ", burstId = %" PRId32 ".",
5092 __FUNCTION__,
5093 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5094 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005095
5096 if (shouldUnlockSettings) {
5097 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5098 }
5099
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005100 if (res != OK) {
5101 SET_ERR("RequestThread: Unable to register new in-flight request:"
5102 " %s (%d)", strerror(-res), res);
5103 return INVALID_OPERATION;
5104 }
5105 }
5106
5107 return OK;
5108}
5109
Igor Murashkin1e479c02013-09-06 16:55:14 -07005110CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005111 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005112 Mutex::Autolock al(mLatestRequestMutex);
5113
5114 ALOGV("RequestThread::%s", __FUNCTION__);
5115
5116 return mLatestRequest;
5117}
5118
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005119bool Camera3Device::RequestThread::isStreamPending(
5120 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005121 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005122 Mutex::Autolock l(mRequestLock);
5123
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005124 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005125 if (!nextRequest.submitted) {
5126 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5127 if (stream == s) return true;
5128 }
5129 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005130 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005131 }
5132
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005133 for (const auto& request : mRequestQueue) {
5134 for (const auto& s : request->mOutputStreams) {
5135 if (stream == s) return true;
5136 }
5137 if (stream == request->mInputStream) return true;
5138 }
5139
5140 for (const auto& request : mRepeatingRequests) {
5141 for (const auto& s : request->mOutputStreams) {
5142 if (stream == s) return true;
5143 }
5144 if (stream == request->mInputStream) return true;
5145 }
5146
5147 return false;
5148}
Jianing Weicb0652e2014-03-12 18:29:36 -07005149
Emilian Peev40ead602017-09-26 15:46:36 +01005150bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5151 ATRACE_CALL();
5152 Mutex::Autolock l(mRequestLock);
5153
5154 for (const auto& nextRequest : mNextRequests) {
5155 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5156 if (s.first == streamId) {
5157 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5158 if (it != s.second.end()) {
5159 return true;
5160 }
5161 }
5162 }
5163 }
5164
5165 for (const auto& request : mRequestQueue) {
5166 for (const auto& s : request->mOutputSurfaces) {
5167 if (s.first == streamId) {
5168 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5169 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005170 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005171 }
5172 }
5173 }
5174 }
5175
5176 for (const auto& request : mRepeatingRequests) {
5177 for (const auto& s : request->mOutputSurfaces) {
5178 if (s.first == streamId) {
5179 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5180 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005181 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005182 }
5183 }
5184 }
5185 }
5186
5187 return false;
5188}
5189
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005190void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5191 if (!mUseHalBufManager) {
5192 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5193 return;
5194 }
5195
5196 Mutex::Autolock pl(mPauseLock);
5197 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005198 mInterface->signalPipelineDrain(streamIds);
5199 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005200 }
5201 // If request thread is still busy, wait until paused then notify HAL
5202 mNotifyPipelineDrain = true;
5203 mStreamIdsToBeDrained = streamIds;
5204}
5205
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005206void Camera3Device::RequestThread::resetPipelineDrain() {
5207 Mutex::Autolock pl(mPauseLock);
5208 mNotifyPipelineDrain = false;
5209 mStreamIdsToBeDrained.clear();
5210}
5211
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005212void Camera3Device::RequestThread::clearPreviousRequest() {
5213 Mutex::Autolock l(mRequestLock);
5214 mPrevRequest.clear();
5215}
5216
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005217status_t Camera3Device::RequestThread::switchToOffline(
5218 const std::vector<int32_t>& streamsToKeep,
5219 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005220 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5221 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005222 Mutex::Autolock l(mRequestLock);
5223 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5224
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005225 // Wait until request thread is fully stopped
5226 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5227
5228 // We could also check for mRepeatingRequests.empty(), but the API interface
5229 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5230 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005231 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5232 while (!queueEmpty) {
5233 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5234 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005235 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005236 return res;
5237 } else if (res != OK) {
5238 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5239 __FUNCTION__, strerror(-res), res);
5240 return res;
5241 }
5242 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5243 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005244
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005245 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005246 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005247}
5248
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005249status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5250 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5251 ATRACE_CALL();
5252 Mutex::Autolock l(mTriggerMutex);
5253 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5254 return BAD_VALUE;
5255 }
5256 mRotateAndCropOverride = rotateAndCropValue;
5257 return OK;
5258}
5259
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005260status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005261 ATRACE_CALL();
5262 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005263 if (muteMode != mCameraMute) {
5264 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005265 mCameraMuteChanged = true;
5266 }
5267 return OK;
5268}
5269
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005270nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005271 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005272 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005273 return mExpectedInflightDuration > kMinInflightDuration ?
5274 mExpectedInflightDuration : kMinInflightDuration;
5275}
5276
Emilian Peevaebbe412018-01-15 13:53:24 +00005277void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005278 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005279 if ((request == nullptr) || (halRequest == nullptr)) {
5280 ALOGE("%s: Invalid request!", __FUNCTION__);
5281 return;
5282 }
5283
5284 if (halRequest->num_physcam_settings > 0) {
5285 if (halRequest->physcam_id != nullptr) {
5286 delete [] halRequest->physcam_id;
5287 halRequest->physcam_id = nullptr;
5288 }
5289 if (halRequest->physcam_settings != nullptr) {
5290 auto it = ++(request->mSettingsList.begin());
5291 size_t i = 0;
5292 for (; it != request->mSettingsList.end(); it++, i++) {
5293 it->metadata.unlock(halRequest->physcam_settings[i]);
5294 }
5295 delete [] halRequest->physcam_settings;
5296 halRequest->physcam_settings = nullptr;
5297 }
5298 }
5299}
5300
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005301void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5302 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005303 return;
5304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005305
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005306 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005307 // Skip the ones that have been submitted successfully.
5308 if (nextRequest.submitted) {
5309 continue;
5310 }
5311
5312 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005313 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5314 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005315
5316 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005317 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005318 }
5319
Emilian Peevaebbe412018-01-15 13:53:24 +00005320 cleanupPhysicalSettings(captureRequest, halRequest);
5321
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005322 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005323 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005324 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5325 }
5326
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005327 // No output buffer can be returned when using HAL buffer manager
5328 if (!mUseHalBufManager) {
5329 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5330 //Buffers that failed processing could still have
5331 //valid acquire fence.
5332 int acquireFence = (*outputBuffers)[i].acquire_fence;
5333 if (0 <= acquireFence) {
5334 close(acquireFence);
5335 outputBuffers->editItemAt(i).acquire_fence = -1;
5336 }
Emilian Peevf4816702020-04-03 15:44:51 -07005337 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005338 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5339 /*timestampIncreasing*/true, std::vector<size_t> (),
5340 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005341 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005342 }
5343
5344 if (sendRequestError) {
5345 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005346 sp<NotificationListener> listener = mListener.promote();
5347 if (listener != NULL) {
5348 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005349 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005350 captureRequest->mResultExtras);
5351 }
5352 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005353
5354 // Remove yet-to-be submitted inflight request from inflightMap
5355 {
5356 sp<Camera3Device> parent = mParent.promote();
5357 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005358 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005359 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5360 if (idx >= 0) {
5361 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5362 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5363 parent->removeInFlightMapEntryLocked(idx);
5364 }
5365 }
5366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005367 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005368
5369 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005370 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005371}
5372
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005373void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005374 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005375 // Optimized a bit for the simple steady-state case (single repeating
5376 // request), to avoid putting that request in the queue temporarily.
5377 Mutex::Autolock l(mRequestLock);
5378
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005379 assert(mNextRequests.empty());
5380
5381 NextRequest nextRequest;
5382 nextRequest.captureRequest = waitForNextRequestLocked();
5383 if (nextRequest.captureRequest == nullptr) {
5384 return;
5385 }
5386
Emilian Peevf4816702020-04-03 15:44:51 -07005387 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005388 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005389 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005390
5391 // Wait for additional requests
5392 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5393
5394 for (size_t i = 1; i < batchSize; i++) {
5395 NextRequest additionalRequest;
5396 additionalRequest.captureRequest = waitForNextRequestLocked();
5397 if (additionalRequest.captureRequest == nullptr) {
5398 break;
5399 }
5400
Emilian Peevf4816702020-04-03 15:44:51 -07005401 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005402 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005403 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005404 }
5405
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005406 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005407 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005408 mNextRequests.size(), batchSize);
5409 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005410 }
5411
5412 return;
5413}
5414
5415sp<Camera3Device::CaptureRequest>
5416 Camera3Device::RequestThread::waitForNextRequestLocked() {
5417 status_t res;
5418 sp<CaptureRequest> nextRequest;
5419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005420 while (mRequestQueue.empty()) {
5421 if (!mRepeatingRequests.empty()) {
5422 // Always atomically enqueue all requests in a repeating request
5423 // list. Guarantees a complete in-sequence set of captures to
5424 // application.
5425 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005426 if (mFirstRepeating) {
5427 mFirstRepeating = false;
5428 } else {
5429 for (auto& request : requests) {
5430 // For repeating requests, override timestamp request using
5431 // the time a request is inserted into the request queue,
5432 // because the original repeating request will have an old
5433 // fixed timestamp.
5434 request->mRequestTimeNs = systemTime();
5435 }
5436 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005437 RequestList::const_iterator firstRequest =
5438 requests.begin();
5439 nextRequest = *firstRequest;
5440 mRequestQueue.insert(mRequestQueue.end(),
5441 ++firstRequest,
5442 requests.end());
5443 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005444
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005445 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005446
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005447 break;
5448 }
5449
5450 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5451
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005452 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5453 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005454 Mutex::Autolock pl(mPauseLock);
5455 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005456 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005457 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005458 if (mNotifyPipelineDrain) {
5459 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5460 mNotifyPipelineDrain = false;
5461 mStreamIdsToBeDrained.clear();
5462 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005463 // Let the tracker know
5464 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5465 if (statusTracker != 0) {
5466 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5467 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005468 sp<Camera3Device> parent = mParent.promote();
5469 if (parent != nullptr) {
5470 parent->mRequestBufferSM.onRequestThreadPaused();
5471 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005472 }
5473 // Stop waiting for now and let thread management happen
5474 return NULL;
5475 }
5476 }
5477
5478 if (nextRequest == NULL) {
5479 // Don't have a repeating request already in hand, so queue
5480 // must have an entry now.
5481 RequestList::iterator firstRequest =
5482 mRequestQueue.begin();
5483 nextRequest = *firstRequest;
5484 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005485 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5486 sp<NotificationListener> listener = mListener.promote();
5487 if (listener != NULL) {
5488 listener->notifyRequestQueueEmpty();
5489 }
5490 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005491 }
5492
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005493 // In case we've been unpaused by setPaused clearing mDoPause, need to
5494 // update internal pause state (capture/setRepeatingRequest unpause
5495 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005496 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005497 if (mPaused) {
5498 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5499 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5500 if (statusTracker != 0) {
5501 statusTracker->markComponentActive(mStatusId);
5502 }
5503 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005504 mPaused = false;
5505
5506 // Check if we've reconfigured since last time, and reset the preview
5507 // request if so. Can't use 'NULL request == repeat' across configure calls.
5508 if (mReconfigured) {
5509 mPrevRequest.clear();
5510 mReconfigured = false;
5511 }
5512
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005513 if (nextRequest != NULL) {
5514 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005515 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5516 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005517
5518 // Since RequestThread::clear() removes buffers from the input stream,
5519 // get the right buffer here before unlocking mRequestLock
5520 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005521 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5522 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005523 if (res != OK) {
5524 // Can't get input buffer from gralloc queue - this could be due to
5525 // disconnected queue or other producer misbehavior, so not a fatal
5526 // error
5527 ALOGE("%s: Can't get input buffer, skipping request:"
5528 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005529
5530 sp<NotificationListener> listener = mListener.promote();
5531 if (listener != NULL) {
5532 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005533 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005534 nextRequest->mResultExtras);
5535 }
5536 return NULL;
5537 }
5538 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005539 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005541 return nextRequest;
5542}
5543
5544bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005545 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005546 status_t res;
5547 Mutex::Autolock l(mPauseLock);
5548 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005549 if (mPaused == false) {
5550 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005551 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005552 if (mNotifyPipelineDrain) {
5553 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5554 mNotifyPipelineDrain = false;
5555 mStreamIdsToBeDrained.clear();
5556 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005557 // Let the tracker know
5558 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5559 if (statusTracker != 0) {
5560 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5561 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005562 sp<Camera3Device> parent = mParent.promote();
5563 if (parent != nullptr) {
5564 parent->mRequestBufferSM.onRequestThreadPaused();
5565 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005566 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005567
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005568 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005569 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005570 return true;
5571 }
5572 }
5573 // We don't set mPaused to false here, because waitForNextRequest needs
5574 // to further manage the paused state in case of starvation.
5575 return false;
5576}
5577
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005578void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005579 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005580 // With work to do, mark thread as unpaused.
5581 // If paused by request (setPaused), don't resume, to avoid
5582 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005583 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005584 Mutex::Autolock p(mPauseLock);
5585 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005586 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5587 if (mPaused) {
5588 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5589 if (statusTracker != 0) {
5590 statusTracker->markComponentActive(mStatusId);
5591 }
5592 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005593 mPaused = false;
5594 }
5595}
5596
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005597void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5598 sp<Camera3Device> parent = mParent.promote();
5599 if (parent != NULL) {
5600 va_list args;
5601 va_start(args, fmt);
5602
5603 parent->setErrorStateV(fmt, args);
5604
5605 va_end(args);
5606 }
5607}
5608
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005609status_t Camera3Device::RequestThread::insertTriggers(
5610 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005611 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005612 Mutex::Autolock al(mTriggerMutex);
5613
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005614 sp<Camera3Device> parent = mParent.promote();
5615 if (parent == NULL) {
5616 CLOGE("RequestThread: Parent is gone");
5617 return DEAD_OBJECT;
5618 }
5619
Emilian Peevaebbe412018-01-15 13:53:24 +00005620 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005621 size_t count = mTriggerMap.size();
5622
5623 for (size_t i = 0; i < count; ++i) {
5624 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005625 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005626
5627 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5628 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5629 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005630 if (isAeTrigger) {
5631 request->mResultExtras.precaptureTriggerId = triggerId;
5632 mCurrentPreCaptureTriggerId = triggerId;
5633 } else {
5634 request->mResultExtras.afTriggerId = triggerId;
5635 mCurrentAfTriggerId = triggerId;
5636 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005637 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005638 }
5639
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005640 camera_metadata_entry entry = metadata.find(tag);
5641
5642 if (entry.count > 0) {
5643 /**
5644 * Already has an entry for this trigger in the request.
5645 * Rewrite it with our requested trigger value.
5646 */
5647 RequestTrigger oldTrigger = trigger;
5648
5649 oldTrigger.entryValue = entry.data.u8[0];
5650
5651 mTriggerReplacedMap.add(tag, oldTrigger);
5652 } else {
5653 /**
5654 * More typical, no trigger entry, so we just add it
5655 */
5656 mTriggerRemovedMap.add(tag, trigger);
5657 }
5658
5659 status_t res;
5660
5661 switch (trigger.getTagType()) {
5662 case TYPE_BYTE: {
5663 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5664 res = metadata.update(tag,
5665 &entryValue,
5666 /*count*/1);
5667 break;
5668 }
5669 case TYPE_INT32:
5670 res = metadata.update(tag,
5671 &trigger.entryValue,
5672 /*count*/1);
5673 break;
5674 default:
5675 ALOGE("%s: Type not supported: 0x%x",
5676 __FUNCTION__,
5677 trigger.getTagType());
5678 return INVALID_OPERATION;
5679 }
5680
5681 if (res != OK) {
5682 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5683 ", value %d", __FUNCTION__, trigger.getTagName(),
5684 trigger.entryValue);
5685 return res;
5686 }
5687
5688 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5689 trigger.getTagName(),
5690 trigger.entryValue);
5691 }
5692
5693 mTriggerMap.clear();
5694
5695 return count;
5696}
5697
5698status_t Camera3Device::RequestThread::removeTriggers(
5699 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005700 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005701 Mutex::Autolock al(mTriggerMutex);
5702
Emilian Peevaebbe412018-01-15 13:53:24 +00005703 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005704
5705 /**
5706 * Replace all old entries with their old values.
5707 */
5708 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5709 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5710
5711 status_t res;
5712
5713 uint32_t tag = trigger.metadataTag;
5714 switch (trigger.getTagType()) {
5715 case TYPE_BYTE: {
5716 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5717 res = metadata.update(tag,
5718 &entryValue,
5719 /*count*/1);
5720 break;
5721 }
5722 case TYPE_INT32:
5723 res = metadata.update(tag,
5724 &trigger.entryValue,
5725 /*count*/1);
5726 break;
5727 default:
5728 ALOGE("%s: Type not supported: 0x%x",
5729 __FUNCTION__,
5730 trigger.getTagType());
5731 return INVALID_OPERATION;
5732 }
5733
5734 if (res != OK) {
5735 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5736 ", trigger value %d", __FUNCTION__,
5737 trigger.getTagName(), trigger.entryValue);
5738 return res;
5739 }
5740 }
5741 mTriggerReplacedMap.clear();
5742
5743 /**
5744 * Remove all new entries.
5745 */
5746 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5747 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5748 status_t res = metadata.erase(trigger.metadataTag);
5749
5750 if (res != OK) {
5751 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5752 ", trigger value %d", __FUNCTION__,
5753 trigger.getTagName(), trigger.entryValue);
5754 return res;
5755 }
5756 }
5757 mTriggerRemovedMap.clear();
5758
5759 return OK;
5760}
5761
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005762status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005763 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005764 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005765 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005766 status_t res;
5767
Emilian Peevaebbe412018-01-15 13:53:24 +00005768 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005769
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005770 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005771 // exists
5772 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5773 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5774 if (afTrigger.count > 0 &&
5775 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5776 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005777 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005778 if (res != OK) return res;
5779 }
5780
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005781 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005782 // if none already exists
5783 camera_metadata_entry pcTrigger =
5784 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5785 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5786 if (pcTrigger.count > 0 &&
5787 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5788 pcId.count == 0) {
5789 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005790 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005791 if (res != OK) return res;
5792 }
5793
5794 return OK;
5795}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005796
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005797bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5798 const sp<CaptureRequest> &request) {
5799 ATRACE_CALL();
5800
5801 if (request->mRotateAndCropAuto) {
5802 Mutex::Autolock l(mTriggerMutex);
5803 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5804
5805 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5806 if (rotateAndCropEntry.count > 0) {
5807 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5808 return false;
5809 } else {
5810 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5811 return true;
5812 }
5813 } else {
5814 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5815 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5816 &rotateAndCrop_u8, 1);
5817 return true;
5818 }
5819 }
5820 return false;
5821}
5822
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005823bool Camera3Device::RequestThread::overrideTestPattern(
5824 const sp<CaptureRequest> &request) {
5825 ATRACE_CALL();
5826
5827 Mutex::Autolock l(mTriggerMutex);
5828
5829 bool changed = false;
5830
5831 int32_t testPatternMode = request->mOriginalTestPatternMode;
5832 int32_t testPatternData[4] = {
5833 request->mOriginalTestPatternData[0],
5834 request->mOriginalTestPatternData[1],
5835 request->mOriginalTestPatternData[2],
5836 request->mOriginalTestPatternData[3]
5837 };
5838
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005839 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5840 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005841 testPatternData[0] = 0;
5842 testPatternData[1] = 0;
5843 testPatternData[2] = 0;
5844 testPatternData[3] = 0;
5845 }
5846
5847 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5848
5849 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5850 if (testPatternEntry.count > 0) {
5851 if (testPatternEntry.data.i32[0] != testPatternMode) {
5852 testPatternEntry.data.i32[0] = testPatternMode;
5853 changed = true;
5854 }
5855 } else {
5856 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5857 &testPatternMode, 1);
5858 changed = true;
5859 }
5860
5861 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
5862 if (testPatternColor.count > 0) {
5863 for (size_t i = 0; i < 4; i++) {
5864 if (testPatternColor.data.i32[i] != (int32_t)testPatternData[i]) {
5865 testPatternColor.data.i32[i] = testPatternData[i];
5866 changed = true;
5867 }
5868 }
5869 } else {
5870 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
5871 (int32_t*)testPatternData, 4);
5872 changed = true;
5873 }
5874
5875 return changed;
5876}
5877
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005878status_t Camera3Device::RequestThread::setHalInterface(
5879 sp<HalInterface> newHalInterface) {
5880 if (newHalInterface.get() == nullptr) {
5881 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5882 return DEAD_OBJECT;
5883 }
5884
5885 mInterface = newHalInterface;
5886
5887 return OK;
5888}
5889
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005890/**
5891 * PreparerThread inner class methods
5892 */
5893
5894Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005895 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005896 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005897}
5898
5899Camera3Device::PreparerThread::~PreparerThread() {
5900 Thread::requestExitAndWait();
5901 if (mCurrentStream != nullptr) {
5902 mCurrentStream->cancelPrepare();
5903 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5904 mCurrentStream.clear();
5905 }
5906 clear();
5907}
5908
Ruben Brunkc78ac262015-08-13 17:58:46 -07005909status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005910 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005911 status_t res;
5912
5913 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005914 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005915
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005916 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005917 if (res == OK) {
5918 // No preparation needed, fire listener right off
5919 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005920 if (listener != NULL) {
5921 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005922 }
5923 return OK;
5924 } else if (res != NOT_ENOUGH_DATA) {
5925 return res;
5926 }
5927
5928 // Need to prepare, start up thread if necessary
5929 if (!mActive) {
5930 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5931 // isn't running
5932 Thread::requestExitAndWait();
5933 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5934 if (res != OK) {
5935 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005936 if (listener != NULL) {
5937 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005938 }
5939 return res;
5940 }
5941 mCancelNow = false;
5942 mActive = true;
5943 ALOGV("%s: Preparer stream started", __FUNCTION__);
5944 }
5945
5946 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005947 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005948 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5949
5950 return OK;
5951}
5952
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005953void Camera3Device::PreparerThread::pause() {
5954 ATRACE_CALL();
5955
5956 Mutex::Autolock l(mLock);
5957
5958 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5959 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5960 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5961 int currentMaxCount = mCurrentMaxCount;
5962 mPendingStreams.clear();
5963 mCancelNow = true;
5964 while (mActive) {
5965 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5966 if (res == TIMED_OUT) {
5967 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5968 return;
5969 } else if (res != OK) {
5970 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5971 return;
5972 }
5973 }
5974
5975 //Check whether the prepare thread was able to complete the current
5976 //stream. In case work is still pending emplace it along with the rest
5977 //of the streams in the pending list.
5978 if (currentStream != nullptr) {
5979 if (!mCurrentPrepareComplete) {
5980 pendingStreams.emplace(currentMaxCount, currentStream);
5981 }
5982 }
5983
5984 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5985 for (const auto& it : mPendingStreams) {
5986 it.second->cancelPrepare();
5987 }
5988}
5989
5990status_t Camera3Device::PreparerThread::resume() {
5991 ATRACE_CALL();
5992 status_t res;
5993
5994 Mutex::Autolock l(mLock);
5995 sp<NotificationListener> listener = mListener.promote();
5996
5997 if (mActive) {
5998 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5999 return NO_INIT;
6000 }
6001
6002 auto it = mPendingStreams.begin();
6003 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006004 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006005 if (res == OK) {
6006 if (listener != NULL) {
6007 listener->notifyPrepared(it->second->getId());
6008 }
6009 it = mPendingStreams.erase(it);
6010 } else if (res != NOT_ENOUGH_DATA) {
6011 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6012 res, strerror(-res));
6013 it = mPendingStreams.erase(it);
6014 } else {
6015 it++;
6016 }
6017 }
6018
6019 if (mPendingStreams.empty()) {
6020 return OK;
6021 }
6022
6023 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6024 if (res != OK) {
6025 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6026 __FUNCTION__, res, strerror(-res));
6027 return res;
6028 }
6029 mCancelNow = false;
6030 mActive = true;
6031 ALOGV("%s: Preparer stream started", __FUNCTION__);
6032
6033 return OK;
6034}
6035
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006036status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006037 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006038 Mutex::Autolock l(mLock);
6039
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006040 for (const auto& it : mPendingStreams) {
6041 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006042 }
6043 mPendingStreams.clear();
6044 mCancelNow = true;
6045
6046 return OK;
6047}
6048
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006049void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006050 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006051 Mutex::Autolock l(mLock);
6052 mListener = listener;
6053}
6054
6055bool Camera3Device::PreparerThread::threadLoop() {
6056 status_t res;
6057 {
6058 Mutex::Autolock l(mLock);
6059 if (mCurrentStream == nullptr) {
6060 // End thread if done with work
6061 if (mPendingStreams.empty()) {
6062 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6063 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6064 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6065 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006066 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006067 return false;
6068 }
6069
6070 // Get next stream to prepare
6071 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006072 mCurrentStream = it->second;
6073 mCurrentMaxCount = it->first;
6074 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006075 mPendingStreams.erase(it);
6076 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6077 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6078 } else if (mCancelNow) {
6079 mCurrentStream->cancelPrepare();
6080 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6081 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6082 mCurrentStream.clear();
6083 mCancelNow = false;
6084 return true;
6085 }
6086 }
6087
6088 res = mCurrentStream->prepareNextBuffer();
6089 if (res == NOT_ENOUGH_DATA) return true;
6090 if (res != OK) {
6091 // Something bad happened; try to recover by cancelling prepare and
6092 // signalling listener anyway
6093 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6094 mCurrentStream->getId(), res, strerror(-res));
6095 mCurrentStream->cancelPrepare();
6096 }
6097
6098 // This stream has finished, notify listener
6099 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006100 sp<NotificationListener> listener = mListener.promote();
6101 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006102 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6103 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006104 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006105 }
6106
6107 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6108 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006109 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006110
6111 return true;
6112}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006113
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006114status_t Camera3Device::RequestBufferStateMachine::initialize(
6115 sp<camera3::StatusTracker> statusTracker) {
6116 if (statusTracker == nullptr) {
6117 ALOGE("%s: statusTracker is null", __FUNCTION__);
6118 return BAD_VALUE;
6119 }
6120
6121 std::lock_guard<std::mutex> lock(mLock);
6122 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006123 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006124 return OK;
6125}
6126
6127bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6128 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006129 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006130 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006131 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006132 return true;
6133 }
6134 return false;
6135}
6136
6137void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6138 std::lock_guard<std::mutex> lock(mLock);
6139 if (!mRequestBufferOngoing) {
6140 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6141 return;
6142 }
6143 mRequestBufferOngoing = false;
6144 if (mStatus == RB_STATUS_PENDING_STOP) {
6145 checkSwitchToStopLocked();
6146 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006147 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006148}
6149
6150void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6151 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006152 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006153 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006154 return;
6155}
6156
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006157void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006158 std::lock_guard<std::mutex> lock(mLock);
6159 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006160 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6161 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006162 mInflightMapEmpty = false;
6163 if (mStatus == RB_STATUS_STOPPED) {
6164 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006165 }
6166 return;
6167}
6168
6169void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6170 std::lock_guard<std::mutex> lock(mLock);
6171 mRequestThreadPaused = true;
6172 if (mStatus == RB_STATUS_PENDING_STOP) {
6173 checkSwitchToStopLocked();
6174 }
6175 return;
6176}
6177
6178void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6179 std::lock_guard<std::mutex> lock(mLock);
6180 mInflightMapEmpty = true;
6181 if (mStatus == RB_STATUS_PENDING_STOP) {
6182 checkSwitchToStopLocked();
6183 }
6184 return;
6185}
6186
6187void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6188 std::lock_guard<std::mutex> lock(mLock);
6189 if (!checkSwitchToStopLocked()) {
6190 mStatus = RB_STATUS_PENDING_STOP;
6191 }
6192 return;
6193}
6194
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006195bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6196 std::lock_guard<std::mutex> lock(mLock);
6197 if (mRequestBufferOngoing) {
6198 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6199 __FUNCTION__);
6200 return false;
6201 }
6202 mSwitchedToOffline = true;
6203 mInflightMapEmpty = true;
6204 mRequestThreadPaused = true;
6205 mStatus = RB_STATUS_STOPPED;
6206 return true;
6207}
6208
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006209void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6210 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6211 if (statusTracker != nullptr) {
6212 if (active) {
6213 statusTracker->markComponentActive(mRequestBufferStatusId);
6214 } else {
6215 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6216 }
6217 }
6218}
6219
6220bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6221 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6222 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006223 return true;
6224 }
6225 return false;
6226}
6227
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006228bool Camera3Device::startRequestBuffer() {
6229 return mRequestBufferSM.startRequestBuffer();
6230}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006231
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006232void Camera3Device::endRequestBuffer() {
6233 mRequestBufferSM.endRequestBuffer();
6234}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006235
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006236nsecs_t Camera3Device::getWaitDuration() {
6237 return kBaseGetBufferWait + getExpectedInFlightDuration();
6238}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006239
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006240void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6241 mInterface->getInflightBufferKeys(out);
6242}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006244void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6245 mInterface->getInflightRequestBufferKeys(out);
6246}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006247
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006248std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6249 std::vector<sp<Camera3StreamInterface>> ret;
6250 bool hasInputStream = mInputStream != nullptr;
6251 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6252 if (hasInputStream) {
6253 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006254 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006255 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6256 ret.push_back(mOutputStreams[i]);
6257 }
6258 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6259 ret.push_back(mDeletedStreams[i]);
6260 }
6261 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006262}
6263
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006264status_t Camera3Device::switchToOffline(
6265 const std::vector<int32_t>& streamsToKeep,
6266 /*out*/ sp<CameraOfflineSessionBase>* session) {
6267 ATRACE_CALL();
6268 if (session == nullptr) {
6269 ALOGE("%s: session must not be null", __FUNCTION__);
6270 return BAD_VALUE;
6271 }
6272
6273 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006274
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006275 bool hasInputStream = mInputStream != nullptr;
6276 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6277 bool inputStreamSupportsOffline = hasInputStream ?
6278 mInputStream->getOfflineProcessingSupport() : false;
6279 auto outputStreamIds = mOutputStreams.getStreamIds();
6280 auto streamIds = outputStreamIds;
6281 if (hasInputStream) {
6282 streamIds.push_back(mInputStream->getId());
6283 }
6284
6285 // Check all streams in streamsToKeep supports offline mode
6286 for (auto id : streamsToKeep) {
6287 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6288 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6289 return BAD_VALUE;
6290 } else if (id == inputStreamId) {
6291 if (!inputStreamSupportsOffline) {
6292 ALOGE("%s: input stream %d cannot be switched to offline",
6293 __FUNCTION__, id);
6294 return BAD_VALUE;
6295 }
6296 } else {
6297 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6298 if (!stream->getOfflineProcessingSupport()) {
6299 ALOGE("%s: output stream %d cannot be switched to offline",
6300 __FUNCTION__, id);
6301 return BAD_VALUE;
6302 }
6303 }
6304 }
6305
6306 // TODO: block surface sharing and surface group streams until we can support them
6307
6308 // Stop repeating request, wait until all remaining requests are submitted, then call into
6309 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006310 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6311 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006312 camera3::BufferRecords bufferRecords;
6313 status_t ret = mRequestThread->switchToOffline(
6314 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006315
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006316 if (ret != OK) {
6317 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6318 return ret;
6319 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006320
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006321 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6322 if (!succ) {
6323 SET_ERR("HAL must not be calling requestStreamBuffers call");
6324 // TODO: block ALL callbacks from HAL till app configured new streams?
6325 return UNKNOWN_ERROR;
6326 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006327
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006328 // Verify offlineSessionInfo
6329 std::vector<int32_t> offlineStreamIds;
6330 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6331 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6332 // verify stream IDs
6333 int32_t id = offlineStream.id;
6334 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6335 SET_ERR("stream ID %d not found!", id);
6336 return UNKNOWN_ERROR;
6337 }
6338
6339 // When not using HAL buf manager, only allow streams requested by app to be preserved
6340 if (!mUseHalBufManager) {
6341 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6342 SET_ERR("stream ID %d must not be switched to offline!", id);
6343 return UNKNOWN_ERROR;
6344 }
6345 }
6346
6347 offlineStreamIds.push_back(id);
6348 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6349 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6350 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6351 // Verify number of outstanding buffers
6352 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6353 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6354 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6355 return UNKNOWN_ERROR;
6356 }
6357 }
6358
6359 // Verify all streams to be deleted don't have any outstanding buffers
6360 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6361 inputStreamId) == offlineStreamIds.end()) {
6362 if (mInputStream->hasOutstandingBuffers()) {
6363 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6364 inputStreamId, mInputStream->getOutstandingBuffersCount());
6365 return UNKNOWN_ERROR;
6366 }
6367 }
6368
6369 for (const auto& outStreamId : outputStreamIds) {
6370 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6371 outStreamId) == offlineStreamIds.end()) {
6372 auto outStream = mOutputStreams.get(outStreamId);
6373 if (outStream->hasOutstandingBuffers()) {
6374 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6375 outStreamId, outStream->getOutstandingBuffersCount());
6376 return UNKNOWN_ERROR;
6377 }
6378 }
6379 }
6380
6381 InFlightRequestMap offlineReqs;
6382 // Verify inflight requests and their pending buffers
6383 {
6384 std::lock_guard<std::mutex> l(mInFlightLock);
6385 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6386 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6387 if (idx == NAME_NOT_FOUND) {
6388 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6389 return UNKNOWN_ERROR;
6390 }
6391
6392 const auto& inflightReq = mInFlightMap.valueAt(idx);
6393 // TODO: check specific stream IDs
6394 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6395 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6396 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6397 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6398 return UNKNOWN_ERROR;
6399 }
6400 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6401 }
6402 }
6403
6404 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006405 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006406 camera3::StreamSet offlineStreamSet;
6407 sp<camera3::Camera3Stream> inputStream;
6408 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6409 int32_t id = offlineStream.id;
6410 if (mInputStream != nullptr && id == mInputStream->getId()) {
6411 inputStream = mInputStream;
6412 } else {
6413 offlineStreamSet.add(id, mOutputStreams.get(id));
6414 }
6415 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006416
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006417 // TODO: check if we need to lock before copying states
6418 // though technically no other thread should be talking to Camera3Device at this point
6419 Camera3OfflineStates offlineStates(
6420 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006421 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6422 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6423 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6424 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6425 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6426 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6427 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006428
6429 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6430 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6431
6432 // Delete all streams that has been transferred to offline session
6433 Mutex::Autolock l(mLock);
6434 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6435 int32_t id = offlineStream.id;
6436 if (mInputStream != nullptr && id == mInputStream->getId()) {
6437 mInputStream.clear();
6438 } else {
6439 mOutputStreams.remove(id);
6440 }
6441 }
6442
6443 // disconnect all other streams and switch to UNCONFIGURED state
6444 if (mInputStream != nullptr) {
6445 ret = mInputStream->disconnect();
6446 if (ret != OK) {
6447 SET_ERR_L("disconnect input stream failed!");
6448 return UNKNOWN_ERROR;
6449 }
6450 }
6451
6452 for (auto streamId : mOutputStreams.getStreamIds()) {
6453 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6454 ret = stream->disconnect();
6455 if (ret != OK) {
6456 SET_ERR_L("disconnect output stream %d failed!", streamId);
6457 return UNKNOWN_ERROR;
6458 }
6459 }
6460
6461 mInputStream.clear();
6462 mOutputStreams.clear();
6463 mNeedConfig = true;
6464 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6465 mOperatingMode = NO_MODE;
6466 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006467 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006468
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006469 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006470 // TO be done by CameraDeviceClient/Camera3OfflineSession
6471 // register the offline client to camera service
6472 // Setup result passthing threads etc
6473 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6474 // TODO: check how many onIdle callback will be sent
6475 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006476}
6477
Emilian Peevcc0b7952020-01-07 13:54:47 -08006478void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6479 ATRACE_CALL();
6480
6481 if (offlineStreamIds == nullptr) {
6482 return;
6483 }
6484
6485 Mutex::Autolock il(mInterfaceLock);
6486
6487 auto streamIds = mOutputStreams.getStreamIds();
6488 bool hasInputStream = mInputStream != nullptr;
6489 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6490 offlineStreamIds->push_back(mInputStream->getId());
6491 }
6492
6493 for (const auto & streamId : streamIds) {
6494 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6495 // Streams that use the camera buffer manager are currently not supported in
6496 // offline mode
6497 if (stream->getOfflineProcessingSupport() &&
6498 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6499 offlineStreamIds->push_back(streamId);
6500 }
6501 }
6502}
6503
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006504status_t Camera3Device::setRotateAndCropAutoBehavior(
6505 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6506 ATRACE_CALL();
6507 Mutex::Autolock il(mInterfaceLock);
6508 Mutex::Autolock l(mLock);
6509 if (mRequestThread == nullptr) {
6510 return INVALID_OPERATION;
6511 }
6512 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6513}
6514
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006515bool Camera3Device::supportsCameraMute() {
6516 Mutex::Autolock il(mInterfaceLock);
6517 Mutex::Autolock l(mLock);
6518
6519 return mSupportCameraMute;
6520}
6521
6522status_t Camera3Device::setCameraMute(bool enabled) {
6523 ATRACE_CALL();
6524 Mutex::Autolock il(mInterfaceLock);
6525 Mutex::Autolock l(mLock);
6526
6527 if (mRequestThread == nullptr || !mSupportCameraMute) {
6528 return INVALID_OPERATION;
6529 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006530 int32_t muteMode =
6531 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6532 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6533 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6534 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006535}
6536
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006537status_t Camera3Device::injectCamera(const String8& injectedCamId,
6538 sp<CameraProviderManager> manager) {
6539 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6540 ATRACE_CALL();
6541 Mutex::Autolock il(mInterfaceLock);
6542
6543 status_t res = NO_ERROR;
6544 if (mInjectionMethods->isInjecting()) {
6545 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6546 return OK;
6547 } else {
6548 res = mInjectionMethods->stopInjection();
6549 if (res != OK) {
6550 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6551 __FUNCTION__, res);
6552 return res;
6553 }
6554 }
6555 }
6556
6557 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6558 if (res != OK) {
6559 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6560 __FUNCTION__, res);
6561 return res;
6562 }
6563
6564 camera3::camera_stream_configuration injectionConfig;
6565 std::vector<uint32_t> injectionBufferSizes;
6566 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6567 // When the second display of android is cast to the remote device, and the opened camera is
6568 // also cast to the second display, in this case, because the camera has configured the streams
6569 // at this time, we can directly call injectCamera() to replace the internal camera with
6570 // injection camera.
6571 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6572 && injectionBufferSizes.size() > 0) {
6573 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6574 res = mInjectionMethods->injectCamera(
6575 injectionConfig, injectionBufferSizes);
6576 if (res != OK) {
6577 ALOGE("Can't finish inject camera process!");
6578 return res;
6579 }
6580 }
6581
6582 return OK;
6583}
6584
6585status_t Camera3Device::stopInjection() {
6586 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6587 Mutex::Autolock il(mInterfaceLock);
6588 return mInjectionMethods->stopInjection();
6589}
6590
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006591}; // namespace android