blob: b0ccec41d2a9550fe8f301fef8b4ca10cc31adc7 [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");
Emilian Peeva6138c52021-06-24 12:52:38 -0700766 if (mInFlightLock.try_lock()) {
767 if (mInFlightMap.size() == 0) {
768 lines.append(" None\n");
769 } else {
770 for (size_t i = 0; i < mInFlightMap.size(); i++) {
771 InFlightRequest r = mInFlightMap.valueAt(i);
772 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
773 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
774 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
775 r.numBuffersLeft);
776 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700777 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700778 mInFlightLock.unlock();
779 } else {
780 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700781 }
782 write(fd, lines.string(), lines.size());
783
Shuzhen Wang686f6442017-06-20 16:16:04 -0700784 if (mRequestThread != NULL) {
785 mRequestThread->dumpCaptureRequestLatency(fd,
786 " ProcessCaptureRequest latency histogram:");
787 }
788
Igor Murashkin1e479c02013-09-06 16:55:14 -0700789 {
790 lines = String8(" Last request sent:\n");
791 write(fd, lines.string(), lines.size());
792
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700793 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700794 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
795 }
796
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800797 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700798 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800799 "TEMPLATE_PREVIEW",
800 "TEMPLATE_STILL_CAPTURE",
801 "TEMPLATE_VIDEO_RECORD",
802 "TEMPLATE_VIDEO_SNAPSHOT",
803 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800804 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800805 };
806
Emilian Peevf4816702020-04-03 15:44:51 -0700807 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800808 camera_metadata_t *templateRequest = nullptr;
809 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700810 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800811 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800812 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800813 lines.append(" Not supported\n");
814 write(fd, lines.string(), lines.size());
815 } else {
816 write(fd, lines.string(), lines.size());
817 dump_indented_camera_metadata(templateRequest,
818 fd, /*verbosity*/2, /*indentation*/8);
819 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800820 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800821 }
822 }
823
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700824 mTagMonitor.dumpMonitoredMetadata(fd);
825
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800826 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800827 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800828 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800829 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800830 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700832 if (gotLock) mLock.unlock();
833 if (gotInterfaceLock) mInterfaceLock.unlock();
834
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800835 return OK;
836}
837
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800838const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800839 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800840 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
841 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700842 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800843 mStatus == STATUS_ERROR ?
844 "when in error state" : "before init");
845 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700846 if (physicalId.isEmpty()) {
847 return mDeviceInfo;
848 } else {
849 std::string id(physicalId.c_str());
850 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
851 return mPhysicalDeviceInfoMap.at(id);
852 } else {
853 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
854 return mDeviceInfo;
855 }
856 }
857}
858
859const CameraMetadata& Camera3Device::info() const {
860 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800861 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800862}
863
Jianing Wei90e59c92014-03-12 18:29:36 -0700864status_t Camera3Device::checkStatusOkToCaptureLocked() {
865 switch (mStatus) {
866 case STATUS_ERROR:
867 CLOGE("Device has encountered a serious error");
868 return INVALID_OPERATION;
869 case STATUS_UNINITIALIZED:
870 CLOGE("Device not initialized");
871 return INVALID_OPERATION;
872 case STATUS_UNCONFIGURED:
873 case STATUS_CONFIGURED:
874 case STATUS_ACTIVE:
875 // OK
876 break;
877 default:
878 SET_ERR_L("Unexpected status: %d", mStatus);
879 return INVALID_OPERATION;
880 }
881 return OK;
882}
883
884status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000885 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700886 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700887 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700888 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700889 if (requestList == NULL) {
890 CLOGE("requestList cannot be NULL.");
891 return BAD_VALUE;
892 }
893
Jianing Weicb0652e2014-03-12 18:29:36 -0700894 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000895 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
897 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
898 ++metadataIt, ++surfaceMapIt) {
899 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700900 if (newRequest == 0) {
901 CLOGE("Can't create capture request");
902 return BAD_VALUE;
903 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700904
Shuzhen Wang9d066012016-09-30 11:30:20 -0700905 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700906 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700907
Jianing Weicb0652e2014-03-12 18:29:36 -0700908 // Setup burst Id and request Id
909 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800910 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
911 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700912 CLOGE("RequestID does not exist in metadata");
913 return BAD_VALUE;
914 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800915 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700916
Jianing Wei90e59c92014-03-12 18:29:36 -0700917 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700918
919 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700920 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700921 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
922 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
923 return BAD_VALUE;
924 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700925
926 // Setup batch size if this is a high speed video recording request.
927 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
928 auto firstRequest = requestList->begin();
929 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
930 if (outputStream->isVideoStream()) {
931 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800932 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700933 break;
934 }
935 }
936 }
937
Jianing Wei90e59c92014-03-12 18:29:36 -0700938 return OK;
939}
940
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800941status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800942 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800943
Emilian Peevaebbe412018-01-15 13:53:24 +0000944 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700945 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000946 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700947
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800948 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700949}
950
Emilian Peevaebbe412018-01-15 13:53:24 +0000951void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700952 std::list<const SurfaceMap>& surfaceMaps,
953 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000954 PhysicalCameraSettingsList requestList;
955 requestList.push_back({std::string(getId().string()), request});
956 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700957
958 SurfaceMap surfaceMap;
959 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
960 // With no surface list passed in, stream and surface will have 1-to-1
961 // mapping. So the surface index is 0 for each stream in the surfaceMap.
962 for (size_t i = 0; i < streams.count; i++) {
963 surfaceMap[streams.data.i32[i]].push_back(0);
964 }
965 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800966}
967
Jianing Wei90e59c92014-03-12 18:29:36 -0700968status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000969 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700970 const std::list<const SurfaceMap> &surfaceMaps,
971 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700972 /*out*/
973 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700974 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700975 nsecs_t requestTimeNs = systemTime();
976
Jianing Wei90e59c92014-03-12 18:29:36 -0700977 Mutex::Autolock il(mInterfaceLock);
978 Mutex::Autolock l(mLock);
979
980 status_t res = checkStatusOkToCaptureLocked();
981 if (res != OK) {
982 // error logged by previous call
983 return res;
984 }
985
986 RequestList requestList;
987
Shuzhen Wang0129d522016-10-30 22:43:41 -0700988 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700989 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700990 if (res != OK) {
991 // error logged by previous call
992 return res;
993 }
994
995 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700996 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700997 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700998 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700999 }
1000
1001 if (res == OK) {
1002 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
1003 if (res != OK) {
1004 SET_ERR_L("Can't transition to active in %f seconds!",
1005 kActiveTimeout/1e9);
1006 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001007 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001008 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001009 } else {
1010 CLOGE("Cannot queue request. Impossible.");
1011 return BAD_VALUE;
1012 }
1013
1014 return res;
1015}
1016
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001017hardware::Return<void> Camera3Device::requestStreamBuffers(
1018 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1019 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001020 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001021 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001022 *this, *mInterface, *this};
1023 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001024 return hardware::Void();
1025}
1026
1027hardware::Return<void> Camera3Device::returnStreamBuffers(
1028 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001029 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001030 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001032 return hardware::Void();
1033}
1034
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001035hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001036 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001037 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001038 // Ideally we should grab mLock, but that can lead to deadlock, and
1039 // it's not super important to get up to date value of mStatus for this
1040 // warning print, hence skipping the lock here
1041 if (mStatus == STATUS_ERROR) {
1042 // Per API contract, HAL should act as closed after device error
1043 // But mStatus can be set to error by framework as well, so just log
1044 // a warning here.
1045 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001046 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001047
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001048 sp<NotificationListener> listener;
1049 {
1050 std::lock_guard<std::mutex> l(mOutputLock);
1051 listener = mListener.promote();
1052 }
1053
Yifan Honga640c5a2017-04-12 16:30:31 -07001054 if (mProcessCaptureResultLock.tryLock() != OK) {
1055 // This should never happen; it indicates a wrong client implementation
1056 // that doesn't follow the contract. But, we can be tolerant here.
1057 ALOGE("%s: callback overlapped! waiting 1s...",
1058 __FUNCTION__);
1059 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1060 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1061 __FUNCTION__);
1062 // really don't know what to do, so bail out.
1063 return hardware::Void();
1064 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001065 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 CaptureOutputStates states {
1067 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001068 mInFlightLock, mLastCompletedRegularFrameNumber,
1069 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1070 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001071 mNextShutterFrameNumber,
1072 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1073 mNextResultFrameNumber,
1074 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1075 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1076 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001077 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001078 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1079 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001080 };
1081
Yifan Honga640c5a2017-04-12 16:30:31 -07001082 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001083 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001084 }
1085 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001086 return hardware::Void();
1087}
1088
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001089// Only one processCaptureResult should be called at a time, so
1090// the locks won't block. The locks are present here simply to enforce this.
1091hardware::Return<void> Camera3Device::processCaptureResult(
1092 const hardware::hidl_vec<
1093 hardware::camera::device::V3_2::CaptureResult>& results) {
1094 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1095
1096 // Ideally we should grab mLock, but that can lead to deadlock, and
1097 // it's not super important to get up to date value of mStatus for this
1098 // warning print, hence skipping the lock here
1099 if (mStatus == STATUS_ERROR) {
1100 // Per API contract, HAL should act as closed after device error
1101 // But mStatus can be set to error by framework as well, so just log
1102 // a warning here.
1103 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1104 }
1105
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001106 sp<NotificationListener> listener;
1107 {
1108 std::lock_guard<std::mutex> l(mOutputLock);
1109 listener = mListener.promote();
1110 }
1111
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001112 if (mProcessCaptureResultLock.tryLock() != OK) {
1113 // This should never happen; it indicates a wrong client implementation
1114 // that doesn't follow the contract. But, we can be tolerant here.
1115 ALOGE("%s: callback overlapped! waiting 1s...",
1116 __FUNCTION__);
1117 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1118 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1119 __FUNCTION__);
1120 // really don't know what to do, so bail out.
1121 return hardware::Void();
1122 }
1123 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001124
1125 CaptureOutputStates states {
1126 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001127 mInFlightLock, mLastCompletedRegularFrameNumber,
1128 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1129 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001130 mNextShutterFrameNumber,
1131 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1132 mNextResultFrameNumber,
1133 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1134 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1135 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001136 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001137 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1138 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001139 };
1140
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001141 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001142 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001143 }
1144 mProcessCaptureResultLock.unlock();
1145 return hardware::Void();
1146}
1147
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001148hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001149 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001150 // Ideally we should grab mLock, but that can lead to deadlock, and
1151 // it's not super important to get up to date value of mStatus for this
1152 // warning print, hence skipping the lock here
1153 if (mStatus == STATUS_ERROR) {
1154 // Per API contract, HAL should act as closed after device error
1155 // But mStatus can be set to error by framework as well, so just log
1156 // a warning here.
1157 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001158 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001159
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001160 sp<NotificationListener> listener;
1161 {
1162 std::lock_guard<std::mutex> l(mOutputLock);
1163 listener = mListener.promote();
1164 }
1165
1166 CaptureOutputStates states {
1167 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001168 mInFlightLock, mLastCompletedRegularFrameNumber,
1169 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1170 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001171 mNextShutterFrameNumber,
1172 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1173 mNextResultFrameNumber,
1174 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1175 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1176 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001177 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001178 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1179 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001180 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001181 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001182 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001183 }
1184 return hardware::Void();
1185}
1186
Emilian Peevaebbe412018-01-15 13:53:24 +00001187status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001188 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001189 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001190 ATRACE_CALL();
1191
Emilian Peevaebbe412018-01-15 13:53:24 +00001192 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001193}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001194
Jianing Weicb0652e2014-03-12 18:29:36 -07001195status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1196 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001197 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001198
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001200 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001201 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001202
Emilian Peevaebbe412018-01-15 13:53:24 +00001203 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001204 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205}
1206
Emilian Peevaebbe412018-01-15 13:53:24 +00001207status_t Camera3Device::setStreamingRequestList(
1208 const List<const PhysicalCameraSettingsList> &requestsList,
1209 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001210 ATRACE_CALL();
1211
Emilian Peevaebbe412018-01-15 13:53:24 +00001212 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001213}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214
1215sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001216 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 status_t res;
1218
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001219 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001220 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1221 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001222 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001223 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001224 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001226 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001228 } else if (mStatus == STATUS_UNCONFIGURED) {
1229 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001230 CLOGE("No streams configured");
1231 return NULL;
1232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 }
1234
Shuzhen Wang0129d522016-10-30 22:43:41 -07001235 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237}
1238
Jianing Weicb0652e2014-03-12 18:29:36 -07001239status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001241 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001243
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 switch (mStatus) {
1245 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001246 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return INVALID_OPERATION;
1248 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001249 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 case STATUS_UNCONFIGURED:
1252 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 case STATUS_ACTIVE:
1254 // OK
1255 break;
1256 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001260 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001261
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001262 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263}
1264
1265status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1266 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001268
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001269 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001270}
1271
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001272status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001273 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001274 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001276 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001277 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001278 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1279 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001280
1281 status_t res;
1282 bool wasActive = false;
1283
1284 switch (mStatus) {
1285 case STATUS_ERROR:
1286 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1287 return INVALID_OPERATION;
1288 case STATUS_UNINITIALIZED:
1289 ALOGE("%s: Device not initialized", __FUNCTION__);
1290 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 case STATUS_UNCONFIGURED:
1292 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293 // OK
1294 break;
1295 case STATUS_ACTIVE:
1296 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001297 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001298 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300 return res;
1301 }
1302 wasActive = true;
1303 break;
1304 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001305 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 return INVALID_OPERATION;
1307 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001308 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309
1310 if (mInputStream != 0) {
1311 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1312 return INVALID_OPERATION;
1313 }
1314
1315 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1316 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001318
1319 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -08001320 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321
1322 *id = mNextStreamId++;
1323
1324 // Continue captures if active at start
1325 if (wasActive) {
1326 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001327 // Reuse current operating mode and session parameters for new stream config
1328 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001329 if (res != OK) {
1330 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1331 __FUNCTION__, mNextStreamId, strerror(-res), res);
1332 return res;
1333 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001334 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001335 }
1336
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001337 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001338 return OK;
1339}
1340
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001341status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001342 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001343 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001344 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001345 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1346 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1347 uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001348 ATRACE_CALL();
1349
1350 if (consumer == nullptr) {
1351 ALOGE("%s: consumer must not be null", __FUNCTION__);
1352 return BAD_VALUE;
1353 }
1354
1355 std::vector<sp<Surface>> consumers;
1356 consumers.push_back(consumer);
1357
1358 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001359 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
1360 streamSetId, isShared, isMultiResolution, consumerUsage);
1361}
1362
1363static bool isRawFormat(int format) {
1364 switch (format) {
1365 case HAL_PIXEL_FORMAT_RAW16:
1366 case HAL_PIXEL_FORMAT_RAW12:
1367 case HAL_PIXEL_FORMAT_RAW10:
1368 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1369 return true;
1370 default:
1371 return false;
1372 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001373}
1374
1375status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1376 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001377 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001378 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001379 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
1380 uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001381 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001382
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001383 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001384 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001385 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001386 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001387 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1388 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1389 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 status_t res;
1392 bool wasActive = false;
1393
1394 switch (mStatus) {
1395 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001396 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001397 return INVALID_OPERATION;
1398 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001399 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001401 case STATUS_UNCONFIGURED:
1402 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001403 // OK
1404 break;
1405 case STATUS_ACTIVE:
1406 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001407 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001409 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410 return res;
1411 }
1412 wasActive = true;
1413 break;
1414 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001415 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001416 return INVALID_OPERATION;
1417 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001418 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001419
1420 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001421
Shuzhen Wang0129d522016-10-30 22:43:41 -07001422 if (consumers.size() == 0 && !hasDeferredConsumer) {
1423 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1424 return BAD_VALUE;
1425 }
Zhijun He5d677d12016-05-29 16:52:39 -07001426
Shuzhen Wang0129d522016-10-30 22:43:41 -07001427 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001428 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1429 return BAD_VALUE;
1430 }
1431
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001432 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1433 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1434 // be found in only one sensor pixel mode.
1435 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1436 return BAD_VALUE;
1437 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001439 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001440 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001441 blobBufferSize = getPointCloudBufferSize();
1442 if (blobBufferSize <= 0) {
1443 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1444 return BAD_VALUE;
1445 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001446 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1447 blobBufferSize = width * height;
1448 } else {
1449 blobBufferSize = getJpegBufferSize(width, height);
1450 if (blobBufferSize <= 0) {
1451 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1452 return BAD_VALUE;
1453 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001454 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001455 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001456 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001457 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1458 isMultiResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001459 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001460 bool maxResolution =
1461 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1462 sensorPixelModesUsed.end();
1463 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001464 if (rawOpaqueBufferSize <= 0) {
1465 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1466 return BAD_VALUE;
1467 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001468 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001469 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001470 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1471 isMultiResolution);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001472 } else if (isShared) {
1473 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1474 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001475 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1476 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001477 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001478 newStream = new Camera3OutputStream(mNextStreamId,
1479 width, height, format, consumerUsage, 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 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001483 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001484 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001485 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
1486 isMultiResolution);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 }
Emilian Peev40ead602017-09-26 15:46:36 +01001488
1489 size_t consumerCount = consumers.size();
1490 for (size_t i = 0; i < consumerCount; i++) {
1491 int id = newStream->getSurfaceId(consumers[i]);
1492 if (id < 0) {
1493 SET_ERR_L("Invalid surface id");
1494 return BAD_VALUE;
1495 }
1496 if (surfaceIds != nullptr) {
1497 surfaceIds->push_back(id);
1498 }
1499 }
1500
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502
Emilian Peev08dd2452017-04-06 16:55:14 +01001503 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001504
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001505 newStream->setImageDumpMask(mImageDumpMask);
1506
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 res = mOutputStreams.add(mNextStreamId, newStream);
1508 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return res;
1511 }
1512
Shuzhen Wang316781a2020-08-18 18:11:01 -07001513 mSessionStatsBuilder.addStream(mNextStreamId);
1514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001516 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517
1518 // Continue captures if active at start
1519 if (wasActive) {
1520 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001521 // Reuse current operating mode and session parameters for new stream config
1522 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001524 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1525 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return res;
1527 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001530 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001532}
1533
Emilian Peev710c1422017-08-30 11:19:38 +01001534status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001536 if (nullptr == streamInfo) {
1537 return BAD_VALUE;
1538 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 switch (mStatus) {
1543 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001544 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return INVALID_OPERATION;
1546 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001547 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 case STATUS_UNCONFIGURED:
1550 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 case STATUS_ACTIVE:
1552 // OK
1553 break;
1554 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 }
1558
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001559 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1560 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001561 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001562 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 }
1564
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001565 streamInfo->width = stream->getWidth();
1566 streamInfo->height = stream->getHeight();
1567 streamInfo->format = stream->getFormat();
1568 streamInfo->dataSpace = stream->getDataSpace();
1569 streamInfo->formatOverridden = stream->isFormatOverridden();
1570 streamInfo->originalFormat = stream->getOriginalFormat();
1571 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1572 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001574}
1575
1576status_t Camera3Device::setStreamTransform(int id,
1577 int transform) {
1578 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001581
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001582 switch (mStatus) {
1583 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001584 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 return INVALID_OPERATION;
1586 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001587 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 case STATUS_UNCONFIGURED:
1590 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 case STATUS_ACTIVE:
1592 // OK
1593 break;
1594 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001595 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596 return INVALID_OPERATION;
1597 }
1598
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001599 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1600 if (stream == nullptr) {
1601 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001602 return BAD_VALUE;
1603 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001604 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001605}
1606
1607status_t Camera3Device::deleteStream(int id) {
1608 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001609 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 Mutex::Autolock l(mLock);
1611 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001612
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001613 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001614
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 // CameraDevice semantics require device to already be idle before
1616 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001617 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001618 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001619 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001620 }
1621
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001622 if (mStatus == STATUS_ERROR) {
1623 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1624 __FUNCTION__, mId.string());
1625 return -EBUSY;
1626 }
1627
Igor Murashkin2fba5842013-04-22 14:03:54 -07001628 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001629 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001630 if (mInputStream != NULL && id == mInputStream->getId()) {
1631 deletedStream = mInputStream;
1632 mInputStream.clear();
1633 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001634 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001635 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001636 return BAD_VALUE;
1637 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001638 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001639 }
1640
1641 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001642 if (stream != nullptr) {
1643 deletedStream = stream;
1644 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001645 }
1646
1647 // Free up the stream endpoint so that it can be used by some other stream
1648 res = deletedStream->disconnect();
1649 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001650 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001651 // fall through since we want to still list the stream as deleted.
1652 }
1653 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001654 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001655
1656 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001657}
1658
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001659status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001660 ATRACE_CALL();
1661 ALOGV("%s: E", __FUNCTION__);
1662
1663 Mutex::Autolock il(mInterfaceLock);
1664 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001665
Emilian Peev811d2952018-05-25 11:08:40 +01001666 // In case the client doesn't include any session parameter, try a
1667 // speculative configuration using the values from the last cached
1668 // default request.
1669 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001670 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001671 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1672 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1673 mLastTemplateId);
1674 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1675 operatingMode);
1676 }
1677
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001678 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1679}
1680
1681status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1682 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001683 //Filter out any incoming session parameters
1684 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001685 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1686 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001687 CameraMetadata filteredParams(availableSessionKeys.count);
1688 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1689 filteredParams.getAndLock());
1690 set_camera_metadata_vendor_id(meta, mVendorTagId);
1691 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001692 if (availableSessionKeys.count > 0) {
1693 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1694 camera_metadata_ro_entry entry = params.find(
1695 availableSessionKeys.data.i32[i]);
1696 if (entry.count > 0) {
1697 filteredParams.update(entry);
1698 }
1699 }
1700 }
1701
1702 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001703}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001704
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001705status_t Camera3Device::getInputBufferProducer(
1706 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001707 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001708 Mutex::Autolock il(mInterfaceLock);
1709 Mutex::Autolock l(mLock);
1710
1711 if (producer == NULL) {
1712 return BAD_VALUE;
1713 } else if (mInputStream == NULL) {
1714 return INVALID_OPERATION;
1715 }
1716
1717 return mInputStream->getInputBufferProducer(producer);
1718}
1719
Emilian Peevf4816702020-04-03 15:44:51 -07001720status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001721 CameraMetadata *request) {
1722 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001723 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001724
Emilian Peevf4816702020-04-03 15:44:51 -07001725 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001726 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001727 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001728 return BAD_VALUE;
1729 }
1730
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001731 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001733 {
1734 Mutex::Autolock l(mLock);
1735 switch (mStatus) {
1736 case STATUS_ERROR:
1737 CLOGE("Device has encountered a serious error");
1738 return INVALID_OPERATION;
1739 case STATUS_UNINITIALIZED:
1740 CLOGE("Device is not initialized!");
1741 return INVALID_OPERATION;
1742 case STATUS_UNCONFIGURED:
1743 case STATUS_CONFIGURED:
1744 case STATUS_ACTIVE:
1745 // OK
1746 break;
1747 default:
1748 SET_ERR_L("Unexpected status: %d", mStatus);
1749 return INVALID_OPERATION;
1750 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001752 if (!mRequestTemplateCache[templateId].isEmpty()) {
1753 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001754 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001755 return OK;
1756 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001757 }
1758
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001759 camera_metadata_t *rawRequest;
1760 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001761 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001762
1763 {
1764 Mutex::Autolock l(mLock);
1765 if (res == BAD_VALUE) {
1766 ALOGI("%s: template %d is not supported on this camera device",
1767 __FUNCTION__, templateId);
1768 return res;
1769 } else if (res != OK) {
1770 CLOGE("Unable to construct request template %d: %s (%d)",
1771 templateId, strerror(-res), res);
1772 return res;
1773 }
1774
1775 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1776 mRequestTemplateCache[templateId].acquire(rawRequest);
1777
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001778 // Override the template request with zoomRatioMapper
1779 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1780 &mRequestTemplateCache[templateId]);
1781 if (res != OK) {
1782 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1783 templateId, strerror(-res), res);
1784 return res;
1785 }
1786
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001787 // Fill in JPEG_QUALITY if not available
1788 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1789 static const uint8_t kDefaultJpegQuality = 95;
1790 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1791 &kDefaultJpegQuality, 1);
1792 }
1793
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001794 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001795 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001796 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001797 return OK;
1798}
1799
1800status_t Camera3Device::waitUntilDrained() {
1801 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001803 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001804 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001805
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001806 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001807}
1808
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001809status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001810 switch (mStatus) {
1811 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 ALOGV("%s: Already idle", __FUNCTION__);
1814 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 case STATUS_CONFIGURED:
1816 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 case STATUS_ERROR:
1818 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001819 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 break;
1821 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001822 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001823 return INVALID_OPERATION;
1824 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001825 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1826 maxExpectedDuration);
1827 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001828 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001829 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001830 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1831 res);
1832 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 return res;
1834}
1835
Ruben Brunk183f0562015-08-12 12:55:02 -07001836void Camera3Device::internalUpdateStatusLocked(Status status) {
1837 mStatus = status;
1838 mRecentStatusUpdates.add(mStatus);
1839 mStatusChanged.broadcast();
1840}
1841
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001843status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001844 if (mRequestThread.get() != nullptr) {
1845 mRequestThread->setPaused(true);
1846 } else {
1847 return NO_INIT;
1848 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001850 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1851 maxExpectedDuration);
1852 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853 if (res != OK) {
1854 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001855 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856 }
1857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 return res;
1859}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001860
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861// Resume after internalPauseAndWaitLocked
1862status_t Camera3Device::internalResumeLocked() {
1863 status_t res;
1864
1865 mRequestThread->setPaused(false);
1866
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001867 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1868 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1870 if (res != OK) {
1871 SET_ERR_L("Can't transition to active in %f seconds!",
1872 kActiveTimeout/1e9);
1873 }
1874 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001875 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001876}
1877
Ruben Brunk183f0562015-08-12 12:55:02 -07001878status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001879 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001880
1881 size_t startIndex = 0;
1882 if (mStatusWaiters == 0) {
1883 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1884 // this status list
1885 mRecentStatusUpdates.clear();
1886 } else {
1887 // If other threads are waiting on updates to this status list, set the position of the
1888 // first element that this list will check rather than clearing the list.
1889 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890 }
1891
Ruben Brunk183f0562015-08-12 12:55:02 -07001892 mStatusWaiters++;
1893
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001894 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001895 if (!active && mUseHalBufManager) {
1896 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001897 if (mStatus == STATUS_ACTIVE) {
1898 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001899 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001900 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001901 mRequestBufferSM.onWaitUntilIdle();
1902 }
1903
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001904 bool stateSeen = false;
1905 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001906 if (active == (mStatus == STATUS_ACTIVE)) {
1907 // Desired state is current
1908 break;
1909 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001910
1911 res = mStatusChanged.waitRelative(mLock, timeout);
1912 if (res != OK) break;
1913
Ruben Brunk183f0562015-08-12 12:55:02 -07001914 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1915 // transitions.
1916 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1917 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1918 __FUNCTION__);
1919
1920 // Encountered desired state since we began waiting
1921 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001922 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1923 stateSeen = true;
1924 break;
1925 }
1926 }
1927 } while (!stateSeen);
1928
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001929 if (signalPipelineDrain) {
1930 mRequestThread->resetPipelineDrain();
1931 }
1932
Ruben Brunk183f0562015-08-12 12:55:02 -07001933 mStatusWaiters--;
1934
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 return res;
1936}
1937
1938
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001939status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001940 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001941 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001942
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001943 if (listener != NULL && mListener != NULL) {
1944 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1945 }
1946 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001947 mRequestThread->setNotificationListener(listener);
1948 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001949
1950 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951}
1952
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001953bool Camera3Device::willNotify3A() {
1954 return false;
1955}
1956
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001957status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001958 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001959 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001960
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001961 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001962 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1963 if (st == std::cv_status::timeout) {
1964 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001965 }
1966 }
1967 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968}
1969
Jianing Weicb0652e2014-03-12 18:29:36 -07001970status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001972 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001974 if (mResultQueue.empty()) {
1975 return NOT_ENOUGH_DATA;
1976 }
1977
Jianing Weicb0652e2014-03-12 18:29:36 -07001978 if (frame == NULL) {
1979 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1980 return BAD_VALUE;
1981 }
1982
1983 CaptureResult &result = *(mResultQueue.begin());
1984 frame->mResultExtras = result.mResultExtras;
1985 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001986 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001987 mResultQueue.erase(mResultQueue.begin());
1988
1989 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990}
1991
1992status_t Camera3Device::triggerAutofocus(uint32_t id) {
1993 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001994 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001995
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001996 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1997 // Mix-in this trigger into the next request and only the next request.
1998 RequestTrigger trigger[] = {
1999 {
2000 ANDROID_CONTROL_AF_TRIGGER,
2001 ANDROID_CONTROL_AF_TRIGGER_START
2002 },
2003 {
2004 ANDROID_CONTROL_AF_TRIGGER_ID,
2005 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002006 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002007 };
2008
2009 return mRequestThread->queueTrigger(trigger,
2010 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002011}
2012
2013status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2014 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002015 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002016
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002017 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2018 // Mix-in this trigger into the next request and only the next request.
2019 RequestTrigger trigger[] = {
2020 {
2021 ANDROID_CONTROL_AF_TRIGGER,
2022 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2023 },
2024 {
2025 ANDROID_CONTROL_AF_TRIGGER_ID,
2026 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002027 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002028 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002030 return mRequestThread->queueTrigger(trigger,
2031 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002032}
2033
2034status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2035 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002036 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002037
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002038 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2039 // Mix-in this trigger into the next request and only the next request.
2040 RequestTrigger trigger[] = {
2041 {
2042 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2043 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2044 },
2045 {
2046 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2047 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002048 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002049 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002050
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002051 return mRequestThread->queueTrigger(trigger,
2052 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053}
2054
Jianing Weicb0652e2014-03-12 18:29:36 -07002055status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002056 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002057 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002058 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002059
Zhijun He7ef20392014-04-21 16:04:17 -07002060 {
2061 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002062
2063 // b/116514106 "disconnect()" can get called twice for the same device. The
2064 // camera device will not be initialized during the second run.
2065 if (mStatus == STATUS_UNINITIALIZED) {
2066 return OK;
2067 }
2068
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002069 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002070
2071 // Stop session and stream counter
2072 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002073 }
2074
Emilian Peev08dd2452017-04-06 16:55:14 +01002075 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002076}
2077
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002078status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002079 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2080}
2081
2082status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002083 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002084 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002085 Mutex::Autolock il(mInterfaceLock);
2086 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002087
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002088 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2089 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002090 CLOGE("Stream %d does not exist", streamId);
2091 return BAD_VALUE;
2092 }
2093
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002095 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002096 return BAD_VALUE;
2097 }
2098
2099 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002100 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101 return BAD_VALUE;
2102 }
2103
Ruben Brunkc78ac262015-08-13 17:58:46 -07002104 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002105}
2106
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002107status_t Camera3Device::tearDown(int streamId) {
2108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002109 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002110 Mutex::Autolock il(mInterfaceLock);
2111 Mutex::Autolock l(mLock);
2112
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002113 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2114 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002115 CLOGE("Stream %d does not exist", streamId);
2116 return BAD_VALUE;
2117 }
2118
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002119 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2120 CLOGE("Stream %d is a target of a in-progress request", streamId);
2121 return BAD_VALUE;
2122 }
2123
2124 return stream->tearDown();
2125}
2126
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002127status_t Camera3Device::addBufferListenerForStream(int streamId,
2128 wp<Camera3StreamBufferListener> listener) {
2129 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002130 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002131 Mutex::Autolock il(mInterfaceLock);
2132 Mutex::Autolock l(mLock);
2133
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002134 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2135 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002136 CLOGE("Stream %d does not exist", streamId);
2137 return BAD_VALUE;
2138 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002139 stream->addBufferListener(listener);
2140
2141 return OK;
2142}
2143
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002145 * Methods called by subclasses
2146 */
2147
2148void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002149 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002150 std::vector<int> streamIds;
2151 std::vector<hardware::CameraStreamStats> streamStats;
2152
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002153 {
2154 // Need mLock to safely update state and synchronize to current
2155 // state of methods in flight.
2156 Mutex::Autolock l(mLock);
2157 // We can get various system-idle notices from the status tracker
2158 // while starting up. Only care about them if we've actually sent
2159 // in some requests recently.
2160 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2161 return;
2162 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002163 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2164 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002165 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002166
2167 // Skip notifying listener if we're doing some user-transparent
2168 // state changes
2169 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002170
2171 // Populate stream statistics in case of Idle
2172 if (idle) {
2173 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2174 auto stream = mOutputStreams[i];
2175 if (stream.get() == nullptr) continue;
2176 streamIds.push_back(stream->getId());
2177 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2178 int64_t usage = 0LL;
2179 if (camera3Stream != nullptr) {
2180 usage = camera3Stream->getUsage();
2181 }
2182 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2183 stream->getFormat(), stream->getDataSpace(), usage,
2184 stream->getMaxHalBuffers(),
2185 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2186 }
2187 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002188 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002189
2190 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002191 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002192 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002193 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002194 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002195 status_t res = OK;
2196 if (listener != nullptr) {
2197 if (idle) {
2198 // Get session stats from the builder, and notify the listener.
2199 int64_t requestCount, resultErrorCount;
2200 bool deviceError;
2201 std::map<int, StreamStats> streamStatsMap;
2202 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2203 &deviceError, &streamStatsMap);
2204 for (size_t i = 0; i < streamIds.size(); i++) {
2205 int streamId = streamIds[i];
2206 auto stats = streamStatsMap.find(streamId);
2207 if (stats != streamStatsMap.end()) {
2208 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2209 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2210 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2211 streamStats[i].mHistogramType =
2212 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2213 streamStats[i].mHistogramBins.assign(
2214 stats->second.mCaptureLatencyBins.begin(),
2215 stats->second.mCaptureLatencyBins.end());
2216 streamStats[i].mHistogramCounts.assign(
2217 stats->second.mCaptureLatencyHistogram.begin(),
2218 stats->second.mCaptureLatencyHistogram.end());
2219 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002220 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002221 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2222 } else {
2223 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002224 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002225 }
2226 if (res != OK) {
2227 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2228 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002229 }
2230}
2231
Shuzhen Wang758c2152017-01-10 18:26:18 -08002232status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002233 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002234 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002235 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2236 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002237
2238 if (surfaceIds == nullptr) {
2239 return BAD_VALUE;
2240 }
2241
Zhijun He5d677d12016-05-29 16:52:39 -07002242 Mutex::Autolock il(mInterfaceLock);
2243 Mutex::Autolock l(mLock);
2244
Shuzhen Wang758c2152017-01-10 18:26:18 -08002245 if (consumers.size() == 0) {
2246 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002247 return BAD_VALUE;
2248 }
2249
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002250 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2251 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002252 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002253 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002254 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002255
2256 // isConsumerConfigurationDeferred will be off after setConsumers
2257 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002258 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002259 if (res != OK) {
2260 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2261 return res;
2262 }
2263
Emilian Peev40ead602017-09-26 15:46:36 +01002264 for (auto &consumer : consumers) {
2265 int id = stream->getSurfaceId(consumer);
2266 if (id < 0) {
2267 CLOGE("Invalid surface id!");
2268 return BAD_VALUE;
2269 }
2270 surfaceIds->push_back(id);
2271 }
2272
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002273 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002274 if (!stream->isConfiguring()) {
2275 CLOGE("Stream %d was already fully configured.", streamId);
2276 return INVALID_OPERATION;
2277 }
Zhijun He5d677d12016-05-29 16:52:39 -07002278
Shuzhen Wang0129d522016-10-30 22:43:41 -07002279 res = stream->finishConfiguration();
2280 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002281 // If finishConfiguration fails due to abandoned surface, do not set
2282 // device to error state.
2283 bool isSurfaceAbandoned =
2284 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2285 if (!isSurfaceAbandoned) {
2286 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2287 stream->getId(), strerror(-res), res);
2288 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002289 return res;
2290 }
Zhijun He5d677d12016-05-29 16:52:39 -07002291 }
2292
2293 return OK;
2294}
2295
Emilian Peev40ead602017-09-26 15:46:36 +01002296status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2297 const std::vector<OutputStreamInfo> &outputInfo,
2298 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2299 Mutex::Autolock il(mInterfaceLock);
2300 Mutex::Autolock l(mLock);
2301
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002302 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2303 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002304 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002305 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002306 }
2307
2308 for (const auto &it : removedSurfaceIds) {
2309 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2310 CLOGE("Shared surface still part of a pending request!");
2311 return -EBUSY;
2312 }
2313 }
2314
Emilian Peev40ead602017-09-26 15:46:36 +01002315 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2316 if (res != OK) {
2317 CLOGE("Stream %d failed to update stream (error %d %s) ",
2318 streamId, res, strerror(-res));
2319 if (res == UNKNOWN_ERROR) {
2320 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2321 __FUNCTION__);
2322 }
2323 return res;
2324 }
2325
2326 return res;
2327}
2328
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002329status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2330 Mutex::Autolock il(mInterfaceLock);
2331 Mutex::Autolock l(mLock);
2332
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002333 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2334 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002335 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2336 return BAD_VALUE;
2337 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002338
2339 if (dropping) {
2340 mSessionStatsBuilder.stopCounter(streamId);
2341 } else {
2342 mSessionStatsBuilder.startCounter(streamId);
2343 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002344 return stream->dropBuffers(dropping);
2345}
2346
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002347/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002348 * Camera3Device private methods
2349 */
2350
2351sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002352 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002353 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002355 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002356 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002357
2358 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002359 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 if (inputStreams.count > 0) {
2361 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002362 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002363 CLOGE("Request references unknown input stream %d",
2364 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365 return NULL;
2366 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002367
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002368 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002369 SET_ERR_L("%s: input stream %d is not configured!",
2370 __FUNCTION__, mInputStream->getId());
2371 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002372 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002373 // Check if stream prepare is blocking requests.
2374 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002375 CLOGE("Request references an input stream that's being prepared!");
2376 return NULL;
2377 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378
2379 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002380 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 }
2382
2383 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002384 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002386 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002387 return NULL;
2388 }
2389
2390 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002391 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2392 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002393 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002394 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 return NULL;
2396 }
Zhijun He5d677d12016-05-29 16:52:39 -07002397 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002398 auto iter = surfaceMap.find(streams.data.i32[i]);
2399 if (iter != surfaceMap.end()) {
2400 const std::vector<size_t>& surfaces = iter->second;
2401 for (const auto& surface : surfaces) {
2402 if (stream->isConsumerConfigurationDeferred(surface)) {
2403 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2404 "due to deferred consumer", stream->getId(), surface);
2405 return NULL;
2406 }
2407 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002408 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002409 }
2410
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002411 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002412 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2413 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002415 // Check if stream prepare is blocking requests.
2416 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002417 CLOGE("Request references an output stream that's being prepared!");
2418 return NULL;
2419 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420
2421 newRequest->mOutputStreams.push(stream);
2422 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002423 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002424 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002426 auto rotateAndCropEntry =
2427 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2428 if (rotateAndCropEntry.count > 0 &&
2429 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2430 newRequest->mRotateAndCropAuto = true;
2431 } else {
2432 newRequest->mRotateAndCropAuto = false;
2433 }
2434
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002435 auto zoomRatioEntry =
2436 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2437 if (zoomRatioEntry.count > 0 &&
2438 zoomRatioEntry.data.f[0] == 1.0f) {
2439 newRequest->mZoomRatioIs1x = true;
2440 } else {
2441 newRequest->mZoomRatioIs1x = false;
2442 }
2443
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002444 if (mSupportCameraMute) {
2445 auto testPatternModeEntry =
2446 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2447 newRequest->mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2448 testPatternModeEntry.data.i32[0] :
2449 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2450
2451 auto testPatternDataEntry =
2452 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07002453 if (testPatternDataEntry.count >= 4) {
2454 memcpy(newRequest->mOriginalTestPatternData, testPatternDataEntry.data.i32,
2455 sizeof(CaptureRequest::mOriginalTestPatternData));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002456 } else {
2457 newRequest->mOriginalTestPatternData[0] = 0;
2458 newRequest->mOriginalTestPatternData[1] = 0;
2459 newRequest->mOriginalTestPatternData[2] = 0;
2460 newRequest->mOriginalTestPatternData[3] = 0;
2461 }
2462 }
2463
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002465}
2466
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002467void Camera3Device::cancelStreamsConfigurationLocked() {
2468 int res = OK;
2469 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2470 res = mInputStream->cancelConfiguration();
2471 if (res != OK) {
2472 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2473 mInputStream->getId(), strerror(-res), res);
2474 }
2475 }
2476
2477 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002478 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002479 if (outputStream->isConfiguring()) {
2480 res = outputStream->cancelConfiguration();
2481 if (res != OK) {
2482 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2483 outputStream->getId(), strerror(-res), res);
2484 }
2485 }
2486 }
2487
2488 // Return state to that at start of call, so that future configures
2489 // properly clean things up
2490 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2491 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002492
2493 res = mPreparerThread->resume();
2494 if (res != OK) {
2495 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2496 }
2497}
2498
Emilian Peev0d0191e2020-04-21 17:01:18 -07002499bool Camera3Device::checkAbandonedStreamsLocked() {
2500 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2501 return true;
2502 }
2503
2504 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2505 auto stream = mOutputStreams[i];
2506 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2507 return true;
2508 }
2509 }
2510
2511 return false;
2512}
2513
Emilian Peev3bead5f2020-05-28 17:29:08 -07002514bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002515 ATRACE_CALL();
2516 bool ret = false;
2517
Shuzhen Wang316781a2020-08-18 18:11:01 -07002518 nsecs_t startTime = systemTime();
2519
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002520 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002521 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2522
2523 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002524 if (checkAbandonedStreamsLocked()) {
2525 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2526 __FUNCTION__);
2527 return true;
2528 }
2529
Emilian Peev3bead5f2020-05-28 17:29:08 -07002530 status_t rc = NO_ERROR;
2531 bool markClientActive = false;
2532 if (mStatus == STATUS_ACTIVE) {
2533 markClientActive = true;
2534 mPauseStateNotify = true;
2535 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2536
2537 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2538 }
2539
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002540 if (rc == NO_ERROR) {
2541 mNeedConfig = true;
2542 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2543 if (rc == NO_ERROR) {
2544 ret = true;
2545 mPauseStateNotify = false;
2546 //Moving to active state while holding 'mLock' is important.
2547 //There could be pending calls to 'create-/deleteStream' which
2548 //will trigger another stream configuration while the already
2549 //present streams end up with outstanding buffers that will
2550 //not get drained.
2551 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002552 } else if (rc == DEAD_OBJECT) {
2553 // DEAD_OBJECT can be returned if either the consumer surface is
2554 // abandoned, or the HAL has died.
2555 // - If the HAL has died, configureStreamsLocked call will set
2556 // device to error state,
2557 // - If surface is abandoned, we should not set device to error
2558 // state.
2559 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002560 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002561 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002562 }
2563 } else {
2564 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2565 }
2566
Shuzhen Wang316781a2020-08-18 18:11:01 -07002567 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2568 ns2ms(systemTime() - startTime));
2569
Emilian Peev3bead5f2020-05-28 17:29:08 -07002570 if (markClientActive) {
2571 mStatusTracker->markComponentActive(clientStatusId);
2572 }
2573
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002574 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002575}
2576
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002577status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002578 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 ATRACE_CALL();
2580 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002582 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002583 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002584 return INVALID_OPERATION;
2585 }
2586
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002587 if (operatingMode < 0) {
2588 CLOGE("Invalid operating mode: %d", operatingMode);
2589 return BAD_VALUE;
2590 }
2591
2592 bool isConstrainedHighSpeed =
2593 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2594 operatingMode;
2595
2596 if (mOperatingMode != operatingMode) {
2597 mNeedConfig = true;
2598 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2599 mOperatingMode = operatingMode;
2600 }
2601
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002602 // In case called from configureStreams, abort queued input buffers not belonging to
2603 // any pending requests.
2604 if (mInputStream != NULL && notifyRequestThread) {
2605 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002606 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002607 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002608 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002609 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002610 if (res != OK) {
2611 // Exhausted acquiring all input buffers.
2612 break;
2613 }
2614
Emilian Peevf4816702020-04-03 15:44:51 -07002615 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002616 res = mInputStream->returnInputBuffer(inputBuffer);
2617 if (res != OK) {
2618 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2619 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2620 }
2621 }
2622 }
2623
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002624 if (!mNeedConfig) {
2625 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2626 return OK;
2627 }
2628
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002629 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002630 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002631 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2632 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002633 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002634 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002635 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002636 }
2637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002638 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002639 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002641 mPreparerThread->pause();
2642
Emilian Peevf4816702020-04-03 15:44:51 -07002643 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002644 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002646 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647
Emilian Peevf4816702020-04-03 15:44:51 -07002648 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002650 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002651
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652
2653 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002654 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655 inputStream = mInputStream->startConfiguration();
2656 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002657 CLOGE("Can't start input stream configuration");
2658 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659 return INVALID_OPERATION;
2660 }
2661 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002662
2663 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 }
2665
Shuzhen Wang99080502021-03-07 21:08:20 -08002666 mGroupIdPhysicalCameraMap.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002668
2669 // Don't configure bidi streams twice, nor add them twice to the list
2670 if (mOutputStreams[i].get() ==
2671 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2672
2673 config.num_streams--;
2674 continue;
2675 }
2676
Emilian Peevf4816702020-04-03 15:44:51 -07002677 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002678 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002680 CLOGE("Can't start output stream configuration");
2681 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 return INVALID_OPERATION;
2683 }
2684 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002685
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002686 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002687 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2688 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002689 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2690 bufferSizes[k] = static_cast<uint32_t>(
2691 getJpegBufferSize(outputStream->width, outputStream->height));
2692 } else if (outputStream->data_space ==
2693 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2694 bufferSizes[k] = outputStream->width * outputStream->height;
2695 } else {
2696 ALOGW("%s: Blob dataSpace %d not supported",
2697 __FUNCTION__, outputStream->data_space);
2698 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002699 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002700
2701 if (mOutputStreams[i]->isMultiResolution()) {
2702 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2703 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2704 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2705 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002706 }
2707
2708 config.streams = streams.editArray();
2709
2710 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002711 // max_buffers, usage, and priv fields, as well as data_space and format
2712 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002713
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002714 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002715 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002716 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002718 if (res == BAD_VALUE) {
2719 // HAL rejected this set of streams as unsupported, clean up config
2720 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002721 CLOGE("Set of requested inputs/outputs not supported by HAL");
2722 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002723 return BAD_VALUE;
2724 } else if (res != OK) {
2725 // Some other kind of error from configure_streams - this is not
2726 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002727 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2728 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002729 return res;
2730 }
2731
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002732 // Finish all stream configuration immediately.
2733 // TODO: Try to relax this later back to lazy completion, which should be
2734 // faster
2735
Igor Murashkin073f8572013-05-02 14:59:28 -07002736 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002737 bool streamReConfigured = false;
2738 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002739 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002740 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002741 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002742 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002743 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2744 return DEAD_OBJECT;
2745 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002746 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002747 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002748 if (streamReConfigured) {
2749 mInterface->onStreamReConfigured(mInputStream->getId());
2750 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002751 }
2752
2753 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002754 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002755 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002756 bool streamReConfigured = false;
2757 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002758 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002759 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002760 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002761 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002762 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2763 return DEAD_OBJECT;
2764 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002765 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002766 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002767 if (streamReConfigured) {
2768 mInterface->onStreamReConfigured(outputStream->getId());
2769 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002770 }
2771 }
2772
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002773 // Request thread needs to know to avoid using repeat-last-settings protocol
2774 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002775 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002776 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2777 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002778 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002779
Zhijun He90f7c372016-08-16 16:19:43 -07002780 char value[PROPERTY_VALUE_MAX];
2781 property_get("camera.fifo.disable", value, "0");
2782 int32_t disableFifo = atoi(value);
2783 if (disableFifo != 1) {
2784 // Boost priority of request thread to SCHED_FIFO.
2785 pid_t requestThreadTid = mRequestThread->getTid();
2786 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002787 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002788 if (res != OK) {
2789 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2790 strerror(-res), res);
2791 } else {
2792 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2793 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002794 }
2795
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002796 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002797 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2798 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2799 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2800 sessionParams.unlock(newSessionParams);
2801 mSessionParams.unlock(currentSessionParams);
2802 if (updateSessionParams) {
2803 mSessionParams = sessionParams;
2804 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002805
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002806 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002807
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002808 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002809 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002810
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002811 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002812
Zhijun He0a210512014-07-24 13:45:15 -07002813 // tear down the deleted streams after configure streams.
2814 mDeletedStreams.clear();
2815
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002816 auto rc = mPreparerThread->resume();
2817 if (rc != OK) {
2818 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2819 return rc;
2820 }
2821
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002822 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002823 mRequestBufferSM.onStreamsConfigured();
2824 }
2825
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002826 // Since the streams configuration of the injection camera is based on the internal camera, we
2827 // must wait until the internal camera configure streams before calling injectCamera() to
2828 // configure the injection streams.
2829 if (mInjectionMethods->isInjecting()) {
2830 ALOGV("%s: Injection camera %s: Start to configure streams.",
2831 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2832 res = mInjectionMethods->injectCamera(config, bufferSizes);
2833 if (res != OK) {
2834 ALOGE("Can't finish inject camera process!");
2835 return res;
2836 }
2837 }
2838
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002839 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002840}
2841
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002842status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002843 ATRACE_CALL();
2844 status_t res;
2845
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002846 if (mFakeStreamId != NO_STREAM) {
2847 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002848 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002849 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002850 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002851 return INVALID_OPERATION;
2852 }
2853
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002854 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002855
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002856 sp<Camera3OutputStreamInterface> fakeStream =
2857 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002858
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002860 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002861 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002862 return res;
2863 }
2864
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002865 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002866 mNextStreamId++;
2867
2868 return OK;
2869}
2870
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002871status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002872 ATRACE_CALL();
2873 status_t res;
2874
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002875 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002876 if (mOutputStreams.size() == 1) return OK;
2877
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002878 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002879
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002880 // Ok, have a fake stream and there's at least one other output stream,
2881 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002882
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002883 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002884 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002885 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002886 return INVALID_OPERATION;
2887 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002888 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889
2890 // Free up the stream endpoint so that it can be used by some other stream
2891 res = deletedStream->disconnect();
2892 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002893 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002894 // fall through since we want to still list the stream as deleted.
2895 }
2896 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002897 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002898
2899 return res;
2900}
2901
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002902void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002903 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002904 Mutex::Autolock l(mLock);
2905 va_list args;
2906 va_start(args, fmt);
2907
2908 setErrorStateLockedV(fmt, args);
2909
2910 va_end(args);
2911}
2912
2913void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002914 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002915 Mutex::Autolock l(mLock);
2916 setErrorStateLockedV(fmt, args);
2917}
2918
2919void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2920 va_list args;
2921 va_start(args, fmt);
2922
2923 setErrorStateLockedV(fmt, args);
2924
2925 va_end(args);
2926}
2927
2928void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002929 // Print out all error messages to log
2930 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002931 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002932
2933 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002934 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002935
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002936 mErrorCause = errorCause;
2937
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002938 if (mRequestThread != nullptr) {
2939 mRequestThread->setPaused(true);
2940 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002941 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002942
2943 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002944 sp<NotificationListener> listener = mListener.promote();
2945 if (listener != NULL) {
2946 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002947 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002948 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002949 }
2950
2951 // Save stack trace. View by dumping it later.
2952 CameraTraces::saveTrace();
2953 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002954}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955
2956/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002957 * In-flight request management
2958 */
2959
Jianing Weicb0652e2014-03-12 18:29:36 -07002960status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002961 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002962 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002963 const std::set<std::set<String8>>& physicalCameraIds,
2964 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2965 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002966 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002967 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002968 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002969
2970 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002971 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002972 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002973 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002974 if (res < 0) return res;
2975
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002976 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002977 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2978 // avoid a deadlock during reprocess requests.
2979 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002980 if (mStatusTracker != nullptr) {
2981 mStatusTracker->markComponentActive(mInFlightStatusId);
2982 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002983 }
2984
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002985 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002986 return OK;
2987}
2988
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002989void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002990 // Indicate idle inFlightMap to the status tracker
2991 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002992 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002993 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2994 // avoid a deadlock during reprocess requests.
2995 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002996 if (mStatusTracker != nullptr) {
2997 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2998 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002999 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003000 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003001}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003002
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003003void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003004 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003005 // something has likely gone wrong. This might still be legit only if application send in
3006 // a long burst of long exposure requests.
3007 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3008 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3009 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3010 mInFlightMap.size(), mExpectedInflightDuration);
3011 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3012 kInFlightWarnLimitHighSpeed) {
3013 CLOGW("In-flight list too large for high speed configuration: %zu,"
3014 "total inflight duration %" PRIu64,
3015 mInFlightMap.size(), mExpectedInflightDuration);
3016 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003017 }
3018}
3019
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003020void Camera3Device::onInflightMapFlushedLocked() {
3021 mExpectedInflightDuration = 0;
3022}
3023
3024void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07003025 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003026 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
3027 mInFlightMap.removeItemsAt(idx, 1);
3028
3029 onInflightEntryRemovedLocked(duration);
3030}
3031
3032
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003033void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003034 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003035 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003036 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003037 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003038 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003039 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003040
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003041 FlushInflightReqStates states {
3042 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07003043 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003044
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003045 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003046}
3047
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003048CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003049 ALOGV("%s", __FUNCTION__);
3050
Igor Murashkin1e479c02013-09-06 16:55:14 -07003051 CameraMetadata retVal;
3052
3053 if (mRequestThread != NULL) {
3054 retVal = mRequestThread->getLatestRequest();
3055 }
3056
Igor Murashkin1e479c02013-09-06 16:55:14 -07003057 return retVal;
3058}
3059
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003060void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003061 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
3062 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
3063
3064 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
3065 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003066}
3067
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003068/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003069 * HalInterface inner class methods
3070 */
3071
Yifan Hongf79b5542017-04-11 14:44:25 -07003072Camera3Device::HalInterface::HalInterface(
3073 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003074 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003075 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003076 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003077 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003078 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003079 mIsReconfigurationQuerySupported(true),
3080 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003081 // Check with hardware service manager if we can downcast these interfaces
3082 // Somewhat expensive, so cache the results at startup
Shuzhen Wang83bff122020-11-20 15:51:39 -08003083 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3084 if (castResult_3_7.isOk()) {
3085 mHidlSession_3_7 = castResult_3_7;
3086 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003087 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
3088 if (castResult_3_6.isOk()) {
3089 mHidlSession_3_6 = castResult_3_6;
3090 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003091 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3092 if (castResult_3_5.isOk()) {
3093 mHidlSession_3_5 = castResult_3_5;
3094 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003095 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3096 if (castResult_3_4.isOk()) {
3097 mHidlSession_3_4 = castResult_3_4;
3098 }
3099 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3100 if (castResult_3_3.isOk()) {
3101 mHidlSession_3_3 = castResult_3_3;
3102 }
3103}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003104
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003105Camera3Device::HalInterface::HalInterface() :
3106 mUseHalBufManager(false),
3107 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003108
3109Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003110 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003111 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003112 mUseHalBufManager(other.mUseHalBufManager),
3113 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003114
3115bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003116 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003117}
3118
3119void Camera3Device::HalInterface::clear() {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003120 mHidlSession_3_7.clear();
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003121 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003122 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003123 mHidlSession_3_4.clear();
3124 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125 mHidlSession.clear();
3126}
3127
3128status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003129 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130 /*out*/ camera_metadata_t **requestTemplate) {
3131 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3132 if (!valid()) return INVALID_OPERATION;
3133 status_t res = OK;
3134
Emilian Peev31abd0a2017-05-11 18:37:46 +01003135 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003136
3137 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003138 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003139 status = s;
3140 if (status == common::V1_0::Status::OK) {
3141 const camera_metadata *r =
3142 reinterpret_cast<const camera_metadata_t*>(request.data());
3143 size_t expectedSize = request.size();
3144 int ret = validate_camera_metadata_structure(r, &expectedSize);
3145 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3146 *requestTemplate = clone_camera_metadata(r);
3147 if (*requestTemplate == nullptr) {
3148 ALOGE("%s: Unable to clone camera metadata received from HAL",
3149 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003150 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003151 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003152 } else {
3153 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3154 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003155 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003156 }
3157 };
3158 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003159 RequestTemplate id;
3160 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003161 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003162 id = RequestTemplate::PREVIEW;
3163 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003164 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003165 id = RequestTemplate::STILL_CAPTURE;
3166 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003167 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003168 id = RequestTemplate::VIDEO_RECORD;
3169 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003170 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003171 id = RequestTemplate::VIDEO_SNAPSHOT;
3172 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003173 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003174 id = RequestTemplate::ZERO_SHUTTER_LAG;
3175 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003176 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003177 id = RequestTemplate::MANUAL;
3178 break;
3179 default:
3180 // Unknown template ID, or this HAL is too old to support it
3181 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003182 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003183 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003184
Emilian Peev31abd0a2017-05-11 18:37:46 +01003185 if (!err.isOk()) {
3186 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3187 res = DEAD_OBJECT;
3188 } else {
3189 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003190 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003191
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003192 return res;
3193}
3194
Emilian Peev4ec17882019-01-24 17:16:58 -08003195bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3196 CameraMetadata& newSessionParams) {
3197 // We do reconfiguration by default;
3198 bool ret = true;
3199 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3200 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3201 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3202 oldSessionParams.getAndLock());
3203 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3204 newSessionParams.getAndLock());
3205 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3206 get_camera_metadata_size(oldSessioMeta));
3207 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3208 get_camera_metadata_size(newSessioMeta));
3209 hardware::camera::common::V1_0::Status callStatus;
3210 bool required;
3211 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3212 bool requiredFlag) {
3213 callStatus = s;
3214 required = requiredFlag;
3215 };
3216 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3217 oldSessionParams.unlock(oldSessioMeta);
3218 newSessionParams.unlock(newSessioMeta);
3219 if (err.isOk()) {
3220 switch (callStatus) {
3221 case hardware::camera::common::V1_0::Status::OK:
3222 ret = required;
3223 break;
3224 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3225 mIsReconfigurationQuerySupported = false;
3226 ret = true;
3227 break;
3228 default:
3229 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3230 ret = true;
3231 }
3232 } else {
3233 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3234 ret = true;
3235 }
3236 }
3237
3238 return ret;
3239}
3240
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003241status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003242 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003243 ATRACE_NAME("CameraHal::configureStreams");
3244 if (!valid()) return INVALID_OPERATION;
3245 status_t res = OK;
3246
Shuzhen Wang83bff122020-11-20 15:51:39 -08003247 if (config->input_is_multi_resolution && mHidlSession_3_7 == nullptr) {
3248 ALOGE("%s: Camera device doesn't support multi-resolution input stream", __FUNCTION__);
3249 return BAD_VALUE;
3250 }
3251
Emilian Peev31abd0a2017-05-11 18:37:46 +01003252 // Convert stream config to HIDL
3253 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003254 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3255 device::V3_4::StreamConfiguration requestedConfiguration3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003256 device::V3_7::StreamConfiguration requestedConfiguration3_7;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003257 requestedConfiguration3_2.streams.resize(config->num_streams);
3258 requestedConfiguration3_4.streams.resize(config->num_streams);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003259 requestedConfiguration3_7.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003260 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003261 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3262 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Shuzhen Wang83bff122020-11-20 15:51:39 -08003263 device::V3_7::Stream &dst3_7 = requestedConfiguration3_7.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003264 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003265
Emilian Peev31abd0a2017-05-11 18:37:46 +01003266 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3267 cam3stream->setBufferFreedListener(this);
3268 int streamId = cam3stream->getId();
3269 StreamType streamType;
3270 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003271 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003272 streamType = StreamType::OUTPUT;
3273 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003274 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003275 streamType = StreamType::INPUT;
3276 break;
3277 default:
3278 ALOGE("%s: Stream %d: Unsupported stream type %d",
3279 __FUNCTION__, streamId, config->streams[i]->stream_type);
3280 return BAD_VALUE;
3281 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003282 dst3_2.id = streamId;
3283 dst3_2.streamType = streamType;
3284 dst3_2.width = src->width;
3285 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003286 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003287 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003288 // For HidlSession version 3.5 or newer, the format and dataSpace sent
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003289 // to HAL are original, not the overridden ones.
Shuzhen Wang92653952019-05-07 15:11:43 -07003290 if (mHidlSession_3_5 != nullptr) {
3291 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3292 cam3stream->getOriginalFormat() : src->format);
3293 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3294 cam3stream->getOriginalDataSpace() : src->data_space);
3295 } else {
3296 dst3_2.format = mapToPixelFormat(src->format);
3297 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3298 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003299 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003300 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003301 if (src->physical_camera_id != nullptr) {
3302 dst3_4.physicalCameraId = src->physical_camera_id;
3303 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003304 dst3_7.v3_4 = dst3_4;
3305 dst3_7.groupId = cam3stream->getHalStreamGroupId();
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003306 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3307 size_t j = 0;
3308 for (int mode : src->sensor_pixel_modes_used) {
3309 dst3_7.sensorPixelModesUsed[j++] =
3310 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3311 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003312 activeStreams.insert(streamId);
3313 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003314 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003315 }
3316 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003317 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003318
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003319 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003320 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003321 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003322 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 if (res != OK) {
3324 return res;
3325 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003326 requestedConfiguration3_2.operationMode = operationMode;
3327 requestedConfiguration3_4.operationMode = operationMode;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003328 requestedConfiguration3_7.operationMode = operationMode;
3329 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003330 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003331 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003332 sessionParamSize);
Shuzhen Wang83bff122020-11-20 15:51:39 -08003333 requestedConfiguration3_7.operationMode = operationMode;
3334 requestedConfiguration3_7.sessionParams.setToExternal(
3335 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08003336 sessionParamSize);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003337
Emilian Peev31abd0a2017-05-11 18:37:46 +01003338 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003339 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003340 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003341 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003342 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003343
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003344 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003345 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3346 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003347 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003348 };
3349
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003350 auto configStream36Cb = [&status, &finalConfiguration3_6]
3351 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3352 finalConfiguration3_6 = halConfiguration;
3353 status = s;
3354 };
3355
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003356 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3357 (hardware::Return<void>& err) -> status_t {
3358 if (!err.isOk()) {
3359 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3360 return DEAD_OBJECT;
3361 }
3362 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3363 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3364 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3365 }
3366 return OK;
3367 };
3368
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003369 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3370 (hardware::Return<void>& err) -> status_t {
3371 if (!err.isOk()) {
3372 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3373 return DEAD_OBJECT;
3374 }
3375 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3376 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3377 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3378 }
3379 return OK;
3380 };
3381
Shuzhen Wang92653952019-05-07 15:11:43 -07003382 // See which version of HAL we have
Shuzhen Wang83bff122020-11-20 15:51:39 -08003383 if (mHidlSession_3_7 != nullptr) {
3384 ALOGV("%s: v3.7 device found", __FUNCTION__);
3385 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3386 requestedConfiguration3_7.multiResolutionInputImage = config->input_is_multi_resolution;
3387 auto err = mHidlSession_3_7->configureStreams_3_7(
3388 requestedConfiguration3_7, configStream36Cb);
3389 res = postprocConfigStream36(err);
3390 if (res != OK) {
3391 return res;
3392 }
3393 } else if (mHidlSession_3_6 != nullptr) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003394 ALOGV("%s: v3.6 device found", __FUNCTION__);
3395 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3396 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3397 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3398 auto err = mHidlSession_3_6->configureStreams_3_6(
3399 requestedConfiguration3_5, configStream36Cb);
3400 res = postprocConfigStream36(err);
3401 if (res != OK) {
3402 return res;
3403 }
3404 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003405 ALOGV("%s: v3.5 device found", __FUNCTION__);
3406 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3407 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3408 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3409 auto err = mHidlSession_3_5->configureStreams_3_5(
3410 requestedConfiguration3_5, configStream34Cb);
3411 res = postprocConfigStream34(err);
3412 if (res != OK) {
3413 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003414 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003415 } else if (mHidlSession_3_4 != nullptr) {
3416 // We do; use v3.4 for the call
3417 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003418 auto err = mHidlSession_3_4->configureStreams_3_4(
3419 requestedConfiguration3_4, configStream34Cb);
3420 res = postprocConfigStream34(err);
3421 if (res != OK) {
3422 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003423 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003424 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003425 // We do; use v3.3 for the call
3426 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003427 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003428 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003429 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003430 finalConfiguration = halConfiguration;
3431 status = s;
3432 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003433 if (!err.isOk()) {
3434 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3435 return DEAD_OBJECT;
3436 }
3437 } else {
3438 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3439 ALOGV("%s: v3.2 device found", __FUNCTION__);
3440 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003441 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003442 [&status, &finalConfiguration_3_2]
3443 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3444 finalConfiguration_3_2 = halConfiguration;
3445 status = s;
3446 });
3447 if (!err.isOk()) {
3448 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3449 return DEAD_OBJECT;
3450 }
3451 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3452 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3453 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3454 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003455 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003456 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003457 }
3458
3459 if (status != common::V1_0::Status::OK ) {
3460 return CameraProviderManager::mapToStatusT(status);
3461 }
3462
3463 // And convert output stream configuration from HIDL
3464
3465 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003466 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003467 int streamId = Camera3Stream::cast(dst)->getId();
3468
3469 // Start scan at i, with the assumption that the stream order matches
3470 size_t realIdx = i;
3471 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003472 size_t halStreamCount = finalConfiguration.streams.size();
3473 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003474 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003475 found = true;
3476 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003477 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003478 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 }
3480 if (!found) {
3481 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3482 __FUNCTION__, streamId);
3483 return INVALID_OPERATION;
3484 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003485 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003486 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003487
Emilian Peev710c1422017-08-30 11:19:38 +01003488 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003489 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3490 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3491
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003492 if (mHidlSession_3_6 != nullptr) {
3493 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3494 }
3495
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003496 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003497 dstStream->setFormatOverride(false);
3498 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 if (dst->format != overrideFormat) {
3500 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3501 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003502 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003503 if (dst->data_space != overrideDataSpace) {
3504 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3505 streamId, dst->format);
3506 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003507 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003508 bool needFormatOverride =
3509 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3510 bool needDataspaceOverride =
3511 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003512 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003513 dstStream->setFormatOverride(needFormatOverride);
3514 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003515 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003516 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003517 }
3518
Emilian Peevf4816702020-04-03 15:44:51 -07003519 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003520 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003521 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003522 __FUNCTION__, streamId);
3523 return INVALID_OPERATION;
3524 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003525 dstStream->setUsage(
3526 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003527 } else {
3528 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003529 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003530 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3531 __FUNCTION__, streamId);
3532 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003533 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003534 dstStream->setUsage(
3535 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003536 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003537 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003538 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003539
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003540 return res;
3541}
3542
Cliff Wuc2ad9c82021-04-21 00:58:58 +08003543status_t Camera3Device::HalInterface::configureInjectedStreams(
3544 const camera_metadata_t* sessionParams, camera_stream_configuration* config,
3545 const std::vector<uint32_t>& bufferSizes,
3546 const CameraMetadata& cameraCharacteristics) {
3547 ATRACE_NAME("InjectionCameraHal::configureStreams");
3548 if (!valid()) return INVALID_OPERATION;
3549 status_t res = OK;
3550
3551 if (config->input_is_multi_resolution) {
3552 ALOGE("%s: Injection camera device doesn't support multi-resolution input "
3553 "stream", __FUNCTION__);
3554 return BAD_VALUE;
3555 }
3556
3557 // Convert stream config to HIDL
3558 std::set<int> activeStreams;
3559 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3560 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3561 device::V3_7::StreamConfiguration requestedConfiguration3_7;
3562 requestedConfiguration3_2.streams.resize(config->num_streams);
3563 requestedConfiguration3_4.streams.resize(config->num_streams);
3564 requestedConfiguration3_7.streams.resize(config->num_streams);
3565 for (size_t i = 0; i < config->num_streams; i++) {
3566 device::V3_2::Stream& dst3_2 = requestedConfiguration3_2.streams[i];
3567 device::V3_4::Stream& dst3_4 = requestedConfiguration3_4.streams[i];
3568 device::V3_7::Stream& dst3_7 = requestedConfiguration3_7.streams[i];
3569 camera3::camera_stream_t* src = config->streams[i];
3570
3571 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3572 cam3stream->setBufferFreedListener(this);
3573 int streamId = cam3stream->getId();
3574 StreamType streamType;
3575 switch (src->stream_type) {
3576 case CAMERA_STREAM_OUTPUT:
3577 streamType = StreamType::OUTPUT;
3578 break;
3579 case CAMERA_STREAM_INPUT:
3580 streamType = StreamType::INPUT;
3581 break;
3582 default:
3583 ALOGE("%s: Stream %d: Unsupported stream type %d", __FUNCTION__,
3584 streamId, config->streams[i]->stream_type);
3585 return BAD_VALUE;
3586 }
3587 dst3_2.id = streamId;
3588 dst3_2.streamType = streamType;
3589 dst3_2.width = src->width;
3590 dst3_2.height = src->height;
3591 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3592 dst3_2.rotation =
3593 mapToStreamRotation((camera_stream_rotation_t)src->rotation);
3594 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3595 // to HAL are original, not the overridden ones.
3596 if (mHidlSession_3_5 != nullptr) {
3597 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden()
3598 ? cam3stream->getOriginalFormat()
3599 : src->format);
3600 dst3_2.dataSpace =
3601 mapToHidlDataspace(cam3stream->isDataSpaceOverridden()
3602 ? cam3stream->getOriginalDataSpace()
3603 : src->data_space);
3604 } else {
3605 dst3_2.format = mapToPixelFormat(src->format);
3606 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3607 }
3608 dst3_4.v3_2 = dst3_2;
3609 dst3_4.bufferSize = bufferSizes[i];
3610 if (src->physical_camera_id != nullptr) {
3611 dst3_4.physicalCameraId = src->physical_camera_id;
3612 }
3613 dst3_7.v3_4 = dst3_4;
3614 dst3_7.groupId = cam3stream->getHalStreamGroupId();
3615 dst3_7.sensorPixelModesUsed.resize(src->sensor_pixel_modes_used.size());
3616 size_t j = 0;
3617 for (int mode : src->sensor_pixel_modes_used) {
3618 dst3_7.sensorPixelModesUsed[j++] =
3619 static_cast<CameraMetadataEnumAndroidSensorPixelMode>(mode);
3620 }
3621 activeStreams.insert(streamId);
3622 // Create Buffer ID map if necessary
3623 mBufferRecords.tryCreateBufferCache(streamId);
3624 }
3625 // remove BufferIdMap for deleted streams
3626 mBufferRecords.removeInactiveBufferCaches(activeStreams);
3627
3628 StreamConfigurationMode operationMode;
3629 res = mapToStreamConfigurationMode(
3630 (camera_stream_configuration_mode_t)config->operation_mode,
3631 /*out*/ &operationMode);
3632 if (res != OK) {
3633 return res;
3634 }
3635 requestedConfiguration3_7.operationMode = operationMode;
3636 size_t sessionParamSize = get_camera_metadata_size(sessionParams);
3637 requestedConfiguration3_7.operationMode = operationMode;
3638 requestedConfiguration3_7.sessionParams.setToExternal(
3639 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3640 sessionParamSize);
3641
3642 // See which version of HAL we have
3643 if (mHidlSession_3_7 != nullptr) {
3644 requestedConfiguration3_7.streamConfigCounter = mNextStreamConfigCounter++;
3645 requestedConfiguration3_7.multiResolutionInputImage =
3646 config->input_is_multi_resolution;
3647
3648 const camera_metadata_t* rawMetadata = cameraCharacteristics.getAndLock();
3649 ::android::hardware::camera::device::V3_2::CameraMetadata hidlChars = {};
3650 hidlChars.setToExternal(
3651 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(rawMetadata)),
3652 get_camera_metadata_size(rawMetadata));
3653 cameraCharacteristics.unlock(rawMetadata);
3654
3655 sp<hardware::camera::device::V3_7::ICameraInjectionSession>
3656 hidlInjectionSession_3_7;
3657 auto castInjectionResult_3_7 =
3658 device::V3_7::ICameraInjectionSession::castFrom(mHidlSession_3_7);
3659 if (castInjectionResult_3_7.isOk()) {
3660 hidlInjectionSession_3_7 = castInjectionResult_3_7;
3661 } else {
3662 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3663 castInjectionResult_3_7.description().c_str());
3664 return DEAD_OBJECT;
3665 }
3666
3667 auto err = hidlInjectionSession_3_7->configureInjectionStreams(
3668 requestedConfiguration3_7, hidlChars);
3669 if (!err.isOk()) {
3670 ALOGE("%s: Transaction error: %s", __FUNCTION__,
3671 err.description().c_str());
3672 return DEAD_OBJECT;
3673 }
3674 } else {
3675 ALOGE("%s: mHidlSession_3_7 does not exist, the lowest version of injection "
3676 "session is 3.7", __FUNCTION__);
3677 return DEAD_OBJECT;
3678 }
3679
3680 return res;
3681}
3682
Emilian Peevf4816702020-04-03 15:44:51 -07003683status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003684 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003685 /*out*/std::vector<native_handle_t*>* handlesCreated,
3686 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003687 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003688 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3689 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3690 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003691 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003692 }
3693
3694 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003695
3696 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003697
3698 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003699 if (request->input_buffer != nullptr) {
3700 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3701 buffer_handle_t buf = *(request->input_buffer->buffer);
3702 auto pair = getBufferId(buf, streamId);
3703 bool isNewBuffer = pair.first;
3704 uint64_t bufferId = pair.second;
3705 captureRequest->inputBuffer.streamId = streamId;
3706 captureRequest->inputBuffer.bufferId = bufferId;
3707 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3708 captureRequest->inputBuffer.status = BufferStatus::OK;
3709 native_handle_t *acquireFence = nullptr;
3710 if (request->input_buffer->acquire_fence != -1) {
3711 acquireFence = native_handle_create(1,0);
3712 acquireFence->data[0] = request->input_buffer->acquire_fence;
3713 handlesCreated->push_back(acquireFence);
3714 }
3715 captureRequest->inputBuffer.acquireFence = acquireFence;
3716 captureRequest->inputBuffer.releaseFence = nullptr;
3717
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003718 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003719 request->input_buffer->buffer);
3720 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003721 } else {
3722 captureRequest->inputBuffer.streamId = -1;
3723 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3724 }
3725
3726 captureRequest->outputBuffers.resize(request->num_output_buffers);
3727 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003728 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003729 StreamBuffer &dst = captureRequest->outputBuffers[i];
3730 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003731 if (src->buffer != nullptr) {
3732 buffer_handle_t buf = *(src->buffer);
3733 auto pair = getBufferId(buf, streamId);
3734 bool isNewBuffer = pair.first;
3735 dst.bufferId = pair.second;
3736 dst.buffer = isNewBuffer ? buf : nullptr;
3737 native_handle_t *acquireFence = nullptr;
3738 if (src->acquire_fence != -1) {
3739 acquireFence = native_handle_create(1,0);
3740 acquireFence->data[0] = src->acquire_fence;
3741 handlesCreated->push_back(acquireFence);
3742 }
3743 dst.acquireFence = acquireFence;
3744 } else if (mUseHalBufManager) {
3745 // HAL buffer management path
3746 dst.bufferId = BUFFER_ID_NO_BUFFER;
3747 dst.buffer = nullptr;
3748 dst.acquireFence = nullptr;
3749 } else {
3750 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3751 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003752 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003753 dst.streamId = streamId;
3754 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003755 dst.releaseFence = nullptr;
3756
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003757 // Output buffers are empty when using HAL buffer manager
3758 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003759 mBufferRecords.pushInflightBuffer(
3760 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003761 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003762 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003763 }
3764 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003765 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003766}
3767
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003768void Camera3Device::HalInterface::cleanupNativeHandles(
3769 std::vector<native_handle_t*> *handles, bool closeFd) {
3770 if (handles == nullptr) {
3771 return;
3772 }
3773 if (closeFd) {
3774 for (auto& handle : *handles) {
3775 native_handle_close(handle);
3776 }
3777 }
3778 for (auto& handle : *handles) {
3779 native_handle_delete(handle);
3780 }
3781 handles->clear();
3782 return;
3783}
3784
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003785status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003786 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003787 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3788 if (!valid()) return INVALID_OPERATION;
3789
Emilian Peevaebbe412018-01-15 13:53:24 +00003790 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003791 sp<device::V3_7::ICameraDeviceSession> hidlSession_3_7;
3792 auto castResult_3_7 = device::V3_7::ICameraDeviceSession::castFrom(mHidlSession);
3793 if (castResult_3_7.isOk()) {
3794 hidlSession_3_7 = castResult_3_7;
3795 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003796 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3797 if (castResult_3_4.isOk()) {
3798 hidlSession_3_4 = castResult_3_4;
3799 }
3800
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003801 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003802 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003803 hardware::hidl_vec<device::V3_7::CaptureRequest> captureRequests_3_7;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003804 size_t batchSize = requests.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003805 if (hidlSession_3_7 != nullptr) {
3806 captureRequests_3_7.resize(batchSize);
3807 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003808 captureRequests_3_4.resize(batchSize);
3809 } else {
3810 captureRequests.resize(batchSize);
3811 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003812 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003813 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003814
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003815 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003816 for (size_t i = 0; i < batchSize; i++) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003817 if (hidlSession_3_7 != nullptr) {
3818 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_7[i].v3_4.v3_2,
3819 /*out*/&handlesCreated, /*out*/&inflightBuffers);
3820 } else if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003821 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003822 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003823 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003824 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3825 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003826 }
3827 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003828 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003829 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003830 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003831 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003832 }
3833
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003834 std::vector<device::V3_2::BufferCache> cachesToRemove;
3835 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003836 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003837 for (auto& pair : mFreedBuffers) {
3838 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003839 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003840 cachesToRemove.push_back({pair.first, pair.second});
3841 }
3842 }
3843 mFreedBuffers.clear();
3844 }
3845
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003846 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3847 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003848
3849 // Write metadata to FMQ.
3850 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003851 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003852 device::V3_2::CaptureRequest* captureRequest;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003853 if (hidlSession_3_7 != nullptr) {
3854 captureRequest = &captureRequests_3_7[i].v3_4.v3_2;
3855 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003856 captureRequest = &captureRequests_3_4[i].v3_2;
3857 } else {
3858 captureRequest = &captureRequests[i];
3859 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003860
3861 if (request->settings != nullptr) {
3862 size_t settingsSize = get_camera_metadata_size(request->settings);
3863 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3864 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3865 captureRequest->settings.resize(0);
3866 captureRequest->fmqSettingsSize = settingsSize;
3867 } else {
3868 if (mRequestMetadataQueue != nullptr) {
3869 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3870 }
3871 captureRequest->settings.setToExternal(
3872 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3873 get_camera_metadata_size(request->settings));
3874 captureRequest->fmqSettingsSize = 0u;
3875 }
3876 } else {
3877 // A null request settings maps to a size-0 CameraMetadata
3878 captureRequest->settings.resize(0);
3879 captureRequest->fmqSettingsSize = 0u;
3880 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003881
Shuzhen Wang83bff122020-11-20 15:51:39 -08003882 // hidl session 3.7 specific handling.
3883 if (hidlSession_3_7 != nullptr) {
3884 captureRequests_3_7[i].inputWidth = request->input_width;
3885 captureRequests_3_7[i].inputHeight = request->input_height;
3886 }
3887
3888 // hidl session 3.7 and 3.4 specific handling.
3889 if (hidlSession_3_7 != nullptr || hidlSession_3_4 != nullptr) {
3890 hardware::hidl_vec<device::V3_4::PhysicalCameraSetting>& physicalCameraSettings =
3891 (hidlSession_3_7 != nullptr) ?
3892 captureRequests_3_7[i].v3_4.physicalCameraSettings :
3893 captureRequests_3_4[i].physicalCameraSettings;
3894 physicalCameraSettings.resize(request->num_physcam_settings);
Emilian Peevaebbe412018-01-15 13:53:24 +00003895 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003896 if (request->physcam_settings != nullptr) {
3897 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3898 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3899 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3900 settingsSize)) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08003901 physicalCameraSettings[j].settings.resize(0);
3902 physicalCameraSettings[j].fmqSettingsSize = settingsSize;
Emilian Peev00420d22018-02-05 21:33:13 +00003903 } else {
3904 if (mRequestMetadataQueue != nullptr) {
3905 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3906 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003907 physicalCameraSettings[j].settings.setToExternal(
Emilian Peev00420d22018-02-05 21:33:13 +00003908 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3909 request->physcam_settings[j])),
3910 get_camera_metadata_size(request->physcam_settings[j]));
Shuzhen Wang83bff122020-11-20 15:51:39 -08003911 physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003912 }
Emilian Peev00420d22018-02-05 21:33:13 +00003913 } else {
Yin-Chia Yeha2849702021-03-10 10:11:33 -08003914 physicalCameraSettings[j].fmqSettingsSize = 0u;
3915 physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003916 }
Shuzhen Wang83bff122020-11-20 15:51:39 -08003917 physicalCameraSettings[j].physicalCameraId = request->physcam_id[j];
Emilian Peevaebbe412018-01-15 13:53:24 +00003918 }
3919 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003920 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003921
3922 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003923 auto resultCallback =
3924 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3925 status = s;
3926 *numRequestProcessed = n;
3927 };
Shuzhen Wang83bff122020-11-20 15:51:39 -08003928 if (hidlSession_3_7 != nullptr) {
3929 err = hidlSession_3_7->processCaptureRequest_3_7(captureRequests_3_7, cachesToRemove,
3930 resultCallback);
3931 } else if (hidlSession_3_4 != nullptr) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003933 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003934 } else {
3935 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003936 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003937 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003938 if (!err.isOk()) {
3939 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003940 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003941 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003942
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003943 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3944 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3945 __FUNCTION__, *numRequestProcessed, batchSize);
3946 status = common::V1_0::Status::INTERNAL_ERROR;
3947 }
3948
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003949 res = CameraProviderManager::mapToStatusT(status);
3950 if (res == OK) {
3951 if (mHidlSession->isRemote()) {
3952 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3953 // sent to camera HAL processes)
3954 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3955 } else {
3956 // In passthrough mode the FDs are now owned by HAL
3957 cleanupNativeHandles(&handlesCreated);
3958 }
3959 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003960 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003961 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003962 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003963 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003964}
3965
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003966status_t Camera3Device::HalInterface::flush() {
3967 ATRACE_NAME("CameraHal::flush");
3968 if (!valid()) return INVALID_OPERATION;
3969 status_t res = OK;
3970
Emilian Peev31abd0a2017-05-11 18:37:46 +01003971 auto err = mHidlSession->flush();
3972 if (!err.isOk()) {
3973 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3974 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003975 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003976 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003978
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979 return res;
3980}
3981
Emilian Peev31abd0a2017-05-11 18:37:46 +01003982status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003983 ATRACE_NAME("CameraHal::dump");
3984 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003985
Emilian Peev31abd0a2017-05-11 18:37:46 +01003986 // Handled by CameraProviderManager::dump
3987
3988 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989}
3990
3991status_t Camera3Device::HalInterface::close() {
3992 ATRACE_NAME("CameraHal::close()");
3993 if (!valid()) return INVALID_OPERATION;
3994 status_t res = OK;
3995
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996 auto err = mHidlSession->close();
3997 // Interface will be dead shortly anyway, so don't log errors
3998 if (!err.isOk()) {
3999 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 return res;
4003}
4004
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004005void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4006 ATRACE_NAME("CameraHal::signalPipelineDrain");
4007 if (!valid() || mHidlSession_3_5 == nullptr) {
4008 ALOGE("%s called on invalid camera!", __FUNCTION__);
4009 return;
4010 }
4011
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004012 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004013 if (!err.isOk()) {
4014 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4015 return;
4016 }
4017}
4018
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004019status_t Camera3Device::HalInterface::switchToOffline(
4020 const std::vector<int32_t>& streamsToKeep,
4021 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004022 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4023 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004024 ATRACE_NAME("CameraHal::switchToOffline");
4025 if (!valid() || mHidlSession_3_6 == nullptr) {
4026 ALOGE("%s called on invalid camera!", __FUNCTION__);
4027 return INVALID_OPERATION;
4028 }
4029
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004030 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
4031 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004032 return INVALID_OPERATION;
4033 }
4034
4035 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004036 auto resultCallback =
4037 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4038 status = s;
4039 *offlineSessionInfo = info;
4040 *offlineSession = session;
4041 };
4042 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4043
4044 if (!err.isOk()) {
4045 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4046 return DEAD_OBJECT;
4047 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004048
4049 status_t ret = CameraProviderManager::mapToStatusT(status);
4050 if (ret != OK) {
4051 return ret;
4052 }
4053
4054 // TODO: assert no ongoing requestBuffer/returnBuffer call here
4055 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
4056 // returns from switchToOffline.
4057
4058
4059 // Validate buffer caches
4060 std::vector<int32_t> streams;
4061 streams.reserve(offlineSessionInfo->offlineStreams.size());
4062 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
4063 int32_t id = offlineStream.id;
4064 streams.push_back(id);
4065 // Verify buffer caches
4066 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
4067 offlineStream.circulatingBufferIds.end());
4068 if (!verifyBufferIds(id, bufIds)) {
4069 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
4070 return UNKNOWN_ERROR;
4071 }
4072 }
4073
4074 // Move buffer records
4075 bufferRecords->takeBufferCaches(mBufferRecords, streams);
4076 bufferRecords->takeInflightBufferMap(mBufferRecords);
4077 bufferRecords->takeRequestedBufferMap(mBufferRecords);
4078 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004079}
4080
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004081void Camera3Device::HalInterface::getInflightBufferKeys(
4082 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004083 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004084 return;
4085}
4086
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004087void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4088 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004089 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004090 return;
4091}
4092
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004093bool Camera3Device::HalInterface::verifyBufferIds(
4094 int32_t streamId, std::vector<uint64_t>& bufIds) {
4095 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004096}
4097
4098status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004099 int32_t frameNumber, int32_t streamId,
4100 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004101 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004102}
4103
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004104status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004105 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004106 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004107}
4108
4109// Find and pop a buffer_handle_t based on bufferId
4110status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004111 uint64_t bufferId,
4112 /*out*/ buffer_handle_t** buffer,
4113 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004114 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004115}
4116
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004117std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4118 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004120}
4121
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004122void Camera3Device::HalInterface::onBufferFreed(
4123 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004124 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
4125 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4126 if (bufferId != BUFFER_ID_NO_BUFFER) {
4127 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004128 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004129}
4130
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004131void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004132 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
4133 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
4134 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004135 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4136 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004137}
4138
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004139/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004140 * RequestThread inner class methods
4141 */
4142
4143Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004144 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004145 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4146 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004147 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004148 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004149 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004150 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004151 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004152 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07004153 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004154 mReconfigured(false),
4155 mDoPause(false),
4156 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004157 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004158 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004159 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004160 mCurrentAfTriggerId(0),
4161 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004162 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004163 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004164 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004165 mRepeatingLastFrameNumber(
4166 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004167 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004168 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004169 mRequestLatency(kRequestLatencyBinSize),
4170 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004171 mLatestSessionParams(sessionParamKeys.size()),
4172 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004173 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004174}
4175
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004176Camera3Device::RequestThread::~RequestThread() {}
4177
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004178void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004179 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004180 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004181 Mutex::Autolock l(mRequestLock);
4182 mListener = listener;
4183}
4184
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004185void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08004186 const CameraMetadata& sessionParams,
4187 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004188 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004189 Mutex::Autolock l(mRequestLock);
4190 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004191 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08004192 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004193 // Prepare video stream for high speed recording.
4194 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004195 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196}
4197
Jianing Wei90e59c92014-03-12 18:29:36 -07004198status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004199 List<sp<CaptureRequest> > &requests,
4200 /*out*/
4201 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004202 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004203 Mutex::Autolock l(mRequestLock);
4204 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4205 ++it) {
4206 mRequestQueue.push_back(*it);
4207 }
4208
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004209 if (lastFrameNumber != NULL) {
4210 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4211 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4212 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4213 *lastFrameNumber);
4214 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004215
Jianing Wei90e59c92014-03-12 18:29:36 -07004216 unpauseForNewRequests();
4217
4218 return OK;
4219}
4220
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004221
4222status_t Camera3Device::RequestThread::queueTrigger(
4223 RequestTrigger trigger[],
4224 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004225 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004226 Mutex::Autolock l(mTriggerMutex);
4227 status_t ret;
4228
4229 for (size_t i = 0; i < count; ++i) {
4230 ret = queueTriggerLocked(trigger[i]);
4231
4232 if (ret != OK) {
4233 return ret;
4234 }
4235 }
4236
4237 return OK;
4238}
4239
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004240const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4241 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004242 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004243 if (d != nullptr) return d->mId;
4244 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004245}
4246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004247status_t Camera3Device::RequestThread::queueTriggerLocked(
4248 RequestTrigger trigger) {
4249
4250 uint32_t tag = trigger.metadataTag;
4251 ssize_t index = mTriggerMap.indexOfKey(tag);
4252
4253 switch (trigger.getTagType()) {
4254 case TYPE_BYTE:
4255 // fall-through
4256 case TYPE_INT32:
4257 break;
4258 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004259 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4260 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004261 return INVALID_OPERATION;
4262 }
4263
4264 /**
4265 * Collect only the latest trigger, since we only have 1 field
4266 * in the request settings per trigger tag, and can't send more than 1
4267 * trigger per request.
4268 */
4269 if (index != NAME_NOT_FOUND) {
4270 mTriggerMap.editValueAt(index) = trigger;
4271 } else {
4272 mTriggerMap.add(tag, trigger);
4273 }
4274
4275 return OK;
4276}
4277
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004278status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004279 const RequestList &requests,
4280 /*out*/
4281 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004282 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004283 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004284 if (lastFrameNumber != NULL) {
4285 *lastFrameNumber = mRepeatingLastFrameNumber;
4286 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004287 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07004288 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004289 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4290 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004291
4292 unpauseForNewRequests();
4293
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004294 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 return OK;
4296}
4297
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004298bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004299 if (mRepeatingRequests.empty()) {
4300 return false;
4301 }
4302 int32_t requestId = requestIn->mResultExtras.requestId;
4303 const RequestList &repeatRequests = mRepeatingRequests;
4304 // All repeating requests are guaranteed to have same id so only check first quest
4305 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4306 return (firstRequest->mResultExtras.requestId == requestId);
4307}
4308
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004309status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004310 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004312 return clearRepeatingRequestsLocked(lastFrameNumber);
4313
4314}
4315
4316status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004318 if (lastFrameNumber != NULL) {
4319 *lastFrameNumber = mRepeatingLastFrameNumber;
4320 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004321 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 return OK;
4323}
4324
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004325status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004326 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004327 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004328 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004329 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004330
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004331 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004332
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004333 // Send errors for all requests pending in the request queue, including
4334 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004335 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004336 if (listener != NULL) {
4337 for (RequestList::iterator it = mRequestQueue.begin();
4338 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004339 // Abort the input buffers for reprocess requests.
4340 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004341 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004342 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004343 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004344 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004345 if (res != OK) {
4346 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4347 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4348 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004349 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004350 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4351 if (res != OK) {
4352 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4353 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4354 }
4355 }
4356 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004357 // Set the frame number this request would have had, if it
4358 // had been submitted; this frame number will not be reused.
4359 // The requestId and burstId fields were set when the request was
4360 // submitted originally (in convertMetadataListToRequestListLocked)
4361 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004362 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004363 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004364 }
4365 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004366 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004367
4368 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004369 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004370 if (lastFrameNumber != NULL) {
4371 *lastFrameNumber = mRepeatingLastFrameNumber;
4372 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004373 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004374 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004375 return OK;
4376}
4377
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004378status_t Camera3Device::RequestThread::flush() {
4379 ATRACE_CALL();
4380 Mutex::Autolock l(mFlushLock);
4381
Emilian Peev08dd2452017-04-06 16:55:14 +01004382 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004383}
4384
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004385void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004386 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004387 Mutex::Autolock l(mPauseLock);
4388 mDoPause = paused;
4389 mDoPauseSignal.signal();
4390}
4391
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004392status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4393 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004394 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004395 Mutex::Autolock l(mLatestRequestMutex);
4396 status_t res;
4397 while (mLatestRequestId != requestId) {
4398 nsecs_t startTime = systemTime();
4399
4400 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4401 if (res != OK) return res;
4402
4403 timeout -= (systemTime() - startTime);
4404 }
4405
4406 return OK;
4407}
4408
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004409void Camera3Device::RequestThread::requestExit() {
4410 // Call parent to set up shutdown
4411 Thread::requestExit();
4412 // The exit from any possible waits
4413 mDoPauseSignal.signal();
4414 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004415
4416 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4417 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004418}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004419
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004420void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004421 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004422 bool surfaceAbandoned = false;
4423 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004424 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004425 {
4426 Mutex::Autolock l(mRequestLock);
4427 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4428 // repeating requests.
4429 for (const auto& request : mRepeatingRequests) {
4430 for (const auto& s : request->mOutputStreams) {
4431 if (s->isAbandoned()) {
4432 surfaceAbandoned = true;
4433 clearRepeatingRequestsLocked(&lastFrameNumber);
4434 break;
4435 }
4436 }
4437 if (surfaceAbandoned) {
4438 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004439 }
4440 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004441 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004442 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004443
4444 if (listener != NULL && surfaceAbandoned) {
4445 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004446 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004447}
4448
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004449bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004450 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004451 status_t res;
4452 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004453 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004454 uint32_t numRequestProcessed = 0;
4455 for (size_t i = 0; i < batchSize; i++) {
4456 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004457 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004458 }
4459
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004460 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4461
4462 bool triggerRemoveFailed = false;
4463 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4464 for (size_t i = 0; i < numRequestProcessed; i++) {
4465 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4466 nextRequest.submitted = true;
4467
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004468 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004469
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004470 if (!triggerRemoveFailed) {
4471 // Remove any previously queued triggers (after unlock)
4472 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4473 if (removeTriggerRes != OK) {
4474 triggerRemoveFailed = true;
4475 triggerFailedRequest = nextRequest;
4476 }
4477 }
4478 }
4479
4480 if (triggerRemoveFailed) {
4481 SET_ERR("RequestThread: Unable to remove triggers "
4482 "(capture request %d, HAL device: %s (%d)",
4483 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4484 cleanUpFailedRequests(/*sendRequestError*/ false);
4485 return false;
4486 }
4487
4488 if (res != OK) {
4489 // Should only get a failure here for malformed requests or device-level
4490 // errors, so consider all errors fatal. Bad metadata failures should
4491 // come through notify.
4492 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4493 mNextRequests[numRequestProcessed].halRequest.frame_number,
4494 strerror(-res), res);
4495 cleanUpFailedRequests(/*sendRequestError*/ false);
4496 return false;
4497 }
4498 return true;
4499}
4500
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004501nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4502 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4503 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4504 find_camera_metadata_ro_entry(request,
4505 ANDROID_CONTROL_AE_MODE,
4506 &e);
4507 if (e.count == 0) return maxExpectedDuration;
4508
4509 switch (e.data.u8[0]) {
4510 case ANDROID_CONTROL_AE_MODE_OFF:
4511 find_camera_metadata_ro_entry(request,
4512 ANDROID_SENSOR_EXPOSURE_TIME,
4513 &e);
4514 if (e.count > 0) {
4515 maxExpectedDuration = e.data.i64[0];
4516 }
4517 find_camera_metadata_ro_entry(request,
4518 ANDROID_SENSOR_FRAME_DURATION,
4519 &e);
4520 if (e.count > 0) {
4521 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4522 }
4523 break;
4524 default:
4525 find_camera_metadata_ro_entry(request,
4526 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4527 &e);
4528 if (e.count > 1) {
4529 maxExpectedDuration = 1e9 / e.data.u8[0];
4530 }
4531 break;
4532 }
4533
4534 return maxExpectedDuration;
4535}
4536
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004537bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4538 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4539 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4540 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4541 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4542 return true;
4543 }
4544
4545 return false;
4546}
4547
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004548void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4549 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08004550 camera_capture_request_t& halRequest = nextRequest.halRequest;
4551 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004552 Mutex::Autolock al(mLatestRequestMutex);
4553
Shuzhen Wang83bff122020-11-20 15:51:39 -08004554 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004555 mLatestRequest.acquire(cloned);
4556
4557 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08004558 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
4559 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
4560 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004561 CameraMetadata(cloned));
4562 }
4563
4564 sp<Camera3Device> parent = mParent.promote();
4565 if (parent != NULL) {
4566 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08004567 halRequest.frame_number,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004568 0, mLatestRequest, mLatestPhysicalRequest);
4569 }
4570 }
4571
Shuzhen Wang83bff122020-11-20 15:51:39 -08004572 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004573 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08004574 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004575 }
4576
Shuzhen Wang83bff122020-11-20 15:51:39 -08004577 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004578}
4579
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004580bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4581 ATRACE_CALL();
4582 bool updatesDetected = false;
4583
Emilian Peev4ec17882019-01-24 17:16:58 -08004584 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004585 for (auto tag : mSessionParamKeys) {
4586 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004587 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004588
4589 if (entry.count > 0) {
4590 bool isDifferent = false;
4591 if (lastEntry.count > 0) {
4592 // Have a last value, compare to see if changed
4593 if (lastEntry.type == entry.type &&
4594 lastEntry.count == entry.count) {
4595 // Same type and count, compare values
4596 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4597 size_t entryBytes = bytesPerValue * lastEntry.count;
4598 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4599 if (cmp != 0) {
4600 isDifferent = true;
4601 }
4602 } else {
4603 // Count or type has changed
4604 isDifferent = true;
4605 }
4606 } else {
4607 // No last entry, so always consider to be different
4608 isDifferent = true;
4609 }
4610
4611 if (isDifferent) {
4612 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004613 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4614 updatesDetected = true;
4615 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004616 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004617 }
4618 } else if (lastEntry.count > 0) {
4619 // Value has been removed
4620 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004621 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004622 updatesDetected = true;
4623 }
4624 }
4625
Emilian Peev4ec17882019-01-24 17:16:58 -08004626 bool reconfigureRequired;
4627 if (updatesDetected) {
4628 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4629 updatedParams);
4630 mLatestSessionParams = updatedParams;
4631 } else {
4632 reconfigureRequired = false;
4633 }
4634
4635 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004636}
4637
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004638bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004639 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004640 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004641 // Any function called from threadLoop() must not hold mInterfaceLock since
4642 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4643 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004644
4645 // Handle paused state.
4646 if (waitIfPaused()) {
4647 return true;
4648 }
4649
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004650 // Wait for the next batch of requests.
4651 waitForNextRequestBatch();
4652 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004653 return true;
4654 }
4655
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004656 // Get the latest request ID, if any
4657 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004658 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004659 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004660 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004661 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004662 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004663 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4664 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004665 }
4666
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004667 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4668 // or a single request from streaming or burst. In either case the first element
4669 // should contain the latest camera settings that we need to check for any session
4670 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004671 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004672 res = OK;
4673
4674 //Input stream buffers are already acquired at this point so an input stream
4675 //will not be able to move to idle state unless we force it.
4676 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4677 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4678 if (res != OK) {
4679 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4680 cleanUpFailedRequests(/*sendRequestError*/ false);
4681 return false;
4682 }
4683 }
4684
4685 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004686 sp<Camera3Device> parent = mParent.promote();
4687 if (parent != nullptr) {
4688 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004689 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004690 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004691
4692 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4693 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4694 if (res != OK) {
4695 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4696 cleanUpFailedRequests(/*sendRequestError*/ false);
4697 return false;
4698 }
4699 }
4700 }
4701 }
4702
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004703 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004704 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004705 if (res == TIMED_OUT) {
4706 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004708 // Check if any stream is abandoned.
4709 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004710 return true;
4711 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004712 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004713 return false;
4714 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004715
Zhijun Hecc27e112013-10-03 16:12:43 -07004716 // Inform waitUntilRequestProcessed thread of a new request ID
4717 {
4718 Mutex::Autolock al(mLatestRequestMutex);
4719
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004720 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004721 mLatestRequestSignal.signal();
4722 }
4723
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004724 // Submit a batch of requests to HAL.
4725 // Use flush lock only when submitting multilple requests in a batch.
4726 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4727 // which may take a long time to finish so synchronizing flush() and
4728 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4729 // For now, only synchronize for high speed recording and we should figure something out for
4730 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004731 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004732
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004733 if (useFlushLock) {
4734 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004735 }
4736
Zhijun Hef0645c12016-08-02 00:58:11 -07004737 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004738 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004739
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004740 sp<Camera3Device> parent = mParent.promote();
4741 if (parent != nullptr) {
4742 parent->mRequestBufferSM.onSubmittingRequest();
4743 }
4744
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004745 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004746 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004747 submitRequestSuccess = sendRequestsBatch();
4748
Shuzhen Wang686f6442017-06-20 16:16:04 -07004749 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4750 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004751
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004752 if (useFlushLock) {
4753 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004754 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004755
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004756 // Unset as current request
4757 {
4758 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004759 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004760 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004761 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004762
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004763 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004764}
4765
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004766status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004767 ATRACE_CALL();
4768
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004769 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004770 for (size_t i = 0; i < mNextRequests.size(); i++) {
4771 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004772 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004773 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4774 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004775
4776 // Prepare a request to HAL
4777 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4778
4779 // Insert any queued triggers (before metadata is locked)
4780 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004781 if (res < 0) {
4782 SET_ERR("RequestThread: Unable to insert triggers "
4783 "(capture request %d, HAL device: %s (%d)",
4784 halRequest->frame_number, strerror(-res), res);
4785 return INVALID_OPERATION;
4786 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004787
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004788 int triggerCount = res;
4789 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4790 mPrevTriggers = triggerCount;
4791
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004792 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004793 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004794
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004795 // If the request is the same as last, or we had triggers now or last time or
4796 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004797 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004798 (mPrevRequest != captureRequest || triggersMixedIn ||
4799 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004800 // Request settings are all the same within one batch, so only treat the first
4801 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004802 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004803 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004804 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004805 /**
4806 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004807 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004809 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004810 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004811 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004812 "(capture request %d, HAL device: %s (%d)",
4813 halRequest->frame_number, strerror(-res), res);
4814 return INVALID_OPERATION;
4815 }
4816
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004817 {
4818 // Correct metadata regions for distortion correction if enabled
4819 sp<Camera3Device> parent = mParent.promote();
4820 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004821 List<PhysicalCameraSettings>::iterator it;
4822 for (it = captureRequest->mSettingsList.begin();
4823 it != captureRequest->mSettingsList.end(); it++) {
4824 if (parent->mDistortionMappers.find(it->cameraId) ==
4825 parent->mDistortionMappers.end()) {
4826 continue;
4827 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004828
4829 if (!captureRequest->mDistortionCorrectionUpdated) {
4830 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4831 &(it->metadata));
4832 if (res != OK) {
4833 SET_ERR("RequestThread: Unable to correct capture requests "
4834 "for lens distortion for request %d: %s (%d)",
4835 halRequest->frame_number, strerror(-res), res);
4836 return INVALID_OPERATION;
4837 }
4838 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004839 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004840 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004841
4842 for (it = captureRequest->mSettingsList.begin();
4843 it != captureRequest->mSettingsList.end(); it++) {
4844 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4845 parent->mZoomRatioMappers.end()) {
4846 continue;
4847 }
4848
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004849 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004850 cameraIdsWithZoom.insert(it->cameraId);
4851 }
4852
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004853 if (!captureRequest->mZoomRatioUpdated) {
4854 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4855 &(it->metadata));
4856 if (res != OK) {
4857 SET_ERR("RequestThread: Unable to correct capture requests "
4858 "for zoom ratio for request %d: %s (%d)",
4859 halRequest->frame_number, strerror(-res), res);
4860 return INVALID_OPERATION;
4861 }
4862 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004863 }
4864 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004865 if (captureRequest->mRotateAndCropAuto &&
4866 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004867 for (it = captureRequest->mSettingsList.begin();
4868 it != captureRequest->mSettingsList.end(); it++) {
4869 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4870 if (mapper != parent->mRotateAndCropMappers.end()) {
4871 res = mapper->second.updateCaptureRequest(&(it->metadata));
4872 if (res != OK) {
4873 SET_ERR("RequestThread: Unable to correct capture requests "
4874 "for rotate-and-crop for request %d: %s (%d)",
4875 halRequest->frame_number, strerror(-res), res);
4876 return INVALID_OPERATION;
4877 }
4878 }
4879 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004880 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004881 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004882 }
4883 }
4884
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004885 /**
4886 * The request should be presorted so accesses in HAL
4887 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4888 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004889 captureRequest->mSettingsList.begin()->metadata.sort();
4890 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004891 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004892 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004893 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4894
4895 IF_ALOGV() {
4896 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4897 find_camera_metadata_ro_entry(
4898 halRequest->settings,
4899 ANDROID_CONTROL_AF_TRIGGER,
4900 &e
4901 );
4902 if (e.count > 0) {
4903 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4904 __FUNCTION__,
4905 halRequest->frame_number,
4906 e.data.u8[0]);
4907 }
4908 }
4909 } else {
4910 // leave request.settings NULL to indicate 'reuse latest given'
4911 ALOGVV("%s: Request settings are REUSED",
4912 __FUNCTION__);
4913 }
4914
Emilian Peevaebbe412018-01-15 13:53:24 +00004915 if (captureRequest->mSettingsList.size() > 1) {
4916 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4917 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004918 if (newRequest) {
4919 halRequest->physcam_settings =
4920 new const camera_metadata* [halRequest->num_physcam_settings];
4921 } else {
4922 halRequest->physcam_settings = nullptr;
4923 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004924 auto it = ++captureRequest->mSettingsList.begin();
4925 size_t i = 0;
4926 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4927 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004928 if (newRequest) {
4929 it->metadata.sort();
4930 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4931 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004932 }
4933 }
4934
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004935 uint32_t totalNumBuffers = 0;
4936
4937 // Fill in buffers
4938 if (captureRequest->mInputStream != NULL) {
4939 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08004940
4941 halRequest->input_width = captureRequest->mInputBufferSize.width;
4942 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004943 totalNumBuffers += 1;
4944 } else {
4945 halRequest->input_buffer = NULL;
4946 }
4947
Emilian Peevf4816702020-04-03 15:44:51 -07004948 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004949 captureRequest->mOutputStreams.size());
4950 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08004951 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004952
4953 sp<Camera3Device> parent = mParent.promote();
4954 if (parent == NULL) {
4955 // Should not happen, and nowhere to send errors to, so just log it
4956 CLOGE("RequestThread: Parent is gone");
4957 return INVALID_OPERATION;
4958 }
4959 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4960
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004961 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004962 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004963 sp<Camera3OutputStreamInterface> outputStream =
4964 captureRequest->mOutputStreams.editItemAt(j);
4965 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004966
4967 // Prepare video buffers for high speed recording on the first video request.
4968 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4969 // Only try to prepare video stream on the first video request.
4970 mPrepareVideoStream = false;
4971
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004972 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4973 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004974 while (res == NOT_ENOUGH_DATA) {
4975 res = outputStream->prepareNextBuffer();
4976 }
4977 if (res != OK) {
4978 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4979 __FUNCTION__, strerror(-res), res);
4980 outputStream->cancelPrepare();
4981 }
4982 }
4983
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004984 std::vector<size_t> uniqueSurfaceIds;
4985 res = outputStream->getUniqueSurfaceIds(
4986 captureRequest->mOutputSurfaces[streamId],
4987 &uniqueSurfaceIds);
4988 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4989 if (res != OK && res != INVALID_OPERATION) {
4990 ALOGE("%s: failed to query stream %d unique surface IDs",
4991 __FUNCTION__, streamId);
4992 return res;
4993 }
4994 if (res == OK) {
4995 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4996 }
4997
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004998 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004999 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005000 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005001 return TIMED_OUT;
5002 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005003 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07005004 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005005 buffer.stream = outputStream->asHalStream();
5006 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07005007 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005008 buffer.acquire_fence = -1;
5009 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08005010 // Mark the output stream as unpreparable to block clients from calling
5011 // 'prepare' after this request reaches CameraHal and before the respective
5012 // buffers are requested.
5013 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005014 } else {
5015 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5016 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005017 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005018 if (res != OK) {
5019 // Can't get output buffer from gralloc queue - this could be due to
5020 // abandoned queue or other consumer misbehavior, so not a fatal
5021 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005022 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005023 " %s (%d)", strerror(-res), res);
5024
5025 return TIMED_OUT;
5026 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005027 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005028
5029 {
5030 sp<Camera3Device> parent = mParent.promote();
5031 if (parent != nullptr) {
5032 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5033 for (const auto& settings : captureRequest->mSettingsList) {
5034 if ((streamCameraId.isEmpty() &&
5035 parent->getId() == settings.cameraId.c_str()) ||
5036 streamCameraId == settings.cameraId.c_str()) {
5037 outputStream->fireBufferRequestForFrameNumber(
5038 captureRequest->mResultExtras.frameNumber,
5039 settings.metadata);
5040 }
5041 }
5042 }
5043 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005044
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005045 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08005046 int32_t streamGroupId = outputStream->getHalStreamGroupId();
5047 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
5048 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
5049 } else if (!physicalCameraId.isEmpty()) {
5050 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005051 }
5052 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005053 }
5054 totalNumBuffers += halRequest->num_output_buffers;
5055
5056 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005057 // If this request list is for constrained high speed recording (not
5058 // preview), and the current request is not the last one in the batch,
5059 // do not send callback to the app.
5060 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005061 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005062 hasCallback = false;
5063 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005064 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005065 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005066 const camera_metadata_t* settings = halRequest->settings;
5067 bool shouldUnlockSettings = false;
5068 if (settings == nullptr) {
5069 shouldUnlockSettings = true;
5070 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
5071 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005072 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5073 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005074 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01005075 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5076 isStillCapture = true;
5077 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5078 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005079
Emilian Peevaf8416e2021-02-04 17:52:43 -08005080 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005081 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005082 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5083 isZslCapture = true;
5084 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005085 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005086 res = parent->registerInFlight(halRequest->frame_number,
5087 totalNumBuffers, captureRequest->mResultExtras,
5088 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005089 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005090 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005091 requestedPhysicalCameras, isStillCapture, isZslCapture,
5092 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005093 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07005094 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005095 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5096 ", burstId = %" PRId32 ".",
5097 __FUNCTION__,
5098 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5099 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08005100
5101 if (shouldUnlockSettings) {
5102 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
5103 }
5104
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005105 if (res != OK) {
5106 SET_ERR("RequestThread: Unable to register new in-flight request:"
5107 " %s (%d)", strerror(-res), res);
5108 return INVALID_OPERATION;
5109 }
5110 }
5111
5112 return OK;
5113}
5114
Igor Murashkin1e479c02013-09-06 16:55:14 -07005115CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005116 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005117 Mutex::Autolock al(mLatestRequestMutex);
5118
5119 ALOGV("RequestThread::%s", __FUNCTION__);
5120
5121 return mLatestRequest;
5122}
5123
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005124bool Camera3Device::RequestThread::isStreamPending(
5125 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005126 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005127 Mutex::Autolock l(mRequestLock);
5128
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005129 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005130 if (!nextRequest.submitted) {
5131 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5132 if (stream == s) return true;
5133 }
5134 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005135 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005136 }
5137
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005138 for (const auto& request : mRequestQueue) {
5139 for (const auto& s : request->mOutputStreams) {
5140 if (stream == s) return true;
5141 }
5142 if (stream == request->mInputStream) return true;
5143 }
5144
5145 for (const auto& request : mRepeatingRequests) {
5146 for (const auto& s : request->mOutputStreams) {
5147 if (stream == s) return true;
5148 }
5149 if (stream == request->mInputStream) return true;
5150 }
5151
5152 return false;
5153}
Jianing Weicb0652e2014-03-12 18:29:36 -07005154
Emilian Peev40ead602017-09-26 15:46:36 +01005155bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5156 ATRACE_CALL();
5157 Mutex::Autolock l(mRequestLock);
5158
5159 for (const auto& nextRequest : mNextRequests) {
5160 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5161 if (s.first == streamId) {
5162 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5163 if (it != s.second.end()) {
5164 return true;
5165 }
5166 }
5167 }
5168 }
5169
5170 for (const auto& request : mRequestQueue) {
5171 for (const auto& s : request->mOutputSurfaces) {
5172 if (s.first == streamId) {
5173 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5174 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005175 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005176 }
5177 }
5178 }
5179 }
5180
5181 for (const auto& request : mRepeatingRequests) {
5182 for (const auto& s : request->mOutputSurfaces) {
5183 if (s.first == streamId) {
5184 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5185 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005186 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005187 }
5188 }
5189 }
5190 }
5191
5192 return false;
5193}
5194
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005195void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5196 if (!mUseHalBufManager) {
5197 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5198 return;
5199 }
5200
5201 Mutex::Autolock pl(mPauseLock);
5202 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005203 mInterface->signalPipelineDrain(streamIds);
5204 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005205 }
5206 // If request thread is still busy, wait until paused then notify HAL
5207 mNotifyPipelineDrain = true;
5208 mStreamIdsToBeDrained = streamIds;
5209}
5210
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07005211void Camera3Device::RequestThread::resetPipelineDrain() {
5212 Mutex::Autolock pl(mPauseLock);
5213 mNotifyPipelineDrain = false;
5214 mStreamIdsToBeDrained.clear();
5215}
5216
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005217void Camera3Device::RequestThread::clearPreviousRequest() {
5218 Mutex::Autolock l(mRequestLock);
5219 mPrevRequest.clear();
5220}
5221
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005222status_t Camera3Device::RequestThread::switchToOffline(
5223 const std::vector<int32_t>& streamsToKeep,
5224 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005225 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
5226 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005227 Mutex::Autolock l(mRequestLock);
5228 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5229
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005230 // Wait until request thread is fully stopped
5231 // TBD: check if request thread is being paused by other APIs (shouldn't be)
5232
5233 // We could also check for mRepeatingRequests.empty(), but the API interface
5234 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
5235 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005236 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5237 while (!queueEmpty) {
5238 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5239 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005240 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005241 return res;
5242 } else if (res != OK) {
5243 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5244 __FUNCTION__, strerror(-res), res);
5245 return res;
5246 }
5247 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5248 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005249
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005250 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005251 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005252}
5253
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005254status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
5255 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5256 ATRACE_CALL();
5257 Mutex::Autolock l(mTriggerMutex);
5258 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5259 return BAD_VALUE;
5260 }
5261 mRotateAndCropOverride = rotateAndCropValue;
5262 return OK;
5263}
5264
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005265status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005266 ATRACE_CALL();
5267 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005268 if (muteMode != mCameraMute) {
5269 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005270 mCameraMuteChanged = true;
5271 }
5272 return OK;
5273}
5274
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005275nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005276 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005277 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005278 return mExpectedInflightDuration > kMinInflightDuration ?
5279 mExpectedInflightDuration : kMinInflightDuration;
5280}
5281
Emilian Peevaebbe412018-01-15 13:53:24 +00005282void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07005283 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005284 if ((request == nullptr) || (halRequest == nullptr)) {
5285 ALOGE("%s: Invalid request!", __FUNCTION__);
5286 return;
5287 }
5288
5289 if (halRequest->num_physcam_settings > 0) {
5290 if (halRequest->physcam_id != nullptr) {
5291 delete [] halRequest->physcam_id;
5292 halRequest->physcam_id = nullptr;
5293 }
5294 if (halRequest->physcam_settings != nullptr) {
5295 auto it = ++(request->mSettingsList.begin());
5296 size_t i = 0;
5297 for (; it != request->mSettingsList.end(); it++, i++) {
5298 it->metadata.unlock(halRequest->physcam_settings[i]);
5299 }
5300 delete [] halRequest->physcam_settings;
5301 halRequest->physcam_settings = nullptr;
5302 }
5303 }
5304}
5305
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005306void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5307 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005308 return;
5309 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005310
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005311 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005312 // Skip the ones that have been submitted successfully.
5313 if (nextRequest.submitted) {
5314 continue;
5315 }
5316
5317 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07005318 camera_capture_request_t* halRequest = &nextRequest.halRequest;
5319 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005320
5321 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005322 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005323 }
5324
Emilian Peevaebbe412018-01-15 13:53:24 +00005325 cleanupPhysicalSettings(captureRequest, halRequest);
5326
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005327 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07005328 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005329 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5330 }
5331
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005332 // No output buffer can be returned when using HAL buffer manager
5333 if (!mUseHalBufManager) {
5334 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5335 //Buffers that failed processing could still have
5336 //valid acquire fence.
5337 int acquireFence = (*outputBuffers)[i].acquire_fence;
5338 if (0 <= acquireFence) {
5339 close(acquireFence);
5340 outputBuffers->editItemAt(i).acquire_fence = -1;
5341 }
Emilian Peevf4816702020-04-03 15:44:51 -07005342 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005343 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5344 /*timestampIncreasing*/true, std::vector<size_t> (),
5345 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005346 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005347 }
5348
5349 if (sendRequestError) {
5350 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005351 sp<NotificationListener> listener = mListener.promote();
5352 if (listener != NULL) {
5353 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005354 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 captureRequest->mResultExtras);
5356 }
5357 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005358
5359 // Remove yet-to-be submitted inflight request from inflightMap
5360 {
5361 sp<Camera3Device> parent = mParent.promote();
5362 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005363 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005364 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5365 if (idx >= 0) {
5366 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5367 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5368 parent->removeInFlightMapEntryLocked(idx);
5369 }
5370 }
5371 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005372 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005373
5374 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005375 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005376}
5377
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005378void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005379 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005380 // Optimized a bit for the simple steady-state case (single repeating
5381 // request), to avoid putting that request in the queue temporarily.
5382 Mutex::Autolock l(mRequestLock);
5383
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005384 assert(mNextRequests.empty());
5385
5386 NextRequest nextRequest;
5387 nextRequest.captureRequest = waitForNextRequestLocked();
5388 if (nextRequest.captureRequest == nullptr) {
5389 return;
5390 }
5391
Emilian Peevf4816702020-04-03 15:44:51 -07005392 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005393 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005394 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005395
5396 // Wait for additional requests
5397 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5398
5399 for (size_t i = 1; i < batchSize; i++) {
5400 NextRequest additionalRequest;
5401 additionalRequest.captureRequest = waitForNextRequestLocked();
5402 if (additionalRequest.captureRequest == nullptr) {
5403 break;
5404 }
5405
Emilian Peevf4816702020-04-03 15:44:51 -07005406 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005407 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005408 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005409 }
5410
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005411 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005412 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005413 mNextRequests.size(), batchSize);
5414 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005415 }
5416
5417 return;
5418}
5419
5420sp<Camera3Device::CaptureRequest>
5421 Camera3Device::RequestThread::waitForNextRequestLocked() {
5422 status_t res;
5423 sp<CaptureRequest> nextRequest;
5424
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005425 while (mRequestQueue.empty()) {
5426 if (!mRepeatingRequests.empty()) {
5427 // Always atomically enqueue all requests in a repeating request
5428 // list. Guarantees a complete in-sequence set of captures to
5429 // application.
5430 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005431 if (mFirstRepeating) {
5432 mFirstRepeating = false;
5433 } else {
5434 for (auto& request : requests) {
5435 // For repeating requests, override timestamp request using
5436 // the time a request is inserted into the request queue,
5437 // because the original repeating request will have an old
5438 // fixed timestamp.
5439 request->mRequestTimeNs = systemTime();
5440 }
5441 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005442 RequestList::const_iterator firstRequest =
5443 requests.begin();
5444 nextRequest = *firstRequest;
5445 mRequestQueue.insert(mRequestQueue.end(),
5446 ++firstRequest,
5447 requests.end());
5448 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005449
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005450 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005452 break;
5453 }
5454
5455 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005457 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5458 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005459 Mutex::Autolock pl(mPauseLock);
5460 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005461 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005462 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005463 if (mNotifyPipelineDrain) {
5464 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5465 mNotifyPipelineDrain = false;
5466 mStreamIdsToBeDrained.clear();
5467 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005468 // Let the tracker know
5469 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5470 if (statusTracker != 0) {
5471 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5472 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005473 sp<Camera3Device> parent = mParent.promote();
5474 if (parent != nullptr) {
5475 parent->mRequestBufferSM.onRequestThreadPaused();
5476 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005477 }
5478 // Stop waiting for now and let thread management happen
5479 return NULL;
5480 }
5481 }
5482
5483 if (nextRequest == NULL) {
5484 // Don't have a repeating request already in hand, so queue
5485 // must have an entry now.
5486 RequestList::iterator firstRequest =
5487 mRequestQueue.begin();
5488 nextRequest = *firstRequest;
5489 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005490 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5491 sp<NotificationListener> listener = mListener.promote();
5492 if (listener != NULL) {
5493 listener->notifyRequestQueueEmpty();
5494 }
5495 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005496 }
5497
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005498 // In case we've been unpaused by setPaused clearing mDoPause, need to
5499 // update internal pause state (capture/setRepeatingRequest unpause
5500 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005501 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005502 if (mPaused) {
5503 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5504 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5505 if (statusTracker != 0) {
5506 statusTracker->markComponentActive(mStatusId);
5507 }
5508 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005509 mPaused = false;
5510
5511 // Check if we've reconfigured since last time, and reset the preview
5512 // request if so. Can't use 'NULL request == repeat' across configure calls.
5513 if (mReconfigured) {
5514 mPrevRequest.clear();
5515 mReconfigured = false;
5516 }
5517
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005518 if (nextRequest != NULL) {
5519 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005520 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5521 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005522
5523 // Since RequestThread::clear() removes buffers from the input stream,
5524 // get the right buffer here before unlocking mRequestLock
5525 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08005526 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
5527 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005528 if (res != OK) {
5529 // Can't get input buffer from gralloc queue - this could be due to
5530 // disconnected queue or other producer misbehavior, so not a fatal
5531 // error
5532 ALOGE("%s: Can't get input buffer, skipping request:"
5533 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005534
5535 sp<NotificationListener> listener = mListener.promote();
5536 if (listener != NULL) {
5537 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005538 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005539 nextRequest->mResultExtras);
5540 }
5541 return NULL;
5542 }
5543 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005544 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005545
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005546 return nextRequest;
5547}
5548
5549bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005550 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005551 status_t res;
5552 Mutex::Autolock l(mPauseLock);
5553 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005554 if (mPaused == false) {
5555 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005556 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005557 if (mNotifyPipelineDrain) {
5558 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5559 mNotifyPipelineDrain = false;
5560 mStreamIdsToBeDrained.clear();
5561 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005562 // Let the tracker know
5563 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5564 if (statusTracker != 0) {
5565 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5566 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005567 sp<Camera3Device> parent = mParent.promote();
5568 if (parent != nullptr) {
5569 parent->mRequestBufferSM.onRequestThreadPaused();
5570 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005571 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005572
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005573 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005574 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005575 return true;
5576 }
5577 }
5578 // We don't set mPaused to false here, because waitForNextRequest needs
5579 // to further manage the paused state in case of starvation.
5580 return false;
5581}
5582
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005583void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005584 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005585 // With work to do, mark thread as unpaused.
5586 // If paused by request (setPaused), don't resume, to avoid
5587 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005588 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005589 Mutex::Autolock p(mPauseLock);
5590 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005591 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5592 if (mPaused) {
5593 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5594 if (statusTracker != 0) {
5595 statusTracker->markComponentActive(mStatusId);
5596 }
5597 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005598 mPaused = false;
5599 }
5600}
5601
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005602void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5603 sp<Camera3Device> parent = mParent.promote();
5604 if (parent != NULL) {
5605 va_list args;
5606 va_start(args, fmt);
5607
5608 parent->setErrorStateV(fmt, args);
5609
5610 va_end(args);
5611 }
5612}
5613
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005614status_t Camera3Device::RequestThread::insertTriggers(
5615 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005616 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005617 Mutex::Autolock al(mTriggerMutex);
5618
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005619 sp<Camera3Device> parent = mParent.promote();
5620 if (parent == NULL) {
5621 CLOGE("RequestThread: Parent is gone");
5622 return DEAD_OBJECT;
5623 }
5624
Emilian Peevaebbe412018-01-15 13:53:24 +00005625 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005626 size_t count = mTriggerMap.size();
5627
5628 for (size_t i = 0; i < count; ++i) {
5629 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005630 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005631
5632 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5633 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5634 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005635 if (isAeTrigger) {
5636 request->mResultExtras.precaptureTriggerId = triggerId;
5637 mCurrentPreCaptureTriggerId = triggerId;
5638 } else {
5639 request->mResultExtras.afTriggerId = triggerId;
5640 mCurrentAfTriggerId = triggerId;
5641 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005642 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005643 }
5644
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005645 camera_metadata_entry entry = metadata.find(tag);
5646
5647 if (entry.count > 0) {
5648 /**
5649 * Already has an entry for this trigger in the request.
5650 * Rewrite it with our requested trigger value.
5651 */
5652 RequestTrigger oldTrigger = trigger;
5653
5654 oldTrigger.entryValue = entry.data.u8[0];
5655
5656 mTriggerReplacedMap.add(tag, oldTrigger);
5657 } else {
5658 /**
5659 * More typical, no trigger entry, so we just add it
5660 */
5661 mTriggerRemovedMap.add(tag, trigger);
5662 }
5663
5664 status_t res;
5665
5666 switch (trigger.getTagType()) {
5667 case TYPE_BYTE: {
5668 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5669 res = metadata.update(tag,
5670 &entryValue,
5671 /*count*/1);
5672 break;
5673 }
5674 case TYPE_INT32:
5675 res = metadata.update(tag,
5676 &trigger.entryValue,
5677 /*count*/1);
5678 break;
5679 default:
5680 ALOGE("%s: Type not supported: 0x%x",
5681 __FUNCTION__,
5682 trigger.getTagType());
5683 return INVALID_OPERATION;
5684 }
5685
5686 if (res != OK) {
5687 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5688 ", value %d", __FUNCTION__, trigger.getTagName(),
5689 trigger.entryValue);
5690 return res;
5691 }
5692
5693 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5694 trigger.getTagName(),
5695 trigger.entryValue);
5696 }
5697
5698 mTriggerMap.clear();
5699
5700 return count;
5701}
5702
5703status_t Camera3Device::RequestThread::removeTriggers(
5704 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005705 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005706 Mutex::Autolock al(mTriggerMutex);
5707
Emilian Peevaebbe412018-01-15 13:53:24 +00005708 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005709
5710 /**
5711 * Replace all old entries with their old values.
5712 */
5713 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5714 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5715
5716 status_t res;
5717
5718 uint32_t tag = trigger.metadataTag;
5719 switch (trigger.getTagType()) {
5720 case TYPE_BYTE: {
5721 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5722 res = metadata.update(tag,
5723 &entryValue,
5724 /*count*/1);
5725 break;
5726 }
5727 case TYPE_INT32:
5728 res = metadata.update(tag,
5729 &trigger.entryValue,
5730 /*count*/1);
5731 break;
5732 default:
5733 ALOGE("%s: Type not supported: 0x%x",
5734 __FUNCTION__,
5735 trigger.getTagType());
5736 return INVALID_OPERATION;
5737 }
5738
5739 if (res != OK) {
5740 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5741 ", trigger value %d", __FUNCTION__,
5742 trigger.getTagName(), trigger.entryValue);
5743 return res;
5744 }
5745 }
5746 mTriggerReplacedMap.clear();
5747
5748 /**
5749 * Remove all new entries.
5750 */
5751 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5752 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5753 status_t res = metadata.erase(trigger.metadataTag);
5754
5755 if (res != OK) {
5756 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5757 ", trigger value %d", __FUNCTION__,
5758 trigger.getTagName(), trigger.entryValue);
5759 return res;
5760 }
5761 }
5762 mTriggerRemovedMap.clear();
5763
5764 return OK;
5765}
5766
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005767status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005768 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005769 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005770 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005771 status_t res;
5772
Emilian Peevaebbe412018-01-15 13:53:24 +00005773 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005774
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005775 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005776 // exists
5777 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5778 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5779 if (afTrigger.count > 0 &&
5780 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5781 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005782 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005783 if (res != OK) return res;
5784 }
5785
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005786 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005787 // if none already exists
5788 camera_metadata_entry pcTrigger =
5789 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5790 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5791 if (pcTrigger.count > 0 &&
5792 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5793 pcId.count == 0) {
5794 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005795 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005796 if (res != OK) return res;
5797 }
5798
5799 return OK;
5800}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005801
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005802bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5803 const sp<CaptureRequest> &request) {
5804 ATRACE_CALL();
5805
5806 if (request->mRotateAndCropAuto) {
5807 Mutex::Autolock l(mTriggerMutex);
5808 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5809
5810 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5811 if (rotateAndCropEntry.count > 0) {
5812 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5813 return false;
5814 } else {
5815 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5816 return true;
5817 }
5818 } else {
5819 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5820 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5821 &rotateAndCrop_u8, 1);
5822 return true;
5823 }
5824 }
5825 return false;
5826}
5827
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005828bool Camera3Device::RequestThread::overrideTestPattern(
5829 const sp<CaptureRequest> &request) {
5830 ATRACE_CALL();
5831
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005832 {
5833 sp<Camera3Device> parent = mParent.promote();
5834 if (parent != nullptr) {
5835 if (!parent->supportsCameraMute()) return false;
5836 }
5837 }
5838
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005839 Mutex::Autolock l(mTriggerMutex);
5840
5841 bool changed = false;
5842
5843 int32_t testPatternMode = request->mOriginalTestPatternMode;
5844 int32_t testPatternData[4] = {
5845 request->mOriginalTestPatternData[0],
5846 request->mOriginalTestPatternData[1],
5847 request->mOriginalTestPatternData[2],
5848 request->mOriginalTestPatternData[3]
5849 };
5850
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005851 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
5852 testPatternMode = mCameraMute;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005853 testPatternData[0] = 0;
5854 testPatternData[1] = 0;
5855 testPatternData[2] = 0;
5856 testPatternData[3] = 0;
5857 }
5858
5859 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5860
5861 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
5862 if (testPatternEntry.count > 0) {
5863 if (testPatternEntry.data.i32[0] != testPatternMode) {
5864 testPatternEntry.data.i32[0] = testPatternMode;
5865 changed = true;
5866 }
5867 } else {
5868 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
5869 &testPatternMode, 1);
5870 changed = true;
5871 }
5872
5873 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005874 if (testPatternColor.count >= 4) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005875 for (size_t i = 0; i < 4; i++) {
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005876 if (testPatternColor.data.i32[i] != testPatternData[i]) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005877 testPatternColor.data.i32[i] = testPatternData[i];
5878 changed = true;
5879 }
5880 }
5881 } else {
5882 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07005883 testPatternData, 4);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005884 changed = true;
5885 }
5886
5887 return changed;
5888}
5889
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005890status_t Camera3Device::RequestThread::setHalInterface(
5891 sp<HalInterface> newHalInterface) {
5892 if (newHalInterface.get() == nullptr) {
5893 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
5894 return DEAD_OBJECT;
5895 }
5896
5897 mInterface = newHalInterface;
5898
5899 return OK;
5900}
5901
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005902/**
5903 * PreparerThread inner class methods
5904 */
5905
5906Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005907 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005908 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005909}
5910
5911Camera3Device::PreparerThread::~PreparerThread() {
5912 Thread::requestExitAndWait();
5913 if (mCurrentStream != nullptr) {
5914 mCurrentStream->cancelPrepare();
5915 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5916 mCurrentStream.clear();
5917 }
5918 clear();
5919}
5920
Ruben Brunkc78ac262015-08-13 17:58:46 -07005921status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005922 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005923 status_t res;
5924
5925 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005926 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005927
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005928 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005929 if (res == OK) {
5930 // No preparation needed, fire listener right off
5931 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005932 if (listener != NULL) {
5933 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005934 }
5935 return OK;
5936 } else if (res != NOT_ENOUGH_DATA) {
5937 return res;
5938 }
5939
5940 // Need to prepare, start up thread if necessary
5941 if (!mActive) {
5942 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5943 // isn't running
5944 Thread::requestExitAndWait();
5945 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5946 if (res != OK) {
5947 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005948 if (listener != NULL) {
5949 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005950 }
5951 return res;
5952 }
5953 mCancelNow = false;
5954 mActive = true;
5955 ALOGV("%s: Preparer stream started", __FUNCTION__);
5956 }
5957
5958 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005959 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005960 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5961
5962 return OK;
5963}
5964
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005965void Camera3Device::PreparerThread::pause() {
5966 ATRACE_CALL();
5967
5968 Mutex::Autolock l(mLock);
5969
5970 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5971 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5972 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5973 int currentMaxCount = mCurrentMaxCount;
5974 mPendingStreams.clear();
5975 mCancelNow = true;
5976 while (mActive) {
5977 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5978 if (res == TIMED_OUT) {
5979 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5980 return;
5981 } else if (res != OK) {
5982 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5983 return;
5984 }
5985 }
5986
5987 //Check whether the prepare thread was able to complete the current
5988 //stream. In case work is still pending emplace it along with the rest
5989 //of the streams in the pending list.
5990 if (currentStream != nullptr) {
5991 if (!mCurrentPrepareComplete) {
5992 pendingStreams.emplace(currentMaxCount, currentStream);
5993 }
5994 }
5995
5996 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5997 for (const auto& it : mPendingStreams) {
5998 it.second->cancelPrepare();
5999 }
6000}
6001
6002status_t Camera3Device::PreparerThread::resume() {
6003 ATRACE_CALL();
6004 status_t res;
6005
6006 Mutex::Autolock l(mLock);
6007 sp<NotificationListener> listener = mListener.promote();
6008
6009 if (mActive) {
6010 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6011 return NO_INIT;
6012 }
6013
6014 auto it = mPendingStreams.begin();
6015 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006016 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006017 if (res == OK) {
6018 if (listener != NULL) {
6019 listener->notifyPrepared(it->second->getId());
6020 }
6021 it = mPendingStreams.erase(it);
6022 } else if (res != NOT_ENOUGH_DATA) {
6023 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6024 res, strerror(-res));
6025 it = mPendingStreams.erase(it);
6026 } else {
6027 it++;
6028 }
6029 }
6030
6031 if (mPendingStreams.empty()) {
6032 return OK;
6033 }
6034
6035 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6036 if (res != OK) {
6037 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6038 __FUNCTION__, res, strerror(-res));
6039 return res;
6040 }
6041 mCancelNow = false;
6042 mActive = true;
6043 ALOGV("%s: Preparer stream started", __FUNCTION__);
6044
6045 return OK;
6046}
6047
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006048status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006049 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006050 Mutex::Autolock l(mLock);
6051
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006052 for (const auto& it : mPendingStreams) {
6053 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006054 }
6055 mPendingStreams.clear();
6056 mCancelNow = true;
6057
6058 return OK;
6059}
6060
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006061void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006062 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006063 Mutex::Autolock l(mLock);
6064 mListener = listener;
6065}
6066
6067bool Camera3Device::PreparerThread::threadLoop() {
6068 status_t res;
6069 {
6070 Mutex::Autolock l(mLock);
6071 if (mCurrentStream == nullptr) {
6072 // End thread if done with work
6073 if (mPendingStreams.empty()) {
6074 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6075 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6076 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6077 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006078 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006079 return false;
6080 }
6081
6082 // Get next stream to prepare
6083 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006084 mCurrentStream = it->second;
6085 mCurrentMaxCount = it->first;
6086 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006087 mPendingStreams.erase(it);
6088 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6089 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6090 } else if (mCancelNow) {
6091 mCurrentStream->cancelPrepare();
6092 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6093 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6094 mCurrentStream.clear();
6095 mCancelNow = false;
6096 return true;
6097 }
6098 }
6099
6100 res = mCurrentStream->prepareNextBuffer();
6101 if (res == NOT_ENOUGH_DATA) return true;
6102 if (res != OK) {
6103 // Something bad happened; try to recover by cancelling prepare and
6104 // signalling listener anyway
6105 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6106 mCurrentStream->getId(), res, strerror(-res));
6107 mCurrentStream->cancelPrepare();
6108 }
6109
6110 // This stream has finished, notify listener
6111 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006112 sp<NotificationListener> listener = mListener.promote();
6113 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006114 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6115 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006116 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006117 }
6118
6119 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6120 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006121 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006122
6123 return true;
6124}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006125
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006126status_t Camera3Device::RequestBufferStateMachine::initialize(
6127 sp<camera3::StatusTracker> statusTracker) {
6128 if (statusTracker == nullptr) {
6129 ALOGE("%s: statusTracker is null", __FUNCTION__);
6130 return BAD_VALUE;
6131 }
6132
6133 std::lock_guard<std::mutex> lock(mLock);
6134 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07006135 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006136 return OK;
6137}
6138
6139bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6140 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006141 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006142 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006143 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006144 return true;
6145 }
6146 return false;
6147}
6148
6149void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6150 std::lock_guard<std::mutex> lock(mLock);
6151 if (!mRequestBufferOngoing) {
6152 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6153 return;
6154 }
6155 mRequestBufferOngoing = false;
6156 if (mStatus == RB_STATUS_PENDING_STOP) {
6157 checkSwitchToStopLocked();
6158 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006159 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006160}
6161
6162void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6163 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006164 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006165 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006166 return;
6167}
6168
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006169void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006170 std::lock_guard<std::mutex> lock(mLock);
6171 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006172 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6173 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006174 mInflightMapEmpty = false;
6175 if (mStatus == RB_STATUS_STOPPED) {
6176 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006177 }
6178 return;
6179}
6180
6181void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6182 std::lock_guard<std::mutex> lock(mLock);
6183 mRequestThreadPaused = true;
6184 if (mStatus == RB_STATUS_PENDING_STOP) {
6185 checkSwitchToStopLocked();
6186 }
6187 return;
6188}
6189
6190void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6191 std::lock_guard<std::mutex> lock(mLock);
6192 mInflightMapEmpty = true;
6193 if (mStatus == RB_STATUS_PENDING_STOP) {
6194 checkSwitchToStopLocked();
6195 }
6196 return;
6197}
6198
6199void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6200 std::lock_guard<std::mutex> lock(mLock);
6201 if (!checkSwitchToStopLocked()) {
6202 mStatus = RB_STATUS_PENDING_STOP;
6203 }
6204 return;
6205}
6206
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006207bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
6208 std::lock_guard<std::mutex> lock(mLock);
6209 if (mRequestBufferOngoing) {
6210 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
6211 __FUNCTION__);
6212 return false;
6213 }
6214 mSwitchedToOffline = true;
6215 mInflightMapEmpty = true;
6216 mRequestThreadPaused = true;
6217 mStatus = RB_STATUS_STOPPED;
6218 return true;
6219}
6220
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006221void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6222 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6223 if (statusTracker != nullptr) {
6224 if (active) {
6225 statusTracker->markComponentActive(mRequestBufferStatusId);
6226 } else {
6227 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6228 }
6229 }
6230}
6231
6232bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6233 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6234 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006235 return true;
6236 }
6237 return false;
6238}
6239
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006240bool Camera3Device::startRequestBuffer() {
6241 return mRequestBufferSM.startRequestBuffer();
6242}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006244void Camera3Device::endRequestBuffer() {
6245 mRequestBufferSM.endRequestBuffer();
6246}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006247
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006248nsecs_t Camera3Device::getWaitDuration() {
6249 return kBaseGetBufferWait + getExpectedInFlightDuration();
6250}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006251
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006252void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
6253 mInterface->getInflightBufferKeys(out);
6254}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006255
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006256void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
6257 mInterface->getInflightRequestBufferKeys(out);
6258}
Shuzhen Wang268a1362018-10-16 16:32:59 -07006259
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006260std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
6261 std::vector<sp<Camera3StreamInterface>> ret;
6262 bool hasInputStream = mInputStream != nullptr;
6263 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
6264 if (hasInputStream) {
6265 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07006266 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006267 for (size_t i = 0; i < mOutputStreams.size(); i++) {
6268 ret.push_back(mOutputStreams[i]);
6269 }
6270 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
6271 ret.push_back(mDeletedStreams[i]);
6272 }
6273 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07006274}
6275
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006276status_t Camera3Device::switchToOffline(
6277 const std::vector<int32_t>& streamsToKeep,
6278 /*out*/ sp<CameraOfflineSessionBase>* session) {
6279 ATRACE_CALL();
6280 if (session == nullptr) {
6281 ALOGE("%s: session must not be null", __FUNCTION__);
6282 return BAD_VALUE;
6283 }
6284
6285 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006286
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006287 bool hasInputStream = mInputStream != nullptr;
6288 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
6289 bool inputStreamSupportsOffline = hasInputStream ?
6290 mInputStream->getOfflineProcessingSupport() : false;
6291 auto outputStreamIds = mOutputStreams.getStreamIds();
6292 auto streamIds = outputStreamIds;
6293 if (hasInputStream) {
6294 streamIds.push_back(mInputStream->getId());
6295 }
6296
6297 // Check all streams in streamsToKeep supports offline mode
6298 for (auto id : streamsToKeep) {
6299 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6300 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
6301 return BAD_VALUE;
6302 } else if (id == inputStreamId) {
6303 if (!inputStreamSupportsOffline) {
6304 ALOGE("%s: input stream %d cannot be switched to offline",
6305 __FUNCTION__, id);
6306 return BAD_VALUE;
6307 }
6308 } else {
6309 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
6310 if (!stream->getOfflineProcessingSupport()) {
6311 ALOGE("%s: output stream %d cannot be switched to offline",
6312 __FUNCTION__, id);
6313 return BAD_VALUE;
6314 }
6315 }
6316 }
6317
6318 // TODO: block surface sharing and surface group streams until we can support them
6319
6320 // Stop repeating request, wait until all remaining requests are submitted, then call into
6321 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006322 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6323 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006324 camera3::BufferRecords bufferRecords;
6325 status_t ret = mRequestThread->switchToOffline(
6326 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006327
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006328 if (ret != OK) {
6329 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
6330 return ret;
6331 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006332
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006333 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
6334 if (!succ) {
6335 SET_ERR("HAL must not be calling requestStreamBuffers call");
6336 // TODO: block ALL callbacks from HAL till app configured new streams?
6337 return UNKNOWN_ERROR;
6338 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006339
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006340 // Verify offlineSessionInfo
6341 std::vector<int32_t> offlineStreamIds;
6342 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
6343 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6344 // verify stream IDs
6345 int32_t id = offlineStream.id;
6346 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
6347 SET_ERR("stream ID %d not found!", id);
6348 return UNKNOWN_ERROR;
6349 }
6350
6351 // When not using HAL buf manager, only allow streams requested by app to be preserved
6352 if (!mUseHalBufManager) {
6353 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
6354 SET_ERR("stream ID %d must not be switched to offline!", id);
6355 return UNKNOWN_ERROR;
6356 }
6357 }
6358
6359 offlineStreamIds.push_back(id);
6360 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
6361 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
6362 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
6363 // Verify number of outstanding buffers
6364 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
6365 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
6366 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
6367 return UNKNOWN_ERROR;
6368 }
6369 }
6370
6371 // Verify all streams to be deleted don't have any outstanding buffers
6372 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6373 inputStreamId) == offlineStreamIds.end()) {
6374 if (mInputStream->hasOutstandingBuffers()) {
6375 SET_ERR("Input stream %d still has %zu outstanding buffer!",
6376 inputStreamId, mInputStream->getOutstandingBuffersCount());
6377 return UNKNOWN_ERROR;
6378 }
6379 }
6380
6381 for (const auto& outStreamId : outputStreamIds) {
6382 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
6383 outStreamId) == offlineStreamIds.end()) {
6384 auto outStream = mOutputStreams.get(outStreamId);
6385 if (outStream->hasOutstandingBuffers()) {
6386 SET_ERR("Output stream %d still has %zu outstanding buffer!",
6387 outStreamId, outStream->getOutstandingBuffersCount());
6388 return UNKNOWN_ERROR;
6389 }
6390 }
6391 }
6392
6393 InFlightRequestMap offlineReqs;
6394 // Verify inflight requests and their pending buffers
6395 {
6396 std::lock_guard<std::mutex> l(mInFlightLock);
6397 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
6398 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
6399 if (idx == NAME_NOT_FOUND) {
6400 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
6401 return UNKNOWN_ERROR;
6402 }
6403
6404 const auto& inflightReq = mInFlightMap.valueAt(idx);
6405 // TODO: check specific stream IDs
6406 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6407 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6408 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6409 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6410 return UNKNOWN_ERROR;
6411 }
6412 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6413 }
6414 }
6415
6416 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006417 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006418 camera3::StreamSet offlineStreamSet;
6419 sp<camera3::Camera3Stream> inputStream;
6420 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6421 int32_t id = offlineStream.id;
6422 if (mInputStream != nullptr && id == mInputStream->getId()) {
6423 inputStream = mInputStream;
6424 } else {
6425 offlineStreamSet.add(id, mOutputStreams.get(id));
6426 }
6427 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006428
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006429 // TODO: check if we need to lock before copying states
6430 // though technically no other thread should be talking to Camera3Device at this point
6431 Camera3OfflineStates offlineStates(
6432 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006433 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6434 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6435 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6436 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6437 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6438 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6439 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006440
6441 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6442 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6443
6444 // Delete all streams that has been transferred to offline session
6445 Mutex::Autolock l(mLock);
6446 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6447 int32_t id = offlineStream.id;
6448 if (mInputStream != nullptr && id == mInputStream->getId()) {
6449 mInputStream.clear();
6450 } else {
6451 mOutputStreams.remove(id);
6452 }
6453 }
6454
6455 // disconnect all other streams and switch to UNCONFIGURED state
6456 if (mInputStream != nullptr) {
6457 ret = mInputStream->disconnect();
6458 if (ret != OK) {
6459 SET_ERR_L("disconnect input stream failed!");
6460 return UNKNOWN_ERROR;
6461 }
6462 }
6463
6464 for (auto streamId : mOutputStreams.getStreamIds()) {
6465 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6466 ret = stream->disconnect();
6467 if (ret != OK) {
6468 SET_ERR_L("disconnect output stream %d failed!", streamId);
6469 return UNKNOWN_ERROR;
6470 }
6471 }
6472
6473 mInputStream.clear();
6474 mOutputStreams.clear();
6475 mNeedConfig = true;
6476 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6477 mOperatingMode = NO_MODE;
6478 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006479 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006480
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006481 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006482 // TO be done by CameraDeviceClient/Camera3OfflineSession
6483 // register the offline client to camera service
6484 // Setup result passthing threads etc
6485 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6486 // TODO: check how many onIdle callback will be sent
6487 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006488}
6489
Emilian Peevcc0b7952020-01-07 13:54:47 -08006490void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6491 ATRACE_CALL();
6492
6493 if (offlineStreamIds == nullptr) {
6494 return;
6495 }
6496
6497 Mutex::Autolock il(mInterfaceLock);
6498
6499 auto streamIds = mOutputStreams.getStreamIds();
6500 bool hasInputStream = mInputStream != nullptr;
6501 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6502 offlineStreamIds->push_back(mInputStream->getId());
6503 }
6504
6505 for (const auto & streamId : streamIds) {
6506 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6507 // Streams that use the camera buffer manager are currently not supported in
6508 // offline mode
6509 if (stream->getOfflineProcessingSupport() &&
6510 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6511 offlineStreamIds->push_back(streamId);
6512 }
6513 }
6514}
6515
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006516status_t Camera3Device::setRotateAndCropAutoBehavior(
6517 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6518 ATRACE_CALL();
6519 Mutex::Autolock il(mInterfaceLock);
6520 Mutex::Autolock l(mLock);
6521 if (mRequestThread == nullptr) {
6522 return INVALID_OPERATION;
6523 }
6524 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6525}
6526
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006527bool Camera3Device::supportsCameraMute() {
6528 Mutex::Autolock il(mInterfaceLock);
6529 Mutex::Autolock l(mLock);
6530
6531 return mSupportCameraMute;
6532}
6533
6534status_t Camera3Device::setCameraMute(bool enabled) {
6535 ATRACE_CALL();
6536 Mutex::Autolock il(mInterfaceLock);
6537 Mutex::Autolock l(mLock);
6538
6539 if (mRequestThread == nullptr || !mSupportCameraMute) {
6540 return INVALID_OPERATION;
6541 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07006542 int32_t muteMode =
6543 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
6544 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
6545 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
6546 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006547}
6548
Cliff Wuc2ad9c82021-04-21 00:58:58 +08006549status_t Camera3Device::injectCamera(const String8& injectedCamId,
6550 sp<CameraProviderManager> manager) {
6551 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
6552 ATRACE_CALL();
6553 Mutex::Autolock il(mInterfaceLock);
6554
6555 status_t res = NO_ERROR;
6556 if (mInjectionMethods->isInjecting()) {
6557 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
6558 return OK;
6559 } else {
6560 res = mInjectionMethods->stopInjection();
6561 if (res != OK) {
6562 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
6563 __FUNCTION__, res);
6564 return res;
6565 }
6566 }
6567 }
6568
6569 res = mInjectionMethods->injectionInitialize(injectedCamId, manager, this);
6570 if (res != OK) {
6571 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
6572 __FUNCTION__, res);
6573 return res;
6574 }
6575
6576 camera3::camera_stream_configuration injectionConfig;
6577 std::vector<uint32_t> injectionBufferSizes;
6578 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
6579 // When the second display of android is cast to the remote device, and the opened camera is
6580 // also cast to the second display, in this case, because the camera has configured the streams
6581 // at this time, we can directly call injectCamera() to replace the internal camera with
6582 // injection camera.
6583 if (mOperatingMode >= 0 && injectionConfig.num_streams > 0
6584 && injectionBufferSizes.size() > 0) {
6585 ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
6586 res = mInjectionMethods->injectCamera(
6587 injectionConfig, injectionBufferSizes);
6588 if (res != OK) {
6589 ALOGE("Can't finish inject camera process!");
6590 return res;
6591 }
6592 }
6593
6594 return OK;
6595}
6596
6597status_t Camera3Device::stopInjection() {
6598 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
6599 Mutex::Autolock il(mInterfaceLock);
6600 return mInjectionMethods->stopInjection();
6601}
6602
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006603}; // namespace android