blob: 1127eaa3a1e36715f239d44c3ab140ddaebc3fdb [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
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070055#include "CameraService.h"
Emilian Peeve579d8b2023-02-28 14:16:08 -080056#include "aidl/android/hardware/graphics/common/Dataspace.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080057#include "aidl/AidlUtils.h"
58#include "device3/Camera3Device.h"
59#include "device3/Camera3FakeStream.h"
60#include "device3/Camera3InputStream.h"
61#include "device3/Camera3OutputStream.h"
62#include "device3/Camera3SharedOutputStream.h"
63#include "mediautils/SchedulingPolicyService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070064#include "utils/CameraThreadState.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080065#include "utils/CameraTraces.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080066#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070067#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080069#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080070#include <tuple>
71
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080072using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080073using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080074
75namespace android {
76
Austin Borger74fca042022-05-23 12:41:21 -070077Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070078 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070079 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080080 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070081 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080082 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070083 mIsConstrainedHighSpeedConfiguration(false),
Emilian Peeve579d8b2023-02-28 14:16:08 -080084 mSupportNativeJpegR(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070085 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070086 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070087 mUsePartialResult(false),
88 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080089 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080090 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070092 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070094 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070095 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070096 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000097 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010098 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070099 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700100 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -0700101 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800102 mOverrideToPortrait(overrideToPortrait),
Emilian Peevd865f0d2023-03-17 17:13:07 -0700103 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
104 mComposerOutput(false),
105 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700106 mSettingsOverride(-1),
Austin Borgerc8099762023-01-12 17:08:46 -0800107 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108{
109 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111}
112
113Camera3Device::~Camera3Device()
114{
115 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700117 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800118}
119
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800121 return mId;
122}
123
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124status_t Camera3Device::initializeCommonLocked() {
125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700126 /** Start up status tracker thread */
127 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700129 if (res != OK) {
130 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
131 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700133 mStatusTracker.clear();
134 return res;
135 }
136
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700137 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700138 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700139
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700140 if (mUseHalBufManager) {
141 res = mRequestBufferSM.initialize(mStatusTracker);
142 if (res != OK) {
143 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
144 strerror(-res), res);
145 mInterface->close();
146 mStatusTracker.clear();
147 return res;
148 }
149 }
150
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800151 /** Create buffer manager */
152 mBufferManager = new Camera3BufferManager();
153
154 Vector<int32_t> sessionParamKeys;
155 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
156 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
157 if (sessionKeysEntry.count > 0) {
158 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
159 }
160
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700161 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
162 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
163 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
164 if (availableTestPatternModes.data.i32[i] ==
165 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
166 mSupportCameraMute = true;
167 mSupportTestPatternSolidColor = true;
168 break;
169 } else if (availableTestPatternModes.data.i32[i] ==
170 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
171 mSupportCameraMute = true;
172 mSupportTestPatternSolidColor = false;
173 }
174 }
175
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700176 camera_metadata_entry_t availableSettingsOverrides = mDeviceInfo.find(
177 ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES);
178 for (size_t i = 0; i < availableSettingsOverrides.count; i++) {
179 if (availableSettingsOverrides.data.i32[i] ==
180 ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM) {
181 mSupportZoomOverride = true;
182 break;
183 }
184 }
185
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700186 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800187 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700188 this, mStatusTracker, mInterface, sessionParamKeys,
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700189 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait,
190 mSupportZoomOverride);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800191 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800192 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700193 SET_ERR_L("Unable to start request queue thread: %s (%d)",
194 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800195 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800196 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800197 return res;
198 }
199
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700200 mPreparerThread = new PreparerThread();
201
Ruben Brunk183f0562015-08-12 12:55:02 -0700202 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800203 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400204 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700205 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700206 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800207 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800208
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800209 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800210 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800211 camera_metadata_entry timestampSource =
212 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
213 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
214 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800215 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800216 }
217
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700218 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100219 camera_metadata_entry partialResultsCount =
220 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
221 if (partialResultsCount.count > 0) {
222 mNumPartialResults = partialResultsCount.data.i32[0];
223 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700224 }
225
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800226 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
227 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700228 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700229 if (res != OK) {
230 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
231 return res;
232 }
233 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800234
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800235 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800236 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800237
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800238 if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700239 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
240 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
241 }
242
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800243 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
244 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
245 }
246
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800247 // Hidl/AidlCamera3DeviceInjectionMethods
248 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800249
Ravneetaeb20dc2022-03-30 05:33:03 +0000250 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800251 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700252 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
253 if (res != OK) {
254 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
255 strerror(-res), res);
256 return res;
257 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000258
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800259 return OK;
260}
261
262status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700263 return disconnectImpl();
264}
265
266status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800267 ATRACE_CALL();
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000268 Mutex::Autolock il(mInterfaceLock);
269
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700270 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800271
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700272 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700273 std::vector<wp<Camera3StreamInterface>> streams;
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000274 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000276 Mutex::Autolock l(mLock);
277 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000279 if (mRequestThread != NULL) {
280 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
281 res = mRequestThread->clear();
282 if (res != OK) {
283 SET_ERR_L("Can't stop streaming");
284 // Continue to close device even in case of error
285 } else {
286 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800287 if (res != OK) {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000288 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
289 maxExpectedDuration);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800290 // Continue to close device even in case of error
291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700293 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000294 // Signal to request thread that we're not expecting any
295 // more requests. This will be true since once we're in
296 // disconnect and we've cleared off the request queue, the
297 // request thread can't receive any new requests through
298 // binder calls - since disconnect holds
299 // mBinderSerialization lock.
300 mRequestThread->setRequestClearing();
301 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800302
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000303 if (mStatus == STATUS_ERROR) {
304 CLOGE("Shutting down in an error state");
305 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000307 if (mStatusTracker != NULL) {
308 mStatusTracker->requestExit();
309 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000311 if (mRequestThread != NULL) {
312 mRequestThread->requestExit();
313 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000315 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
316 for (size_t i = 0; i < mOutputStreams.size(); i++) {
317 streams.push_back(mOutputStreams[i]);
318 }
319 if (mInputStream != nullptr) {
320 streams.push_back(mInputStream);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700321 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700322 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000323
324 // Joining done without holding mLock, otherwise deadlocks may ensue
325 // as the threads try to access parent state
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
327 // HAL may be in a bad state, so waiting for request thread
328 // (which may be stuck in the HAL processCaptureRequest call)
329 // could be dangerous.
330 mRequestThread->join();
331 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000332
333 if (mStatusTracker != NULL) {
334 mStatusTracker->join();
335 }
336
337 if (mInjectionMethods->isInjecting()) {
338 mInjectionMethods->stopInjection();
339 }
340
341 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700342 {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000343 Mutex::Autolock l(mLock);
344 mRequestThread.clear();
345 Mutex::Autolock stLock(mTrackerLock);
346 mStatusTracker.clear();
347 interface = mInterface.get();
348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800349
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000350 // Call close without internal mutex held, as the HAL close may need to
351 // wait on assorted callbacks,etc, to complete before it can return.
352 mCameraServiceWatchdog->WATCH(interface->close());
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800353
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000354 flushInflightRequests();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700355
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000356 {
357 Mutex::Autolock l(mLock);
358 mInterface->clear();
359 mOutputStreams.clear();
360 mInputStream.clear();
361 mDeletedStreams.clear();
362 mBufferManager.clear();
363 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
364 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700365
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000366 for (auto& weakStream : streams) {
367 sp<Camera3StreamInterface> stream = weakStream.promote();
368 if (stream != nullptr) {
369 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
370 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700371 }
372 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700373 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000374
375 if (mCameraServiceWatchdog != NULL) {
376 mCameraServiceWatchdog->requestExit();
377 mCameraServiceWatchdog.clear();
378 }
379
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700380 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800381}
382
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383// For dumping/debugging only -
384// try to acquire a lock a few times, eventually give up to proceed with
385// debug/dump operations
386bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
387 bool gotLock = false;
388 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
389 if (lock.tryLock() == NO_ERROR) {
390 gotLock = true;
391 break;
392 } else {
393 usleep(kDumpSleepDuration);
394 }
395 }
396 return gotLock;
397}
398
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800399nsecs_t Camera3Device::getMonoToBoottimeOffset() {
400 // try three times to get the clock offset, choose the one
401 // with the minimum gap in measurements.
402 const int tries = 3;
403 nsecs_t bestGap, measured;
404 for (int i = 0; i < tries; ++i) {
405 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
406 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
407 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
408 const nsecs_t gap = tmono2 - tmono;
409 if (i == 0 || gap < bestGap) {
410 bestGap = gap;
411 measured = tbase - ((tmono + tmono2) >> 1);
412 }
413 }
414 return measured;
415}
416
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800417ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
418 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700419 // Get max jpeg size (area-wise) for default sensor pixel mode
420 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800421 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800422 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
424 // not ultra high res sensor
425 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800426 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700427 /*isUltraHighResolution*/true);
428 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800429 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
430 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 return BAD_VALUE;
432 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700433 bool useMaxSensorPixelModeThreshold = false;
434 if (uhrMaxJpegResolution.width != 0 &&
435 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
436 // Use the ultra high res max jpeg size and max jpeg buffer size
437 useMaxSensorPixelModeThreshold = true;
438 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700439
Zhijun Hef7da0962014-04-24 13:27:56 -0700440 // Get max jpeg buffer size
441 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800442 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700443 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800444 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
445 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700446 return BAD_VALUE;
447 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700448 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700449
450 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
451 if (useMaxSensorPixelModeThreshold) {
452 maxJpegBufferSize =
453 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
454 maxDefaultJpegResolution, maxJpegBufferSize);
455 chosenMaxJpegResolution = uhrMaxJpegResolution;
456 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800457 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700458
459 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700460 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700461 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800462 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
463 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700464 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800465 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
466 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700467 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700468 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700469 return jpegBufferSize;
470}
471
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800472ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700473 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800474 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700475 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800476 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
477 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700478 return BAD_VALUE;
479 }
480 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
481 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
482 return maxBytesForPointCloud;
483}
484
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800485ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
486 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800487 const int PER_CONFIGURATION_SIZE = 3;
488 const int WIDTH_OFFSET = 0;
489 const int HEIGHT_OFFSET = 1;
490 const int SIZE_OFFSET = 2;
491 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800492 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800493 camera3::SessionConfigurationUtils::getAppropriateModeTag(
494 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
495 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800496 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800497 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800498 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
499 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800500 return BAD_VALUE;
501 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700502
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800503 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
504 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
505 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
506 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
507 }
508 }
509
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800510 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
511 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800512 return BAD_VALUE;
513}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700514
Jing Mikec7f9b132023-03-12 11:12:04 +0800515status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800516 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700517
518 // Try to lock, but continue in case of failure (to avoid blocking in
519 // deadlocks)
520 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
521 bool gotLock = tryLockSpinRightRound(mLock);
522
523 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800524 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
525 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700526 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800527 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
528 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700529
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800530 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700531
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800532 String16 templatesOption("-t");
533 int n = args.size();
534 for (int i = 0; i < n; i++) {
535 if (args[i] == templatesOption) {
536 dumpTemplates = true;
537 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000538 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700539 if (i + 1 < n) {
540 String8 monitorTags = String8(args[i + 1]);
541 if (monitorTags == "off") {
542 mTagMonitor.disableMonitoring();
543 } else {
544 mTagMonitor.parseTagsToMonitor(monitorTags);
545 }
546 } else {
547 mTagMonitor.disableMonitoring();
548 }
549 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800550 }
551
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800552 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 const char *status =
555 mStatus == STATUS_ERROR ? "ERROR" :
556 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700557 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
558 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800559 mStatus == STATUS_ACTIVE ? "ACTIVE" :
560 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700561
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800562 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700563 if (mStatus == STATUS_ERROR) {
564 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
565 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800566 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800567 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000568 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
569 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
570 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800571 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800572
573 if (mInputStream != NULL) {
574 write(fd, lines.string(), lines.size());
575 mInputStream->dump(fd, args);
576 } else {
577 lines.appendFormat(" No input stream.\n");
578 write(fd, lines.string(), lines.size());
579 }
580 for (size_t i = 0; i < mOutputStreams.size(); i++) {
581 mOutputStreams[i]->dump(fd,args);
582 }
583
Zhijun He431503c2016-03-07 17:30:16 -0800584 if (mBufferManager != NULL) {
585 lines = String8(" Camera3 Buffer Manager:\n");
586 write(fd, lines.string(), lines.size());
587 mBufferManager->dump(fd, args);
588 }
Zhijun He125684a2015-12-26 15:07:30 -0800589
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700590 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700591 if (mInFlightLock.try_lock()) {
592 if (mInFlightMap.size() == 0) {
593 lines.append(" None\n");
594 } else {
595 for (size_t i = 0; i < mInFlightMap.size(); i++) {
596 InFlightRequest r = mInFlightMap.valueAt(i);
597 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
598 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
599 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
600 r.numBuffersLeft);
601 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700602 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700603 mInFlightLock.unlock();
604 } else {
605 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700606 }
607 write(fd, lines.string(), lines.size());
608
Shuzhen Wang686f6442017-06-20 16:16:04 -0700609 if (mRequestThread != NULL) {
610 mRequestThread->dumpCaptureRequestLatency(fd,
611 " ProcessCaptureRequest latency histogram:");
612 }
613
Igor Murashkin1e479c02013-09-06 16:55:14 -0700614 {
615 lines = String8(" Last request sent:\n");
616 write(fd, lines.string(), lines.size());
617
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700618 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700619 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
620 }
621
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800622 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700623 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 "TEMPLATE_PREVIEW",
625 "TEMPLATE_STILL_CAPTURE",
626 "TEMPLATE_VIDEO_RECORD",
627 "TEMPLATE_VIDEO_SNAPSHOT",
628 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800629 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800630 };
631
Emilian Peevf4816702020-04-03 15:44:51 -0700632 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 camera_metadata_t *templateRequest = nullptr;
634 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700635 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800636 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 lines.append(" Not supported\n");
639 write(fd, lines.string(), lines.size());
640 } else {
641 write(fd, lines.string(), lines.size());
642 dump_indented_camera_metadata(templateRequest,
643 fd, /*verbosity*/2, /*indentation*/8);
644 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800645 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800646 }
647 }
648
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700649 mTagMonitor.dumpMonitoredMetadata(fd);
650
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800651 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800652 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800653 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800654 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800656
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700657 if (gotLock) mLock.unlock();
658 if (gotInterfaceLock) mInterfaceLock.unlock();
659
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800660 return OK;
661}
662
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700663status_t Camera3Device::startWatchingTags(const String8 &tags) {
664 mTagMonitor.parseTagsToMonitor(tags);
665 return OK;
666}
667
668status_t Camera3Device::stopWatchingTags() {
669 mTagMonitor.disableMonitoring();
670 return OK;
671}
672
673status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
674 mTagMonitor.getLatestMonitoredTagEvents(out);
675 return OK;
676}
677
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800678const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800679 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800680 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
681 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700682 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800683 mStatus == STATUS_ERROR ?
684 "when in error state" : "before init");
685 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700686 if (physicalId.isEmpty()) {
687 return mDeviceInfo;
688 } else {
689 std::string id(physicalId.c_str());
690 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
691 return mPhysicalDeviceInfoMap.at(id);
692 } else {
693 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
694 return mDeviceInfo;
695 }
696 }
697}
698
699const CameraMetadata& Camera3Device::info() const {
700 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800701 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800702}
703
Jianing Wei90e59c92014-03-12 18:29:36 -0700704status_t Camera3Device::checkStatusOkToCaptureLocked() {
705 switch (mStatus) {
706 case STATUS_ERROR:
707 CLOGE("Device has encountered a serious error");
708 return INVALID_OPERATION;
709 case STATUS_UNINITIALIZED:
710 CLOGE("Device not initialized");
711 return INVALID_OPERATION;
712 case STATUS_UNCONFIGURED:
713 case STATUS_CONFIGURED:
714 case STATUS_ACTIVE:
715 // OK
716 break;
717 default:
718 SET_ERR_L("Unexpected status: %d", mStatus);
719 return INVALID_OPERATION;
720 }
721 return OK;
722}
723
724status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000725 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700726 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700727 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700728 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700729 if (requestList == NULL) {
730 CLOGE("requestList cannot be NULL.");
731 return BAD_VALUE;
732 }
733
Jianing Weicb0652e2014-03-12 18:29:36 -0700734 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000735 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700736 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
737 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
738 ++metadataIt, ++surfaceMapIt) {
739 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700740 if (newRequest == 0) {
741 CLOGE("Can't create capture request");
742 return BAD_VALUE;
743 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700744
Shuzhen Wang9d066012016-09-30 11:30:20 -0700745 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700746 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700747
Jianing Weicb0652e2014-03-12 18:29:36 -0700748 // Setup burst Id and request Id
749 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800750 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
751 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700752 CLOGE("RequestID does not exist in metadata");
753 return BAD_VALUE;
754 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800755 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700756
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700758
759 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700760 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
762 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
763 return BAD_VALUE;
764 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700765
766 // Setup batch size if this is a high speed video recording request.
767 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
768 auto firstRequest = requestList->begin();
769 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
770 if (outputStream->isVideoStream()) {
771 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800772 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700773 break;
774 }
775 }
776 }
777
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 return OK;
779}
780
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800781status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800782 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783
Emilian Peevaebbe412018-01-15 13:53:24 +0000784 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000786 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700787
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800788 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700789}
790
Emilian Peevaebbe412018-01-15 13:53:24 +0000791void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700792 std::list<const SurfaceMap>& surfaceMaps,
793 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000794 PhysicalCameraSettingsList requestList;
795 requestList.push_back({std::string(getId().string()), request});
796 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700797
798 SurfaceMap surfaceMap;
799 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
800 // With no surface list passed in, stream and surface will have 1-to-1
801 // mapping. So the surface index is 0 for each stream in the surfaceMap.
802 for (size_t i = 0; i < streams.count; i++) {
803 surfaceMap[streams.data.i32[i]].push_back(0);
804 }
805 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806}
807
Jianing Wei90e59c92014-03-12 18:29:36 -0700808status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000809 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700810 const std::list<const SurfaceMap> &surfaceMaps,
811 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 /*out*/
813 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700814 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700815 nsecs_t requestTimeNs = systemTime();
816
Jianing Wei90e59c92014-03-12 18:29:36 -0700817 Mutex::Autolock il(mInterfaceLock);
818 Mutex::Autolock l(mLock);
819
820 status_t res = checkStatusOkToCaptureLocked();
821 if (res != OK) {
822 // error logged by previous call
823 return res;
824 }
825
826 RequestList requestList;
827
Shuzhen Wang0129d522016-10-30 22:43:41 -0700828 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700829 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700830 if (res != OK) {
831 // error logged by previous call
832 return res;
833 }
834
835 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700836 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700838 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700839 }
840
841 if (res == OK) {
842 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
843 if (res != OK) {
844 SET_ERR_L("Can't transition to active in %f seconds!",
845 kActiveTimeout/1e9);
846 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800847 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700848 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700849 } else {
850 CLOGE("Cannot queue request. Impossible.");
851 return BAD_VALUE;
852 }
853
854 return res;
855}
856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700859 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700860 ATRACE_CALL();
861
Emilian Peevaebbe412018-01-15 13:53:24 +0000862 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700863}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800864
Jianing Weicb0652e2014-03-12 18:29:36 -0700865status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
866 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800867 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800868
Emilian Peevaebbe412018-01-15 13:53:24 +0000869 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700870 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700872
Emilian Peevaebbe412018-01-15 13:53:24 +0000873 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700874 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800875}
876
Emilian Peevaebbe412018-01-15 13:53:24 +0000877status_t Camera3Device::setStreamingRequestList(
878 const List<const PhysicalCameraSettingsList> &requestsList,
879 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700880 ATRACE_CALL();
881
Emilian Peevaebbe412018-01-15 13:53:24 +0000882 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884
885sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000886 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 status_t res;
888
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700889 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800890 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
891 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000892 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700893 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700894 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800895 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700896 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800897 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700898 } else if (mStatus == STATUS_UNCONFIGURED) {
899 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700900 CLOGE("No streams configured");
901 return NULL;
902 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800903 }
904
Shuzhen Wang0129d522016-10-30 22:43:41 -0700905 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800906 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800907}
908
Jianing Weicb0652e2014-03-12 18:29:36 -0700909status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800910 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700911 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800912 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800913
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800914 switch (mStatus) {
915 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700916 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800917 return INVALID_OPERATION;
918 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700919 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800920 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700921 case STATUS_UNCONFIGURED:
922 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800923 case STATUS_ACTIVE:
924 // OK
925 break;
926 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700927 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800928 return INVALID_OPERATION;
929 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800930 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700931
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700932 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800933}
934
935status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
936 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700937 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800938
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700939 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800940}
941
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800943 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700944 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700945 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700946 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700947 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800948 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
949 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950
951 status_t res;
952 bool wasActive = false;
953
954 switch (mStatus) {
955 case STATUS_ERROR:
956 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
957 return INVALID_OPERATION;
958 case STATUS_UNINITIALIZED:
959 ALOGE("%s: Device not initialized", __FUNCTION__);
960 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700961 case STATUS_UNCONFIGURED:
962 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 // OK
964 break;
965 case STATUS_ACTIVE:
966 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700967 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700968 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700969 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700970 return res;
971 }
972 wasActive = true;
973 break;
974 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700975 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700976 return INVALID_OPERATION;
977 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700978 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979
980 if (mInputStream != 0) {
981 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
982 return INVALID_OPERATION;
983 }
984
985 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
986 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700987 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700988
989 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800990 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700991
992 *id = mNextStreamId++;
993
994 // Continue captures if active at start
995 if (wasActive) {
996 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100997 // Reuse current operating mode and session parameters for new stream config
998 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700999 if (res != OK) {
1000 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1001 __FUNCTION__, mNextStreamId, strerror(-res), res);
1002 return res;
1003 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001004 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001005 }
1006
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001007 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001008 return OK;
1009}
1010
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001011status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001012 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001013 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001014 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001015 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1016 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001017 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001018 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001019 ATRACE_CALL();
1020
1021 if (consumer == nullptr) {
1022 ALOGE("%s: consumer must not be null", __FUNCTION__);
1023 return BAD_VALUE;
1024 }
1025
1026 std::vector<sp<Surface>> consumers;
1027 consumers.push_back(consumer);
1028
1029 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001030 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001031 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001032 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001033}
1034
1035static bool isRawFormat(int format) {
1036 switch (format) {
1037 case HAL_PIXEL_FORMAT_RAW16:
1038 case HAL_PIXEL_FORMAT_RAW12:
1039 case HAL_PIXEL_FORMAT_RAW10:
1040 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1041 return true;
1042 default:
1043 return false;
1044 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001045}
1046
1047status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1048 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001049 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001050 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001051 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001052 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001053 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001054 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001055
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001056 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001057 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001059 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001060 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001061 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001062 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001063 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001064 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001065 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1066 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001067
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001068 status_t res;
1069 bool wasActive = false;
1070
1071 switch (mStatus) {
1072 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001073 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 return INVALID_OPERATION;
1075 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001076 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001078 case STATUS_UNCONFIGURED:
1079 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080 // OK
1081 break;
1082 case STATUS_ACTIVE:
1083 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001084 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001085 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001086 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001087 return res;
1088 }
1089 wasActive = true;
1090 break;
1091 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001092 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 return INVALID_OPERATION;
1094 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001095 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096
1097 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001098
Shuzhen Wang0129d522016-10-30 22:43:41 -07001099 if (consumers.size() == 0 && !hasDeferredConsumer) {
1100 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1101 return BAD_VALUE;
1102 }
Zhijun He5d677d12016-05-29 16:52:39 -07001103
Shuzhen Wang0129d522016-10-30 22:43:41 -07001104 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001105 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1106 return BAD_VALUE;
1107 }
1108
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001109 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1110 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1111 // be found in only one sensor pixel mode.
1112 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1113 return BAD_VALUE;
1114 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001115 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001116 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001117 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001118 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001119 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001120 if (blobBufferSize <= 0) {
1121 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1122 return BAD_VALUE;
1123 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001124 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1125 blobBufferSize = width * height;
1126 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001127 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001128 if (blobBufferSize <= 0) {
1129 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1130 return BAD_VALUE;
1131 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001132 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001133 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001134 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001135 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001136 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001137 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001138 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001139 bool maxResolution =
1140 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1141 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001142 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1143 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001144 if (rawOpaqueBufferSize <= 0) {
1145 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1146 return BAD_VALUE;
1147 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001148 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001149 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001150 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001151 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001152 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001153 } else if (isShared) {
1154 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1155 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001156 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001157 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001158 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001159 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001160 newStream = new Camera3OutputStream(mNextStreamId,
1161 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001162 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001163 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001164 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001165 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001166 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001167 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001168 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001169 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001170 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 }
Emilian Peev40ead602017-09-26 15:46:36 +01001172
1173 size_t consumerCount = consumers.size();
1174 for (size_t i = 0; i < consumerCount; i++) {
1175 int id = newStream->getSurfaceId(consumers[i]);
1176 if (id < 0) {
1177 SET_ERR_L("Invalid surface id");
1178 return BAD_VALUE;
1179 }
1180 if (surfaceIds != nullptr) {
1181 surfaceIds->push_back(id);
1182 }
1183 }
1184
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186
Emilian Peev08dd2452017-04-06 16:55:14 +01001187 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001188
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001189 newStream->setImageDumpMask(mImageDumpMask);
1190
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 res = mOutputStreams.add(mNextStreamId, newStream);
1192 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001193 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 return res;
1195 }
1196
Shuzhen Wang316781a2020-08-18 18:11:01 -07001197 mSessionStatsBuilder.addStream(mNextStreamId);
1198
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001200 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201
1202 // Continue captures if active at start
1203 if (wasActive) {
1204 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001205 // Reuse current operating mode and session parameters for new stream config
1206 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001208 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1209 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return res;
1211 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001214 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001216}
1217
Emilian Peev710c1422017-08-30 11:19:38 +01001218status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001220 if (nullptr == streamInfo) {
1221 return BAD_VALUE;
1222 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 switch (mStatus) {
1227 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001228 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 return INVALID_OPERATION;
1230 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001233 case STATUS_UNCONFIGURED:
1234 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 case STATUS_ACTIVE:
1236 // OK
1237 break;
1238 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001239 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 return INVALID_OPERATION;
1241 }
1242
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001243 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1244 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001245 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001246 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 }
1248
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001249 streamInfo->width = stream->getWidth();
1250 streamInfo->height = stream->getHeight();
1251 streamInfo->format = stream->getFormat();
1252 streamInfo->dataSpace = stream->getDataSpace();
1253 streamInfo->formatOverridden = stream->isFormatOverridden();
1254 streamInfo->originalFormat = stream->getOriginalFormat();
1255 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1256 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001257 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001258 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001260}
1261
1262status_t Camera3Device::setStreamTransform(int id,
1263 int transform) {
1264 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001265 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001267
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 switch (mStatus) {
1269 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return INVALID_OPERATION;
1272 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001273 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 case STATUS_UNCONFIGURED:
1276 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 case STATUS_ACTIVE:
1278 // OK
1279 break;
1280 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001281 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 return INVALID_OPERATION;
1283 }
1284
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001285 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1286 if (stream == nullptr) {
1287 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 return BAD_VALUE;
1289 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001290 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001291}
1292
1293status_t Camera3Device::deleteStream(int id) {
1294 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001295 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001296 Mutex::Autolock l(mLock);
1297 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001298
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001299 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301 // CameraDevice semantics require device to already be idle before
1302 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001304 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001305 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001306 }
1307
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001308 if (mStatus == STATUS_ERROR) {
1309 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1310 __FUNCTION__, mId.string());
1311 return -EBUSY;
1312 }
1313
Igor Murashkin2fba5842013-04-22 14:03:54 -07001314 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001315 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001316 if (mInputStream != NULL && id == mInputStream->getId()) {
1317 deletedStream = mInputStream;
1318 mInputStream.clear();
1319 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001320 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001321 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001322 return BAD_VALUE;
1323 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001324 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001325 }
1326
1327 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001328 if (stream != nullptr) {
1329 deletedStream = stream;
1330 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001331 }
1332
1333 // Free up the stream endpoint so that it can be used by some other stream
1334 res = deletedStream->disconnect();
1335 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001336 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001337 // fall through since we want to still list the stream as deleted.
1338 }
1339 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001340 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341
1342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001343}
1344
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001345status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001346 ATRACE_CALL();
1347 ALOGV("%s: E", __FUNCTION__);
1348
1349 Mutex::Autolock il(mInterfaceLock);
1350 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001351
Emilian Peev811d2952018-05-25 11:08:40 +01001352 // In case the client doesn't include any session parameter, try a
1353 // speculative configuration using the values from the last cached
1354 // default request.
1355 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001356 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001357 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1358 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1359 mLastTemplateId);
1360 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1361 operatingMode);
1362 }
1363
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001364 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1365}
1366
1367status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1368 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001369 //Filter out any incoming session parameters
1370 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001371 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1372 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001373 CameraMetadata filteredParams(availableSessionKeys.count);
1374 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1375 filteredParams.getAndLock());
1376 set_camera_metadata_vendor_id(meta, mVendorTagId);
1377 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001378 if (availableSessionKeys.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001379 bool rotateAndCropSessionKey = false;
1380 bool autoframingSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001381 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1382 camera_metadata_ro_entry entry = params.find(
1383 availableSessionKeys.data.i32[i]);
1384 if (entry.count > 0) {
1385 filteredParams.update(entry);
1386 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07001387 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1388 rotateAndCropSessionKey = true;
1389 }
1390 if (ANDROID_CONTROL_AUTOFRAMING == availableSessionKeys.data.i32[i]) {
1391 autoframingSessionKey = true;
1392 }
1393 }
1394
1395 if (rotateAndCropSessionKey || autoframingSessionKey) {
1396 sp<CaptureRequest> request = new CaptureRequest();
1397 PhysicalCameraSettings settingsList;
1398 settingsList.metadata = filteredParams;
1399 request->mSettingsList.push_back(settingsList);
1400
1401 if (rotateAndCropSessionKey) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001402 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1403 if (rotateAndCropEntry.count > 0 &&
1404 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1405 request->mRotateAndCropAuto = true;
1406 } else {
1407 request->mRotateAndCropAuto = false;
1408 }
1409
1410 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1411 }
1412
1413 if (autoframingSessionKey) {
1414 auto autoframingEntry = filteredParams.find(ANDROID_CONTROL_AUTOFRAMING);
1415 if (autoframingEntry.count > 0 &&
1416 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
1417 overrideAutoframing(request, mAutoframingOverride);
1418 }
1419 }
1420
1421 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001422 }
1423 }
1424
1425 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001426}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001427
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001428status_t Camera3Device::getInputBufferProducer(
1429 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001430 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001431 Mutex::Autolock il(mInterfaceLock);
1432 Mutex::Autolock l(mLock);
1433
1434 if (producer == NULL) {
1435 return BAD_VALUE;
1436 } else if (mInputStream == NULL) {
1437 return INVALID_OPERATION;
1438 }
1439
1440 return mInputStream->getInputBufferProducer(producer);
1441}
1442
Emilian Peevf4816702020-04-03 15:44:51 -07001443status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001444 CameraMetadata *request) {
1445 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001446 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001447
Emilian Peevf4816702020-04-03 15:44:51 -07001448 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001449 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001450 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001451 return BAD_VALUE;
1452 }
1453
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001454 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001456 {
1457 Mutex::Autolock l(mLock);
1458 switch (mStatus) {
1459 case STATUS_ERROR:
1460 CLOGE("Device has encountered a serious error");
1461 return INVALID_OPERATION;
1462 case STATUS_UNINITIALIZED:
1463 CLOGE("Device is not initialized!");
1464 return INVALID_OPERATION;
1465 case STATUS_UNCONFIGURED:
1466 case STATUS_CONFIGURED:
1467 case STATUS_ACTIVE:
1468 // OK
1469 break;
1470 default:
1471 SET_ERR_L("Unexpected status: %d", mStatus);
1472 return INVALID_OPERATION;
1473 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001475 if (!mRequestTemplateCache[templateId].isEmpty()) {
1476 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001477 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001478 return OK;
1479 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001480 }
1481
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001482 camera_metadata_t *rawRequest;
1483 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001484 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001485
1486 {
1487 Mutex::Autolock l(mLock);
1488 if (res == BAD_VALUE) {
1489 ALOGI("%s: template %d is not supported on this camera device",
1490 __FUNCTION__, templateId);
1491 return res;
1492 } else if (res != OK) {
1493 CLOGE("Unable to construct request template %d: %s (%d)",
1494 templateId, strerror(-res), res);
1495 return res;
1496 }
1497
1498 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1499 mRequestTemplateCache[templateId].acquire(rawRequest);
1500
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001501 // Override the template request with zoomRatioMapper
1502 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1503 &mRequestTemplateCache[templateId]);
1504 if (res != OK) {
1505 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1506 templateId, strerror(-res), res);
1507 return res;
1508 }
1509
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001510 // Fill in JPEG_QUALITY if not available
1511 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1512 static const uint8_t kDefaultJpegQuality = 95;
1513 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1514 &kDefaultJpegQuality, 1);
1515 }
1516
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001517 // Fill in AUTOFRAMING if not available
1518 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1519 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1520 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1521 &kDefaultAutoframingMode, 1);
1522 }
1523
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001524 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001525 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527 return OK;
1528}
1529
1530status_t Camera3Device::waitUntilDrained() {
1531 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001533 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001536 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001537}
1538
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001539status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 switch (mStatus) {
1541 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 ALOGV("%s: Already idle", __FUNCTION__);
1544 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 case STATUS_CONFIGURED:
1546 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 case STATUS_ERROR:
1548 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 break;
1551 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001552 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 return INVALID_OPERATION;
1554 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001555 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1556 maxExpectedDuration);
1557 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001558 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001559 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001560 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1561 res);
1562 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 return res;
1564}
1565
Ruben Brunk183f0562015-08-12 12:55:02 -07001566void Camera3Device::internalUpdateStatusLocked(Status status) {
1567 mStatus = status;
1568 mRecentStatusUpdates.add(mStatus);
1569 mStatusChanged.broadcast();
1570}
1571
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001573status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001574 if (mRequestThread.get() != nullptr) {
1575 mRequestThread->setPaused(true);
1576 } else {
1577 return NO_INIT;
1578 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001580 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1581 maxExpectedDuration);
1582 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001584 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001586 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 }
1588
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 return res;
1590}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592// Resume after internalPauseAndWaitLocked
1593status_t Camera3Device::internalResumeLocked() {
1594 status_t res;
1595
1596 mRequestThread->setPaused(false);
1597
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001598 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1599 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1601 if (res != OK) {
1602 SET_ERR_L("Can't transition to active in %f seconds!",
1603 kActiveTimeout/1e9);
1604 }
1605 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607}
1608
Ruben Brunk183f0562015-08-12 12:55:02 -07001609status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001610 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001611
1612 size_t startIndex = 0;
1613 if (mStatusWaiters == 0) {
1614 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1615 // this status list
1616 mRecentStatusUpdates.clear();
1617 } else {
1618 // If other threads are waiting on updates to this status list, set the position of the
1619 // first element that this list will check rather than clearing the list.
1620 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 }
1622
Ruben Brunk183f0562015-08-12 12:55:02 -07001623 mStatusWaiters++;
1624
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001625 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001626 if (!active && mUseHalBufManager) {
1627 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001628 if (mStatus == STATUS_ACTIVE) {
1629 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001630 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001631 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001632 mRequestBufferSM.onWaitUntilIdle();
1633 }
1634
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001635 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001636 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001637 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001638 if (active == (mStatus == STATUS_ACTIVE)) {
1639 // Desired state is current
1640 break;
1641 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001643 nsecs_t timeElapsed = systemTime() - startTime;
1644 nsecs_t timeToWait = timeout - timeElapsed;
1645 if (timeToWait <= 0) {
1646 // Thread woke up spuriously but has timed out since.
1647 // Force out of loop with TIMED_OUT result.
1648 res = TIMED_OUT;
1649 break;
1650 }
1651 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001652 if (res != OK) break;
1653
Ruben Brunk183f0562015-08-12 12:55:02 -07001654 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1655 // transitions.
1656 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1657 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1658 __FUNCTION__);
1659
1660 // Encountered desired state since we began waiting
1661 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001662 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1663 stateSeen = true;
1664 break;
1665 }
1666 }
1667 } while (!stateSeen);
1668
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001669 if (signalPipelineDrain) {
1670 mRequestThread->resetPipelineDrain();
1671 }
1672
Ruben Brunk183f0562015-08-12 12:55:02 -07001673 mStatusWaiters--;
1674
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675 return res;
1676}
1677
1678
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001679status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001681 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001682
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001683 if (listener != NULL && mListener != NULL) {
1684 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1685 }
1686 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001687 mRequestThread->setNotificationListener(listener);
1688 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001689
1690 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001691}
1692
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001693bool Camera3Device::willNotify3A() {
1694 return false;
1695}
1696
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001698 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001699 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001701 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001702 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1703 if (st == std::cv_status::timeout) {
1704 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001705 }
1706 }
1707 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708}
1709
Jianing Weicb0652e2014-03-12 18:29:36 -07001710status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001711 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001712 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001714 if (mResultQueue.empty()) {
1715 return NOT_ENOUGH_DATA;
1716 }
1717
Jianing Weicb0652e2014-03-12 18:29:36 -07001718 if (frame == NULL) {
1719 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1720 return BAD_VALUE;
1721 }
1722
1723 CaptureResult &result = *(mResultQueue.begin());
1724 frame->mResultExtras = result.mResultExtras;
1725 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001726 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001727 mResultQueue.erase(mResultQueue.begin());
1728
1729 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001730}
1731
1732status_t Camera3Device::triggerAutofocus(uint32_t id) {
1733 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001734 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001735
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001736 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1737 // Mix-in this trigger into the next request and only the next request.
1738 RequestTrigger trigger[] = {
1739 {
1740 ANDROID_CONTROL_AF_TRIGGER,
1741 ANDROID_CONTROL_AF_TRIGGER_START
1742 },
1743 {
1744 ANDROID_CONTROL_AF_TRIGGER_ID,
1745 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001746 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001747 };
1748
1749 return mRequestThread->queueTrigger(trigger,
1750 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751}
1752
1753status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1754 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001755 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001756
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001757 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1758 // Mix-in this trigger into the next request and only the next request.
1759 RequestTrigger trigger[] = {
1760 {
1761 ANDROID_CONTROL_AF_TRIGGER,
1762 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1763 },
1764 {
1765 ANDROID_CONTROL_AF_TRIGGER_ID,
1766 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001767 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001768 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001770 return mRequestThread->queueTrigger(trigger,
1771 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001772}
1773
1774status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1775 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001777
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001778 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1779 // Mix-in this trigger into the next request and only the next request.
1780 RequestTrigger trigger[] = {
1781 {
1782 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1783 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1784 },
1785 {
1786 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1787 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001788 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001789 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001791 return mRequestThread->queueTrigger(trigger,
1792 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001793}
1794
Jianing Weicb0652e2014-03-12 18:29:36 -07001795status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001796 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001797 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001799
Zhijun He7ef20392014-04-21 16:04:17 -07001800 {
1801 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001802
1803 // b/116514106 "disconnect()" can get called twice for the same device. The
1804 // camera device will not be initialized during the second run.
1805 if (mStatus == STATUS_UNINITIALIZED) {
1806 return OK;
1807 }
1808
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001809 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001810
1811 // Stop session and stream counter
1812 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001813 }
1814
Ravneetdbd5b242022-03-02 07:22:46 +00001815 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001816 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001817 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1818 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1819
1820 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001821}
1822
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001823status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001824 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1825}
1826
1827status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001828 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001829 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001830 Mutex::Autolock il(mInterfaceLock);
1831 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001832
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001833 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1834 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001835 CLOGE("Stream %d does not exist", streamId);
1836 return BAD_VALUE;
1837 }
1838
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001839 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001840 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001841 return BAD_VALUE;
1842 }
1843
1844 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001845 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001846 return BAD_VALUE;
1847 }
1848
Ruben Brunkc78ac262015-08-13 17:58:46 -07001849 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001850}
1851
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001852status_t Camera3Device::tearDown(int streamId) {
1853 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001854 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001855 Mutex::Autolock il(mInterfaceLock);
1856 Mutex::Autolock l(mLock);
1857
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001858 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1859 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001860 CLOGE("Stream %d does not exist", streamId);
1861 return BAD_VALUE;
1862 }
1863
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001864 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1865 CLOGE("Stream %d is a target of a in-progress request", streamId);
1866 return BAD_VALUE;
1867 }
1868
1869 return stream->tearDown();
1870}
1871
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001872status_t Camera3Device::addBufferListenerForStream(int streamId,
1873 wp<Camera3StreamBufferListener> listener) {
1874 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001875 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001876 Mutex::Autolock il(mInterfaceLock);
1877 Mutex::Autolock l(mLock);
1878
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001879 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1880 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001881 CLOGE("Stream %d does not exist", streamId);
1882 return BAD_VALUE;
1883 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001884 stream->addBufferListener(listener);
1885
1886 return OK;
1887}
1888
Austin Borger4a870a32022-02-25 01:48:41 +00001889float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1890 camera_metadata_entry minDurations =
1891 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1892 for (size_t i = 0; i < minDurations.count; i += 4) {
1893 if (minDurations.data.i64[i] == stream->getFormat()
1894 && minDurations.data.i64[i+1] == stream->getWidth()
1895 && minDurations.data.i64[i+2] == stream->getHeight()) {
1896 int64_t minFrameDuration = minDurations.data.i64[i+3];
1897 return 1e9f / minFrameDuration;
1898 }
1899 }
1900 return 0.0f;
1901}
1902
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001903/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001904 * Methods called by subclasses
1905 */
1906
1907void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001908 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001909 std::vector<int> streamIds;
1910 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001911 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001912
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 {
1914 // Need mLock to safely update state and synchronize to current
1915 // state of methods in flight.
1916 Mutex::Autolock l(mLock);
1917 // We can get various system-idle notices from the status tracker
1918 // while starting up. Only care about them if we've actually sent
1919 // in some requests recently.
1920 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1921 return;
1922 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001923 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1924 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001925 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926
1927 // Skip notifying listener if we're doing some user-transparent
1928 // state changes
1929 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001930
Austin Borger4a870a32022-02-25 01:48:41 +00001931 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1932 auto stream = mOutputStreams[i];
1933 if (stream.get() == nullptr) continue;
1934
1935 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1936 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1937
1938 // Populate stream statistics in case of Idle
1939 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001940 streamIds.push_back(stream->getId());
1941 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1942 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001943 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001944 if (camera3Stream != nullptr) {
1945 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001946 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001947 }
1948 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001949 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001950 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001951 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001952 stream->getDynamicRangeProfile(), streamUseCase,
1953 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001954 }
1955 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001956 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001957
1958 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001960 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001961 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001962 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001963 status_t res = OK;
1964 if (listener != nullptr) {
1965 if (idle) {
1966 // Get session stats from the builder, and notify the listener.
1967 int64_t requestCount, resultErrorCount;
1968 bool deviceError;
1969 std::map<int, StreamStats> streamStatsMap;
1970 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1971 &deviceError, &streamStatsMap);
1972 for (size_t i = 0; i < streamIds.size(); i++) {
1973 int streamId = streamIds[i];
1974 auto stats = streamStatsMap.find(streamId);
1975 if (stats != streamStatsMap.end()) {
1976 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1977 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1978 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1979 streamStats[i].mHistogramType =
1980 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1981 streamStats[i].mHistogramBins.assign(
1982 stats->second.mCaptureLatencyBins.begin(),
1983 stats->second.mCaptureLatencyBins.end());
1984 streamStats[i].mHistogramCounts.assign(
1985 stats->second.mCaptureLatencyHistogram.begin(),
1986 stats->second.mCaptureLatencyHistogram.end());
1987 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001988 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001989 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1990 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001991 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001992 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001993 }
1994 if (res != OK) {
1995 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1996 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001997 }
1998}
1999
Shuzhen Wang758c2152017-01-10 18:26:18 -08002000status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002001 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002002 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002003 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2004 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002005
2006 if (surfaceIds == nullptr) {
2007 return BAD_VALUE;
2008 }
2009
Zhijun He5d677d12016-05-29 16:52:39 -07002010 Mutex::Autolock il(mInterfaceLock);
2011 Mutex::Autolock l(mLock);
2012
Shuzhen Wang758c2152017-01-10 18:26:18 -08002013 if (consumers.size() == 0) {
2014 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002015 return BAD_VALUE;
2016 }
2017
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002018 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2019 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002020 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002021 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002022 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002023
2024 // isConsumerConfigurationDeferred will be off after setConsumers
2025 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002026 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002027 if (res != OK) {
2028 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2029 return res;
2030 }
2031
Emilian Peev40ead602017-09-26 15:46:36 +01002032 for (auto &consumer : consumers) {
2033 int id = stream->getSurfaceId(consumer);
2034 if (id < 0) {
2035 CLOGE("Invalid surface id!");
2036 return BAD_VALUE;
2037 }
2038 surfaceIds->push_back(id);
2039 }
2040
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002041 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002042 if (!stream->isConfiguring()) {
2043 CLOGE("Stream %d was already fully configured.", streamId);
2044 return INVALID_OPERATION;
2045 }
Zhijun He5d677d12016-05-29 16:52:39 -07002046
Shuzhen Wang0129d522016-10-30 22:43:41 -07002047 res = stream->finishConfiguration();
2048 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002049 // If finishConfiguration fails due to abandoned surface, do not set
2050 // device to error state.
2051 bool isSurfaceAbandoned =
2052 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2053 if (!isSurfaceAbandoned) {
2054 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2055 stream->getId(), strerror(-res), res);
2056 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002057 return res;
2058 }
Zhijun He5d677d12016-05-29 16:52:39 -07002059 }
2060
2061 return OK;
2062}
2063
Emilian Peev40ead602017-09-26 15:46:36 +01002064status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2065 const std::vector<OutputStreamInfo> &outputInfo,
2066 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2067 Mutex::Autolock il(mInterfaceLock);
2068 Mutex::Autolock l(mLock);
2069
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002070 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2071 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002072 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002073 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002074 }
2075
2076 for (const auto &it : removedSurfaceIds) {
2077 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2078 CLOGE("Shared surface still part of a pending request!");
2079 return -EBUSY;
2080 }
2081 }
2082
Emilian Peev40ead602017-09-26 15:46:36 +01002083 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2084 if (res != OK) {
2085 CLOGE("Stream %d failed to update stream (error %d %s) ",
2086 streamId, res, strerror(-res));
2087 if (res == UNKNOWN_ERROR) {
2088 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2089 __FUNCTION__);
2090 }
2091 return res;
2092 }
2093
2094 return res;
2095}
2096
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002097status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2098 Mutex::Autolock il(mInterfaceLock);
2099 Mutex::Autolock l(mLock);
2100
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002101 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2102 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002103 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2104 return BAD_VALUE;
2105 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002106
2107 if (dropping) {
2108 mSessionStatsBuilder.stopCounter(streamId);
2109 } else {
2110 mSessionStatsBuilder.startCounter(streamId);
2111 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002112 return stream->dropBuffers(dropping);
2113}
2114
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002115/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 * Camera3Device private methods
2117 */
2118
2119sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002120 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002121 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002123 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002124 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125
2126 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002127 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128 if (inputStreams.count > 0) {
2129 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002130 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002131 CLOGE("Request references unknown input stream %d",
2132 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133 return NULL;
2134 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002135
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002137 SET_ERR_L("%s: input stream %d is not configured!",
2138 __FUNCTION__, mInputStream->getId());
2139 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002140 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002141 // Check if stream prepare is blocking requests.
2142 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002143 CLOGE("Request references an input stream that's being prepared!");
2144 return NULL;
2145 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146
2147 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002148 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149 }
2150
2151 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002152 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002153 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002154 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155 return NULL;
2156 }
2157
2158 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002159 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2160 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002161 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002162 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002163 return NULL;
2164 }
Zhijun He5d677d12016-05-29 16:52:39 -07002165 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002166 auto iter = surfaceMap.find(streams.data.i32[i]);
2167 if (iter != surfaceMap.end()) {
2168 const std::vector<size_t>& surfaces = iter->second;
2169 for (const auto& surface : surfaces) {
2170 if (stream->isConsumerConfigurationDeferred(surface)) {
2171 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2172 "due to deferred consumer", stream->getId(), surface);
2173 return NULL;
2174 }
2175 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002176 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002177 }
2178
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002179 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002180 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2181 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002182 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002183 // Check if stream prepare is blocking requests.
2184 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002185 CLOGE("Request references an output stream that's being prepared!");
2186 return NULL;
2187 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002188
2189 newRequest->mOutputStreams.push(stream);
2190 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002191 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002192 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002194 auto rotateAndCropEntry =
2195 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2196 if (rotateAndCropEntry.count > 0 &&
2197 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2198 newRequest->mRotateAndCropAuto = true;
2199 } else {
2200 newRequest->mRotateAndCropAuto = false;
2201 }
2202
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002203 auto autoframingEntry =
2204 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2205 if (autoframingEntry.count > 0 &&
2206 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2207 newRequest->mAutoframingAuto = true;
2208 } else {
2209 newRequest->mAutoframingAuto = false;
2210 }
2211
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002212 auto zoomRatioEntry =
2213 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2214 if (zoomRatioEntry.count > 0 &&
2215 zoomRatioEntry.data.f[0] == 1.0f) {
2216 newRequest->mZoomRatioIs1x = true;
2217 } else {
2218 newRequest->mZoomRatioIs1x = false;
2219 }
2220
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002221 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002222 for (auto& settings : newRequest->mSettingsList) {
2223 auto testPatternModeEntry =
2224 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2225 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2226 testPatternModeEntry.data.i32[0] :
2227 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002228
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002229 auto testPatternDataEntry =
2230 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2231 if (testPatternDataEntry.count >= 4) {
2232 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2233 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2234 } else {
2235 settings.mOriginalTestPatternData[0] = 0;
2236 settings.mOriginalTestPatternData[1] = 0;
2237 settings.mOriginalTestPatternData[2] = 0;
2238 settings.mOriginalTestPatternData[3] = 0;
2239 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002240 }
2241 }
2242
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002243 if (mSupportZoomOverride) {
2244 for (auto& settings : newRequest->mSettingsList) {
2245 auto settingsOverrideEntry =
2246 settings.metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
2247 settings.mOriginalSettingsOverride = settingsOverrideEntry.count > 0 ?
2248 settingsOverrideEntry.data.i32[0] :
2249 ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
2250 }
2251 }
2252
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002254}
2255
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002256void Camera3Device::cancelStreamsConfigurationLocked() {
2257 int res = OK;
2258 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2259 res = mInputStream->cancelConfiguration();
2260 if (res != OK) {
2261 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2262 mInputStream->getId(), strerror(-res), res);
2263 }
2264 }
2265
2266 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002267 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002268 if (outputStream->isConfiguring()) {
2269 res = outputStream->cancelConfiguration();
2270 if (res != OK) {
2271 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2272 outputStream->getId(), strerror(-res), res);
2273 }
2274 }
2275 }
2276
2277 // Return state to that at start of call, so that future configures
2278 // properly clean things up
2279 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2280 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002281
2282 res = mPreparerThread->resume();
2283 if (res != OK) {
2284 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2285 }
2286}
2287
Emilian Peev0d0191e2020-04-21 17:01:18 -07002288bool Camera3Device::checkAbandonedStreamsLocked() {
2289 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2290 return true;
2291 }
2292
2293 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2294 auto stream = mOutputStreams[i];
2295 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2296 return true;
2297 }
2298 }
2299
2300 return false;
2301}
2302
Emilian Peev3bead5f2020-05-28 17:29:08 -07002303bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002304 ATRACE_CALL();
2305 bool ret = false;
2306
Shuzhen Wang316781a2020-08-18 18:11:01 -07002307 nsecs_t startTime = systemTime();
2308
Bharatt Kukreja5681f782023-01-18 21:56:28 +00002309 // We must not hold mInterfaceLock here since this function is called from
2310 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2311 // deadlocks (http://b/143513518)
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002312 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2313
2314 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002315 if (checkAbandonedStreamsLocked()) {
2316 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2317 __FUNCTION__);
2318 return true;
2319 }
2320
Emilian Peev3bead5f2020-05-28 17:29:08 -07002321 status_t rc = NO_ERROR;
2322 bool markClientActive = false;
2323 if (mStatus == STATUS_ACTIVE) {
2324 markClientActive = true;
2325 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002326
2327 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2328 }
2329
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002330 if (rc == NO_ERROR) {
2331 mNeedConfig = true;
2332 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2333 if (rc == NO_ERROR) {
2334 ret = true;
2335 mPauseStateNotify = false;
2336 //Moving to active state while holding 'mLock' is important.
2337 //There could be pending calls to 'create-/deleteStream' which
2338 //will trigger another stream configuration while the already
2339 //present streams end up with outstanding buffers that will
2340 //not get drained.
2341 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002342 } else if (rc == DEAD_OBJECT) {
2343 // DEAD_OBJECT can be returned if either the consumer surface is
2344 // abandoned, or the HAL has died.
2345 // - If the HAL has died, configureStreamsLocked call will set
2346 // device to error state,
2347 // - If surface is abandoned, we should not set device to error
2348 // state.
2349 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002350 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002351 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002352 }
2353 } else {
2354 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2355 }
2356
Austin Borger74fca042022-05-23 12:41:21 -07002357 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002358 ns2ms(systemTime() - startTime));
2359
Emilian Peev3bead5f2020-05-28 17:29:08 -07002360 if (markClientActive) {
2361 mStatusTracker->markComponentActive(clientStatusId);
2362 }
2363
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002364 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002365}
2366
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002367status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002368 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 ATRACE_CALL();
2370 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002371
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002372 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002373 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374 return INVALID_OPERATION;
2375 }
2376
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002377 if (operatingMode < 0) {
2378 CLOGE("Invalid operating mode: %d", operatingMode);
2379 return BAD_VALUE;
2380 }
2381
2382 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002383 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002384
2385 if (mOperatingMode != operatingMode) {
2386 mNeedConfig = true;
2387 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2388 mOperatingMode = operatingMode;
2389 }
2390
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002391 // Reset min expected duration when session is reconfigured.
2392 mMinExpectedDuration = 0;
2393
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002394 // In case called from configureStreams, abort queued input buffers not belonging to
2395 // any pending requests.
2396 if (mInputStream != NULL && notifyRequestThread) {
2397 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002398 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002399 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002400 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002401 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002402 if (res != OK) {
2403 // Exhausted acquiring all input buffers.
2404 break;
2405 }
2406
Emilian Peevf4816702020-04-03 15:44:51 -07002407 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002408 res = mInputStream->returnInputBuffer(inputBuffer);
2409 if (res != OK) {
2410 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2411 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2412 }
2413 }
2414 }
2415
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002416 if (!mNeedConfig) {
2417 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2418 return OK;
2419 }
2420
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002421 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002422 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002423 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2424 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002425 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002426 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002427 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002428 }
2429
Shuzhen Wang16610a62022-12-15 22:38:07 -08002430 // Override stream use case based on "adb shell command"
2431 overrideStreamUseCaseLocked();
2432
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002433 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002434 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002435
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002436 mPreparerThread->pause();
2437
Emilian Peevf4816702020-04-03 15:44:51 -07002438 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002439 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002441 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002442
Emilian Peevf4816702020-04-03 15:44:51 -07002443 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002444 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002445 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002446
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002447
2448 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002449 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002450 inputStream = mInputStream->startConfiguration();
2451 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002452 CLOGE("Can't start input stream configuration");
2453 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002454 return INVALID_OPERATION;
2455 }
2456 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002457
2458 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459 }
2460
Shuzhen Wang99080502021-03-07 21:08:20 -08002461 mGroupIdPhysicalCameraMap.clear();
Emilian Peevd865f0d2023-03-17 17:13:07 -07002462 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002463 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002464
2465 // Don't configure bidi streams twice, nor add them twice to the list
2466 if (mOutputStreams[i].get() ==
2467 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2468
2469 config.num_streams--;
2470 continue;
2471 }
2472
Emilian Peevf4816702020-04-03 15:44:51 -07002473 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002474 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002475 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002476 CLOGE("Can't start output stream configuration");
2477 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478 return INVALID_OPERATION;
2479 }
2480 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002481
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002482 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002483 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2484 // always occupy the initial entry.
Emilian Peeve579d8b2023-02-28 14:16:08 -08002485 if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2486 (outputStream->data_space ==
2487 static_cast<android_dataspace_t>(
2488 aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002489 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002490 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2491 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002492 } else if (outputStream->data_space ==
2493 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2494 bufferSizes[k] = outputStream->width * outputStream->height;
2495 } else {
2496 ALOGW("%s: Blob dataSpace %d not supported",
2497 __FUNCTION__, outputStream->data_space);
2498 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002499 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002500
2501 if (mOutputStreams[i]->isMultiResolution()) {
2502 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2503 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2504 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2505 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002506
2507 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07002508 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002509 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002510 }
2511
2512 config.streams = streams.editArray();
2513
2514 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002515 // max_buffers, usage, and priv fields, as well as data_space and format
2516 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002517
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002518 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002519 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002520 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002521 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002522
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002523 if (res == BAD_VALUE) {
2524 // HAL rejected this set of streams as unsupported, clean up config
2525 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002526 CLOGE("Set of requested inputs/outputs not supported by HAL");
2527 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002528 return BAD_VALUE;
2529 } else if (res != OK) {
2530 // Some other kind of error from configure_streams - this is not
2531 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002532 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2533 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 return res;
2535 }
2536
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002537 // Finish all stream configuration immediately.
2538 // TODO: Try to relax this later back to lazy completion, which should be
2539 // faster
2540
Igor Murashkin073f8572013-05-02 14:59:28 -07002541 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002542 bool streamReConfigured = false;
2543 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002544 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002545 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002546 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002547 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002548 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2549 return DEAD_OBJECT;
2550 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002551 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002552 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002553 if (streamReConfigured) {
2554 mInterface->onStreamReConfigured(mInputStream->getId());
2555 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002556 }
2557
2558 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002559 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002560 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002561 bool streamReConfigured = false;
2562 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002563 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002564 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002565 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002566 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002567 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2568 return DEAD_OBJECT;
2569 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002570 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002571 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002572 if (streamReConfigured) {
2573 mInterface->onStreamReConfigured(outputStream->getId());
2574 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002575 }
2576 }
2577
Emilian Peevd865f0d2023-03-17 17:13:07 -07002578 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002579
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002580 // Request thread needs to know to avoid using repeat-last-settings protocol
2581 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002582 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002583 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2584 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002585 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002586
Zhijun He90f7c372016-08-16 16:19:43 -07002587 char value[PROPERTY_VALUE_MAX];
2588 property_get("camera.fifo.disable", value, "0");
2589 int32_t disableFifo = atoi(value);
2590 if (disableFifo != 1) {
2591 // Boost priority of request thread to SCHED_FIFO.
2592 pid_t requestThreadTid = mRequestThread->getTid();
2593 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002594 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002595 if (res != OK) {
2596 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2597 strerror(-res), res);
2598 } else {
2599 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2600 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002601 }
2602
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002603 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002604 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2605 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2606 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2607 sessionParams.unlock(newSessionParams);
2608 mSessionParams.unlock(currentSessionParams);
2609 if (updateSessionParams) {
2610 mSessionParams = sessionParams;
2611 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002613 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002615 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002616 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002617
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002618 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002619
Zhijun He0a210512014-07-24 13:45:15 -07002620 // tear down the deleted streams after configure streams.
2621 mDeletedStreams.clear();
2622
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002623 auto rc = mPreparerThread->resume();
2624 if (rc != OK) {
2625 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2626 return rc;
2627 }
2628
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002629 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002630 mRequestBufferSM.onStreamsConfigured();
2631 }
2632
Cliff Wu3b268182021-07-06 15:44:43 +08002633 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002634 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002635 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002636 // configure the injection streams.
2637 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002638 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002639 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2640 res = mInjectionMethods->injectCamera(config, bufferSizes);
2641 if (res != OK) {
2642 ALOGE("Can't finish inject camera process!");
2643 return res;
2644 }
Cliff Wu3b268182021-07-06 15:44:43 +08002645 } else {
2646 // First run configureStreamsLocked() and then call injectCamera() case:
2647 // If the stream configuration has been completed and camera deive is active, but the
2648 // injection camera has not been injected yet, we need to store the stream configuration of
2649 // the internal camera (because the stream configuration of the injection camera is based
2650 // on the internal camera). When injecting occurs later, this configuration can be used by
2651 // the injection camera.
2652 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2653 " injection camera has not been injected yet.", __FUNCTION__);
2654 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002655 }
2656
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002657 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002658}
2659
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002660status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002661 ATRACE_CALL();
2662 status_t res;
2663
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002664 if (mFakeStreamId != NO_STREAM) {
2665 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002666 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002667 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002668 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002669 return INVALID_OPERATION;
2670 }
2671
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002672 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002673
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002674 sp<Camera3OutputStreamInterface> fakeStream =
2675 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002676
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002677 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002678 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002679 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002680 return res;
2681 }
2682
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002683 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002684 mNextStreamId++;
2685
2686 return OK;
2687}
2688
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002689status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002690 ATRACE_CALL();
2691 status_t res;
2692
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002693 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002694 if (mOutputStreams.size() == 1) return OK;
2695
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002696 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002697
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002698 // Ok, have a fake stream and there's at least one other output stream,
2699 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002700
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002701 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002702 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002703 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002704 return INVALID_OPERATION;
2705 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002706 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002707
2708 // Free up the stream endpoint so that it can be used by some other stream
2709 res = deletedStream->disconnect();
2710 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002711 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002712 // fall through since we want to still list the stream as deleted.
2713 }
2714 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002715 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002716
2717 return res;
2718}
2719
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002720void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002721 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002722 Mutex::Autolock l(mLock);
2723 va_list args;
2724 va_start(args, fmt);
2725
2726 setErrorStateLockedV(fmt, args);
2727
2728 va_end(args);
2729}
2730
2731void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002732 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002733 Mutex::Autolock l(mLock);
2734 setErrorStateLockedV(fmt, args);
2735}
2736
2737void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2738 va_list args;
2739 va_start(args, fmt);
2740
2741 setErrorStateLockedV(fmt, args);
2742
2743 va_end(args);
2744}
2745
2746void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002747 // Print out all error messages to log
2748 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002749 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002750
2751 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002752 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002753
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002754 mErrorCause = errorCause;
2755
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002756 if (mRequestThread != nullptr) {
2757 mRequestThread->setPaused(true);
2758 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002759 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002760
2761 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002762 sp<NotificationListener> listener = mListener.promote();
2763 if (listener != NULL) {
2764 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002765 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002766 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002767 }
2768
2769 // Save stack trace. View by dumping it later.
2770 CameraTraces::saveTrace();
2771 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002772}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002773
2774/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002775 * In-flight request management
2776 */
2777
Jianing Weicb0652e2014-03-12 18:29:36 -07002778status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002779 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002780 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002781 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002782 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002783 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002784 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002785 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002786 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002787
2788 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002789 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002790 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002791 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2792 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002793 if (res < 0) return res;
2794
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002795 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002796 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2797 // avoid a deadlock during reprocess requests.
2798 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002799 if (mStatusTracker != nullptr) {
2800 mStatusTracker->markComponentActive(mInFlightStatusId);
2801 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002802 }
2803
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002804 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002805 return OK;
2806}
2807
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002808void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002809 // Indicate idle inFlightMap to the status tracker
2810 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002811 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002812 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2813 // avoid a deadlock during reprocess requests.
2814 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002815 if (mStatusTracker != nullptr) {
2816 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2817 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002818 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002819 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002820}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002821
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002822void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002823 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002824 // something has likely gone wrong. This might still be legit only if application send in
2825 // a long burst of long exposure requests.
2826 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2827 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2828 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2829 mInFlightMap.size(), mExpectedInflightDuration);
2830 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2831 kInFlightWarnLimitHighSpeed) {
2832 CLOGW("In-flight list too large for high speed configuration: %zu,"
2833 "total inflight duration %" PRIu64,
2834 mInFlightMap.size(), mExpectedInflightDuration);
2835 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002836 }
2837}
2838
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002839void Camera3Device::onInflightMapFlushedLocked() {
2840 mExpectedInflightDuration = 0;
2841}
2842
2843void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002844 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002845 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2846 mInFlightMap.removeItemsAt(idx, 1);
2847
2848 onInflightEntryRemovedLocked(duration);
2849}
2850
2851
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002852void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002853 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002854 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002855 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002856 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002857 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002858 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002859
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002860 FlushInflightReqStates states {
2861 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002862 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002863
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002864 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002865}
2866
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002867CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002868 ALOGV("%s", __FUNCTION__);
2869
Igor Murashkin1e479c02013-09-06 16:55:14 -07002870 CameraMetadata retVal;
2871
2872 if (mRequestThread != NULL) {
2873 retVal = mRequestThread->getLatestRequest();
2874 }
2875
Igor Murashkin1e479c02013-09-06 16:55:14 -07002876 return retVal;
2877}
2878
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002879void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002880 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002881 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002882 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2883 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002884
2885 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002886 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002887}
2888
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002889void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002890 std::vector<native_handle_t*> *handles, bool closeFd) {
2891 if (handles == nullptr) {
2892 return;
2893 }
2894 if (closeFd) {
2895 for (auto& handle : *handles) {
2896 native_handle_close(handle);
2897 }
2898 }
2899 for (auto& handle : *handles) {
2900 native_handle_delete(handle);
2901 }
2902 handles->clear();
2903 return;
2904}
2905
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002906/**
2907 * HalInterface inner class methods
2908 */
2909
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002910void Camera3Device::HalInterface::getInflightBufferKeys(
2911 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002912 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002913 return;
2914}
2915
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002916void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2917 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002918 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002919 return;
2920}
2921
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002922bool Camera3Device::HalInterface::verifyBufferIds(
2923 int32_t streamId, std::vector<uint64_t>& bufIds) {
2924 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002925}
2926
2927status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002928 int32_t frameNumber, int32_t streamId,
2929 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002930 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002931}
2932
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002933status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002934 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002935 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002936}
2937
2938// Find and pop a buffer_handle_t based on bufferId
2939status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002940 uint64_t bufferId,
2941 /*out*/ buffer_handle_t** buffer,
2942 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002943 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002944}
2945
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002946std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2947 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002948 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002949}
2950
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002951uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2952 const native_handle_t* handle) {
2953 return mBufferRecords.removeOneBufferCache(streamId, handle);
2954}
2955
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002956void Camera3Device::HalInterface::onBufferFreed(
2957 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002958 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2959 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2960 if (bufferId != BUFFER_ID_NO_BUFFER) {
2961 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002962 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002963}
2964
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002965void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002966 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2967 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2968 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002969 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2970 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002971}
2972
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002973/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974 * RequestThread inner class methods
2975 */
2976
2977Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002978 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002979 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002980 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002981 bool supportCameraMute,
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002982 bool overrideToPortrait,
2983 bool supportSettingsOverride) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002984 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002985 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002986 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002987 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002988 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002990 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002991 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002992 mReconfigured(false),
2993 mDoPause(false),
2994 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002995 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002996 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002997 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002998 mCurrentAfTriggerId(0),
2999 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003000 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00003001 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07003002 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003003 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003004 mCameraMuteChanged(false),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003005 mSettingsOverride(ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003006 mRepeatingLastFrameNumber(
3007 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003008 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003009 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003010 mRequestLatency(kRequestLatencyBinSize),
3011 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003012 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07003013 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07003014 mSupportCameraMute(supportCameraMute),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003015 mOverrideToPortrait(overrideToPortrait),
3016 mSupportSettingsOverride(supportSettingsOverride) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003017 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08003018 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003019}
3020
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003021Camera3Device::RequestThread::~RequestThread() {}
3022
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003023void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003024 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003025 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003026 Mutex::Autolock l(mRequestLock);
3027 mListener = listener;
3028}
3029
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003030void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08003031 const CameraMetadata& sessionParams,
3032 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003033 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003034 Mutex::Autolock l(mRequestLock);
3035 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003036 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08003037 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003038 // Prepare video stream for high speed recording.
3039 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003040 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003041}
3042
Jianing Wei90e59c92014-03-12 18:29:36 -07003043status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003044 List<sp<CaptureRequest> > &requests,
3045 /*out*/
3046 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003047 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003048 Mutex::Autolock l(mRequestLock);
3049 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3050 ++it) {
3051 mRequestQueue.push_back(*it);
3052 }
3053
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003054 if (lastFrameNumber != NULL) {
3055 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3056 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3057 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3058 *lastFrameNumber);
3059 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003060
Jianing Wei90e59c92014-03-12 18:29:36 -07003061 unpauseForNewRequests();
3062
3063 return OK;
3064}
3065
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003066
3067status_t Camera3Device::RequestThread::queueTrigger(
3068 RequestTrigger trigger[],
3069 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003070 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003071 Mutex::Autolock l(mTriggerMutex);
3072 status_t ret;
3073
3074 for (size_t i = 0; i < count; ++i) {
3075 ret = queueTriggerLocked(trigger[i]);
3076
3077 if (ret != OK) {
3078 return ret;
3079 }
3080 }
3081
3082 return OK;
3083}
3084
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003085const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3086 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003087 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088 if (d != nullptr) return d->mId;
3089 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003090}
3091
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003092status_t Camera3Device::RequestThread::queueTriggerLocked(
3093 RequestTrigger trigger) {
3094
3095 uint32_t tag = trigger.metadataTag;
3096 ssize_t index = mTriggerMap.indexOfKey(tag);
3097
3098 switch (trigger.getTagType()) {
3099 case TYPE_BYTE:
3100 // fall-through
3101 case TYPE_INT32:
3102 break;
3103 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003104 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3105 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003106 return INVALID_OPERATION;
3107 }
3108
3109 /**
3110 * Collect only the latest trigger, since we only have 1 field
3111 * in the request settings per trigger tag, and can't send more than 1
3112 * trigger per request.
3113 */
3114 if (index != NAME_NOT_FOUND) {
3115 mTriggerMap.editValueAt(index) = trigger;
3116 } else {
3117 mTriggerMap.add(tag, trigger);
3118 }
3119
3120 return OK;
3121}
3122
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003123status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003124 const RequestList &requests,
3125 /*out*/
3126 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003127 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003128 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003129 if (lastFrameNumber != NULL) {
3130 *lastFrameNumber = mRepeatingLastFrameNumber;
3131 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003132 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003133 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003134 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3135 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003136
3137 unpauseForNewRequests();
3138
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003139 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003140 return OK;
3141}
3142
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003143bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003144 if (mRepeatingRequests.empty()) {
3145 return false;
3146 }
3147 int32_t requestId = requestIn->mResultExtras.requestId;
3148 const RequestList &repeatRequests = mRepeatingRequests;
3149 // All repeating requests are guaranteed to have same id so only check first quest
3150 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3151 return (firstRequest->mResultExtras.requestId == requestId);
3152}
3153
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003154status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003155 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003156 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003157 return clearRepeatingRequestsLocked(lastFrameNumber);
3158
3159}
3160
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003161status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3162 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003163 std::vector<int32_t> streamIds;
3164 for (const auto& request : mRepeatingRequests) {
3165 for (const auto& stream : request->mOutputStreams) {
3166 streamIds.push_back(stream->getId());
3167 }
3168 }
3169
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003170 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003171 if (lastFrameNumber != NULL) {
3172 *lastFrameNumber = mRepeatingLastFrameNumber;
3173 }
Emilian Peev2295df72021-11-12 18:14:10 -08003174
3175 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3176
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003177 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003178 return OK;
3179}
3180
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003181status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003182 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003183 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003184 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003185 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003186
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003187 // Send errors for all requests pending in the request queue, including
3188 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003189 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003190 if (listener != NULL) {
3191 for (RequestList::iterator it = mRequestQueue.begin();
3192 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003193 // Abort the input buffers for reprocess requests.
3194 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003195 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003196 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003197 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003198 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003199 if (res != OK) {
3200 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3201 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3202 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003203 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003204 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3205 if (res != OK) {
3206 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3207 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3208 }
3209 }
3210 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003211 // Set the frame number this request would have had, if it
3212 // had been submitted; this frame number will not be reused.
3213 // The requestId and burstId fields were set when the request was
3214 // submitted originally (in convertMetadataListToRequestListLocked)
3215 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003216 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003217 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003218 }
3219 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003220 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003221
3222 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003223 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003224 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003225 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003226 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003227 return OK;
3228}
3229
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003230status_t Camera3Device::RequestThread::flush() {
3231 ATRACE_CALL();
3232 Mutex::Autolock l(mFlushLock);
3233
Emilian Peev08dd2452017-04-06 16:55:14 +01003234 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003235}
3236
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003237void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003238 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003239 Mutex::Autolock l(mPauseLock);
3240 mDoPause = paused;
3241 mDoPauseSignal.signal();
3242}
3243
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003244status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3245 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003246 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003247 Mutex::Autolock l(mLatestRequestMutex);
3248 status_t res;
3249 while (mLatestRequestId != requestId) {
3250 nsecs_t startTime = systemTime();
3251
3252 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3253 if (res != OK) return res;
3254
3255 timeout -= (systemTime() - startTime);
3256 }
3257
3258 return OK;
3259}
3260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003261void Camera3Device::RequestThread::requestExit() {
3262 // Call parent to set up shutdown
3263 Thread::requestExit();
3264 // The exit from any possible waits
3265 mDoPauseSignal.signal();
3266 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003267
3268 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3269 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003270}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003271
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003272void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003273 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003274 bool surfaceAbandoned = false;
3275 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003276 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003277 {
3278 Mutex::Autolock l(mRequestLock);
3279 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3280 // repeating requests.
3281 for (const auto& request : mRepeatingRequests) {
3282 for (const auto& s : request->mOutputStreams) {
3283 if (s->isAbandoned()) {
3284 surfaceAbandoned = true;
3285 clearRepeatingRequestsLocked(&lastFrameNumber);
3286 break;
3287 }
3288 }
3289 if (surfaceAbandoned) {
3290 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003291 }
3292 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003293 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003294 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003295
3296 if (listener != NULL && surfaceAbandoned) {
3297 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003298 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003299}
3300
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003301bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003302 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003303 status_t res;
3304 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003305 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003306 uint32_t numRequestProcessed = 0;
3307 for (size_t i = 0; i < batchSize; i++) {
3308 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003309 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003310 }
3311
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003312 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3313
3314 bool triggerRemoveFailed = false;
3315 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3316 for (size_t i = 0; i < numRequestProcessed; i++) {
3317 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3318 nextRequest.submitted = true;
3319
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003320 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003321
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003322 if (!triggerRemoveFailed) {
3323 // Remove any previously queued triggers (after unlock)
3324 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3325 if (removeTriggerRes != OK) {
3326 triggerRemoveFailed = true;
3327 triggerFailedRequest = nextRequest;
3328 }
3329 }
3330 }
3331
3332 if (triggerRemoveFailed) {
3333 SET_ERR("RequestThread: Unable to remove triggers "
3334 "(capture request %d, HAL device: %s (%d)",
3335 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3336 cleanUpFailedRequests(/*sendRequestError*/ false);
3337 return false;
3338 }
3339
3340 if (res != OK) {
3341 // Should only get a failure here for malformed requests or device-level
3342 // errors, so consider all errors fatal. Bad metadata failures should
3343 // come through notify.
3344 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3345 mNextRequests[numRequestProcessed].halRequest.frame_number,
3346 strerror(-res), res);
3347 cleanUpFailedRequests(/*sendRequestError*/ false);
3348 return false;
3349 }
3350 return true;
3351}
3352
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003353Camera3Device::RequestThread::ExpectedDurationInfo
3354 Camera3Device::RequestThread::calculateExpectedDurationRange(
3355 const camera_metadata_t *request) {
3356 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003357 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003358 InFlightRequest::kDefaultMaxExpectedDuration,
3359 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003360 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3361 find_camera_metadata_ro_entry(request,
3362 ANDROID_CONTROL_AE_MODE,
3363 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003364 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003365
3366 switch (e.data.u8[0]) {
3367 case ANDROID_CONTROL_AE_MODE_OFF:
3368 find_camera_metadata_ro_entry(request,
3369 ANDROID_SENSOR_EXPOSURE_TIME,
3370 &e);
3371 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003372 expectedDurationInfo.minDuration = e.data.i64[0];
3373 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003374 }
3375 find_camera_metadata_ro_entry(request,
3376 ANDROID_SENSOR_FRAME_DURATION,
3377 &e);
3378 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003379 expectedDurationInfo.minDuration =
3380 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3381 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003382 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003383 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003384 break;
3385 default:
3386 find_camera_metadata_ro_entry(request,
3387 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3388 &e);
3389 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003390 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3391 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003392 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003393 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003394 break;
3395 }
3396
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003397 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003398}
3399
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003400bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3401 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3402 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3403 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3404 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3405 return true;
3406 }
3407
3408 return false;
3409}
3410
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003411void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3412 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003413 camera_capture_request_t& halRequest = nextRequest.halRequest;
3414 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003415 Mutex::Autolock al(mLatestRequestMutex);
3416
Shuzhen Wang83bff122020-11-20 15:51:39 -08003417 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003418 mLatestRequest.acquire(cloned);
3419
3420 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003421 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3422 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3423 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003424 CameraMetadata(cloned));
3425 }
3426
3427 sp<Camera3Device> parent = mParent.promote();
3428 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003429 int32_t inputStreamId = -1;
3430 if (halRequest.input_buffer != nullptr) {
3431 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3432 }
3433
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003434 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003435 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003436 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3437 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003438 }
3439 }
3440
Shuzhen Wang83bff122020-11-20 15:51:39 -08003441 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003442 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003443 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003444 }
3445
Shuzhen Wang83bff122020-11-20 15:51:39 -08003446 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003447}
3448
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003449bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3450 ATRACE_CALL();
3451 bool updatesDetected = false;
3452
Emilian Peev4ec17882019-01-24 17:16:58 -08003453 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003454 for (auto tag : mSessionParamKeys) {
3455 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003456 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003457
3458 if (entry.count > 0) {
3459 bool isDifferent = false;
3460 if (lastEntry.count > 0) {
3461 // Have a last value, compare to see if changed
3462 if (lastEntry.type == entry.type &&
3463 lastEntry.count == entry.count) {
3464 // Same type and count, compare values
3465 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3466 size_t entryBytes = bytesPerValue * lastEntry.count;
3467 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3468 if (cmp != 0) {
3469 isDifferent = true;
3470 }
3471 } else {
3472 // Count or type has changed
3473 isDifferent = true;
3474 }
3475 } else {
3476 // No last entry, so always consider to be different
3477 isDifferent = true;
3478 }
3479
3480 if (isDifferent) {
3481 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003482 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3483 updatesDetected = true;
3484 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003485 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003486 }
3487 } else if (lastEntry.count > 0) {
3488 // Value has been removed
3489 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003490 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003491 updatesDetected = true;
3492 }
3493 }
3494
Emilian Peev4ec17882019-01-24 17:16:58 -08003495 bool reconfigureRequired;
3496 if (updatesDetected) {
3497 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3498 updatedParams);
3499 mLatestSessionParams = updatedParams;
3500 } else {
3501 reconfigureRequired = false;
3502 }
3503
3504 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003505}
3506
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003507bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003508 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003509 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003510 // Any function called from threadLoop() must not hold mInterfaceLock since
3511 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3512 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003513
3514 // Handle paused state.
3515 if (waitIfPaused()) {
3516 return true;
3517 }
3518
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003519 // Wait for the next batch of requests.
3520 waitForNextRequestBatch();
3521 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003522 return true;
3523 }
3524
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003525 // Get the latest request ID, if any
3526 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003527 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003528 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003529 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003530 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003531 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003532 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3533 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003534 }
3535
Emilian Peevd865f0d2023-03-17 17:13:07 -07003536 for (size_t i = 0; i < mNextRequests.size(); i++) {
3537 auto& nextRequest = mNextRequests.editItemAt(i);
3538 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3539 // Do not override rotate&crop for stream configurations that include
3540 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3541 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3542 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3543 overrideAutoRotateAndCrop(captureRequest);
3544 captureRequest->mAutoframingChanged = overrideAutoframing(captureRequest);
3545 }
3546
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003547 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3548 // or a single request from streaming or burst. In either case the first element
3549 // should contain the latest camera settings that we need to check for any session
3550 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003551 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003552 res = OK;
3553
3554 //Input stream buffers are already acquired at this point so an input stream
3555 //will not be able to move to idle state unless we force it.
3556 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3557 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3558 if (res != OK) {
3559 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3560 cleanUpFailedRequests(/*sendRequestError*/ false);
3561 return false;
3562 }
3563 }
3564
3565 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003566 sp<Camera3Device> parent = mParent.promote();
3567 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003568 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3569 if (statusTracker != nullptr) {
3570 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3571 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003572 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003573 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003574 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003575
3576 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3577 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3578 if (res != OK) {
3579 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3580 cleanUpFailedRequests(/*sendRequestError*/ false);
3581 return false;
3582 }
3583 }
3584 }
3585 }
3586
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003587 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003588 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003589 if (res == TIMED_OUT) {
3590 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003591 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003592 // Check if any stream is abandoned.
3593 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003594 return true;
3595 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003596 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003597 return false;
3598 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003599
Zhijun Hecc27e112013-10-03 16:12:43 -07003600 // Inform waitUntilRequestProcessed thread of a new request ID
3601 {
3602 Mutex::Autolock al(mLatestRequestMutex);
3603
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003604 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003605 mLatestRequestSignal.signal();
3606 }
3607
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003608 // Submit a batch of requests to HAL.
3609 // Use flush lock only when submitting multilple requests in a batch.
3610 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3611 // which may take a long time to finish so synchronizing flush() and
3612 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3613 // For now, only synchronize for high speed recording and we should figure something out for
3614 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003615 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003616
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003617 if (useFlushLock) {
3618 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003619 }
3620
Zhijun Hef0645c12016-08-02 00:58:11 -07003621 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003622 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003623
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003624 sp<Camera3Device> parent = mParent.promote();
3625 if (parent != nullptr) {
3626 parent->mRequestBufferSM.onSubmittingRequest();
3627 }
3628
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003629 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003630 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003631 submitRequestSuccess = sendRequestsBatch();
3632
Shuzhen Wang686f6442017-06-20 16:16:04 -07003633 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3634 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003635
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003636 if (useFlushLock) {
3637 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003638 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003639
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003640 // Unset as current request
3641 {
3642 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003644 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003645 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003646
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003647 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003648}
3649
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003650status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3651 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3652 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3653 ANDROID_SCALER_CROP_REGION_SET};
3654 if (request == nullptr) {
3655 ALOGE("%s request metadata nullptr", __FUNCTION__);
3656 return BAD_VALUE;
3657 }
3658 status_t res = OK;
3659 for (const auto &key : kFwkOnlyRegionKeys) {
3660 if (request->exists(key)) {
3661 res = request->erase(key);
3662 if (res != OK) {
3663 return res;
3664 }
3665 }
3666 }
3667 return OK;
3668}
3669
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003670status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003671 ATRACE_CALL();
3672
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003673 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003674 for (size_t i = 0; i < mNextRequests.size(); i++) {
3675 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003676 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003677 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3678 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003679
3680 // Prepare a request to HAL
3681 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3682
3683 // Insert any queued triggers (before metadata is locked)
3684 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003685 if (res < 0) {
3686 SET_ERR("RequestThread: Unable to insert triggers "
3687 "(capture request %d, HAL device: %s (%d)",
3688 halRequest->frame_number, strerror(-res), res);
3689 return INVALID_OPERATION;
3690 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003691
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003692 int triggerCount = res;
3693 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3694 mPrevTriggers = triggerCount;
3695
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003696 bool testPatternChanged = overrideTestPattern(captureRequest);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003697 bool settingsOverrideChanged = overrideSettingsOverride(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003698
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003699 // If the request is the same as last, or we had triggers now or last time or
3700 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003701 bool newRequest =
Emilian Peevd865f0d2023-03-17 17:13:07 -07003702 (mPrevRequest != captureRequest || triggersMixedIn ||
3703 captureRequest->mRotateAndCropChanged ||
3704 captureRequest->mAutoframingChanged ||
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003705 testPatternChanged || settingsOverrideChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003706 // Request settings are all the same within one batch, so only treat the first
3707 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003708 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003709 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003710 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711 /**
3712 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003713 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003714 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003715 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003716 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003717 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003718 "(capture request %d, HAL device: %s (%d)",
3719 halRequest->frame_number, strerror(-res), res);
3720 return INVALID_OPERATION;
3721 }
3722
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003723 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003724 sp<Camera3Device> parent = mParent.promote();
3725 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003726 List<PhysicalCameraSettings>::iterator it;
3727 for (it = captureRequest->mSettingsList.begin();
3728 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003729 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3730 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003731 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3732 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3733 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3734 res);
3735 return INVALID_OPERATION;
3736 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003737 continue;
3738 }
3739
3740 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3741 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3742 updateCaptureRequest(&(it->metadata));
3743 if (res != OK) {
3744 SET_ERR("RequestThread: Unable to correct capture requests "
3745 "for scaler crop region and metering regions for request "
3746 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3747 res);
3748 return INVALID_OPERATION;
3749 }
3750 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003751 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3752 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3753 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3754 res);
3755 return INVALID_OPERATION;
3756 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003757 }
3758 }
3759
3760 // Correct metadata regions for distortion correction if enabled
3761 for (it = captureRequest->mSettingsList.begin();
3762 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003763 if (parent->mDistortionMappers.find(it->cameraId) ==
3764 parent->mDistortionMappers.end()) {
3765 continue;
3766 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003767
3768 if (!captureRequest->mDistortionCorrectionUpdated) {
3769 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3770 &(it->metadata));
3771 if (res != OK) {
3772 SET_ERR("RequestThread: Unable to correct capture requests "
3773 "for lens distortion for request %d: %s (%d)",
3774 halRequest->frame_number, strerror(-res), res);
3775 return INVALID_OPERATION;
3776 }
3777 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003778 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003779 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003780
3781 for (it = captureRequest->mSettingsList.begin();
3782 it != captureRequest->mSettingsList.end(); it++) {
3783 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3784 parent->mZoomRatioMappers.end()) {
3785 continue;
3786 }
3787
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003788 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003789 cameraIdsWithZoom.insert(it->cameraId);
3790 }
3791
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003792 if (!captureRequest->mZoomRatioUpdated) {
3793 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3794 &(it->metadata));
3795 if (res != OK) {
3796 SET_ERR("RequestThread: Unable to correct capture requests "
3797 "for zoom ratio for request %d: %s (%d)",
3798 halRequest->frame_number, strerror(-res), res);
3799 return INVALID_OPERATION;
3800 }
3801 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003802 }
3803 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003804 if (captureRequest->mRotateAndCropAuto &&
3805 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003806 for (it = captureRequest->mSettingsList.begin();
3807 it != captureRequest->mSettingsList.end(); it++) {
3808 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3809 if (mapper != parent->mRotateAndCropMappers.end()) {
3810 res = mapper->second.updateCaptureRequest(&(it->metadata));
3811 if (res != OK) {
3812 SET_ERR("RequestThread: Unable to correct capture requests "
3813 "for rotate-and-crop for request %d: %s (%d)",
3814 halRequest->frame_number, strerror(-res), res);
3815 return INVALID_OPERATION;
3816 }
3817 }
3818 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003819 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003820 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003821
3822 for (it = captureRequest->mSettingsList.begin();
3823 it != captureRequest->mSettingsList.end(); it++) {
3824 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3825 mVndkVersion, it->metadata, false /*isStatic*/);
3826 if (res != OK) {
3827 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3828 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3829 return INVALID_OPERATION;
3830 }
3831 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003832 }
3833 }
3834
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003835 /**
3836 * The request should be presorted so accesses in HAL
3837 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3838 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003839 captureRequest->mSettingsList.begin()->metadata.sort();
3840 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003841 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003842 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003843 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3844
3845 IF_ALOGV() {
3846 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3847 find_camera_metadata_ro_entry(
3848 halRequest->settings,
3849 ANDROID_CONTROL_AF_TRIGGER,
3850 &e
3851 );
3852 if (e.count > 0) {
3853 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3854 __FUNCTION__,
3855 halRequest->frame_number,
3856 e.data.u8[0]);
3857 }
3858 }
3859 } else {
3860 // leave request.settings NULL to indicate 'reuse latest given'
3861 ALOGVV("%s: Request settings are REUSED",
3862 __FUNCTION__);
3863 }
3864
Emilian Peevaebbe412018-01-15 13:53:24 +00003865 if (captureRequest->mSettingsList.size() > 1) {
3866 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3867 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003868 if (newRequest) {
3869 halRequest->physcam_settings =
3870 new const camera_metadata* [halRequest->num_physcam_settings];
3871 } else {
3872 halRequest->physcam_settings = nullptr;
3873 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003874 auto it = ++captureRequest->mSettingsList.begin();
3875 size_t i = 0;
3876 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3877 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003878 if (newRequest) {
3879 it->metadata.sort();
3880 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3881 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003882 }
3883 }
3884
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003885 uint32_t totalNumBuffers = 0;
3886
3887 // Fill in buffers
3888 if (captureRequest->mInputStream != NULL) {
3889 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003890
3891 halRequest->input_width = captureRequest->mInputBufferSize.width;
3892 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003893 totalNumBuffers += 1;
3894 } else {
3895 halRequest->input_buffer = NULL;
3896 }
3897
Emilian Peevf4816702020-04-03 15:44:51 -07003898 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003899 captureRequest->mOutputStreams.size());
3900 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003901 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003902
3903 sp<Camera3Device> parent = mParent.promote();
3904 if (parent == NULL) {
3905 // Should not happen, and nowhere to send errors to, so just log it
3906 CLOGE("RequestThread: Parent is gone");
3907 return INVALID_OPERATION;
3908 }
3909 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3910
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003911 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003912 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003913 sp<Camera3OutputStreamInterface> outputStream =
3914 captureRequest->mOutputStreams.editItemAt(j);
3915 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003916
3917 // Prepare video buffers for high speed recording on the first video request.
3918 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3919 // Only try to prepare video stream on the first video request.
3920 mPrepareVideoStream = false;
3921
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003922 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3923 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003924 while (res == NOT_ENOUGH_DATA) {
3925 res = outputStream->prepareNextBuffer();
3926 }
3927 if (res != OK) {
3928 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3929 __FUNCTION__, strerror(-res), res);
3930 outputStream->cancelPrepare();
3931 }
3932 }
3933
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003934 std::vector<size_t> uniqueSurfaceIds;
3935 res = outputStream->getUniqueSurfaceIds(
3936 captureRequest->mOutputSurfaces[streamId],
3937 &uniqueSurfaceIds);
3938 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3939 if (res != OK && res != INVALID_OPERATION) {
3940 ALOGE("%s: failed to query stream %d unique surface IDs",
3941 __FUNCTION__, streamId);
3942 return res;
3943 }
3944 if (res == OK) {
3945 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3946 }
3947
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003948 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003949 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003950 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003951 return TIMED_OUT;
3952 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003953 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003954 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003955 buffer.stream = outputStream->asHalStream();
3956 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003957 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003958 buffer.acquire_fence = -1;
3959 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003960 // Mark the output stream as unpreparable to block clients from calling
3961 // 'prepare' after this request reaches CameraHal and before the respective
3962 // buffers are requested.
3963 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003964 } else {
3965 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3966 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003967 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003968 if (res != OK) {
3969 // Can't get output buffer from gralloc queue - this could be due to
3970 // abandoned queue or other consumer misbehavior, so not a fatal
3971 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003972 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003973 " %s (%d)", strerror(-res), res);
3974
3975 return TIMED_OUT;
3976 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003977 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003978
3979 {
3980 sp<Camera3Device> parent = mParent.promote();
3981 if (parent != nullptr) {
3982 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3983 for (const auto& settings : captureRequest->mSettingsList) {
3984 if ((streamCameraId.isEmpty() &&
3985 parent->getId() == settings.cameraId.c_str()) ||
3986 streamCameraId == settings.cameraId.c_str()) {
3987 outputStream->fireBufferRequestForFrameNumber(
3988 captureRequest->mResultExtras.frameNumber,
3989 settings.metadata);
3990 }
3991 }
3992 }
3993 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003994
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003995 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003996 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3997 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3998 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3999 } else if (!physicalCameraId.isEmpty()) {
4000 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004001 }
4002 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004003 }
4004 totalNumBuffers += halRequest->num_output_buffers;
4005
4006 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004007 // If this request list is for constrained high speed recording (not
4008 // preview), and the current request is not the last one in the batch,
4009 // do not send callback to the app.
4010 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004011 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004012 hasCallback = false;
4013 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004014 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004015 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004016 const camera_metadata_t* settings = halRequest->settings;
4017 bool shouldUnlockSettings = false;
4018 if (settings == nullptr) {
4019 shouldUnlockSettings = true;
4020 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4021 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004022 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4023 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004024 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004025 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4026 isStillCapture = true;
4027 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4028 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004029
Emilian Peevaf8416e2021-02-04 17:52:43 -08004030 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004031 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004032 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4033 isZslCapture = true;
4034 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004035 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004036 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004037 res = parent->registerInFlight(halRequest->frame_number,
4038 totalNumBuffers, captureRequest->mResultExtras,
4039 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004040 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004041 expectedDurationInfo.minDuration,
4042 expectedDurationInfo.maxDuration,
4043 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004044 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004045 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
4046 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004047 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004048 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004049 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4050 ", burstId = %" PRId32 ".",
4051 __FUNCTION__,
4052 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4053 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004054
4055 if (shouldUnlockSettings) {
4056 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4057 }
4058
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 if (res != OK) {
4060 SET_ERR("RequestThread: Unable to register new in-flight request:"
4061 " %s (%d)", strerror(-res), res);
4062 return INVALID_OPERATION;
4063 }
4064 }
4065
4066 return OK;
4067}
4068
Igor Murashkin1e479c02013-09-06 16:55:14 -07004069CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004070 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004071 Mutex::Autolock al(mLatestRequestMutex);
4072
4073 ALOGV("RequestThread::%s", __FUNCTION__);
4074
4075 return mLatestRequest;
4076}
4077
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004078bool Camera3Device::RequestThread::isStreamPending(
4079 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004080 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004081 Mutex::Autolock l(mRequestLock);
4082
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004084 if (!nextRequest.submitted) {
4085 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4086 if (stream == s) return true;
4087 }
4088 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004089 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004090 }
4091
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004092 for (const auto& request : mRequestQueue) {
4093 for (const auto& s : request->mOutputStreams) {
4094 if (stream == s) return true;
4095 }
4096 if (stream == request->mInputStream) return true;
4097 }
4098
4099 for (const auto& request : mRepeatingRequests) {
4100 for (const auto& s : request->mOutputStreams) {
4101 if (stream == s) return true;
4102 }
4103 if (stream == request->mInputStream) return true;
4104 }
4105
4106 return false;
4107}
Jianing Weicb0652e2014-03-12 18:29:36 -07004108
Emilian Peev40ead602017-09-26 15:46:36 +01004109bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4110 ATRACE_CALL();
4111 Mutex::Autolock l(mRequestLock);
4112
4113 for (const auto& nextRequest : mNextRequests) {
4114 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4115 if (s.first == streamId) {
4116 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4117 if (it != s.second.end()) {
4118 return true;
4119 }
4120 }
4121 }
4122 }
4123
4124 for (const auto& request : mRequestQueue) {
4125 for (const auto& s : request->mOutputSurfaces) {
4126 if (s.first == streamId) {
4127 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4128 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004129 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004130 }
4131 }
4132 }
4133 }
4134
4135 for (const auto& request : mRepeatingRequests) {
4136 for (const auto& s : request->mOutputSurfaces) {
4137 if (s.first == streamId) {
4138 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4139 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004140 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004141 }
4142 }
4143 }
4144 }
4145
4146 return false;
4147}
4148
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004149void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4150 if (!mUseHalBufManager) {
4151 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4152 return;
4153 }
4154
4155 Mutex::Autolock pl(mPauseLock);
4156 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004157 mInterface->signalPipelineDrain(streamIds);
4158 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004159 }
4160 // If request thread is still busy, wait until paused then notify HAL
4161 mNotifyPipelineDrain = true;
4162 mStreamIdsToBeDrained = streamIds;
4163}
4164
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004165void Camera3Device::RequestThread::resetPipelineDrain() {
4166 Mutex::Autolock pl(mPauseLock);
4167 mNotifyPipelineDrain = false;
4168 mStreamIdsToBeDrained.clear();
4169}
4170
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004171void Camera3Device::RequestThread::clearPreviousRequest() {
4172 Mutex::Autolock l(mRequestLock);
4173 mPrevRequest.clear();
4174}
4175
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004176status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4177 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4178 ATRACE_CALL();
4179 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004180 mRotateAndCropOverride = rotateAndCropValue;
4181 return OK;
4182}
4183
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004184status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4185 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4186 ATRACE_CALL();
4187 Mutex::Autolock l(mTriggerMutex);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004188 mAutoframingOverride = autoframingValue;
4189 return OK;
4190}
4191
Emilian Peeve23f1d92021-09-20 14:56:01 -07004192status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4193 ATRACE_CALL();
4194 Mutex::Autolock l(mTriggerMutex);
4195 mComposerOutput = composerSurfacePresent;
4196 return OK;
4197}
4198
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004199status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004200 ATRACE_CALL();
4201 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004202 if (muteMode != mCameraMute) {
4203 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004204 mCameraMuteChanged = true;
4205 }
4206 return OK;
4207}
4208
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004209status_t Camera3Device::RequestThread::setZoomOverride(int32_t zoomOverride) {
4210 ATRACE_CALL();
4211 Mutex::Autolock l(mTriggerMutex);
4212 mSettingsOverride = zoomOverride;
4213 return OK;
4214}
4215
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004216nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004217 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004218 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004219 return mExpectedInflightDuration > kMinInflightDuration ?
4220 mExpectedInflightDuration : kMinInflightDuration;
4221}
4222
Emilian Peevaebbe412018-01-15 13:53:24 +00004223void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004224 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004225 if ((request == nullptr) || (halRequest == nullptr)) {
4226 ALOGE("%s: Invalid request!", __FUNCTION__);
4227 return;
4228 }
4229
4230 if (halRequest->num_physcam_settings > 0) {
4231 if (halRequest->physcam_id != nullptr) {
4232 delete [] halRequest->physcam_id;
4233 halRequest->physcam_id = nullptr;
4234 }
4235 if (halRequest->physcam_settings != nullptr) {
4236 auto it = ++(request->mSettingsList.begin());
4237 size_t i = 0;
4238 for (; it != request->mSettingsList.end(); it++, i++) {
4239 it->metadata.unlock(halRequest->physcam_settings[i]);
4240 }
4241 delete [] halRequest->physcam_settings;
4242 halRequest->physcam_settings = nullptr;
4243 }
4244 }
4245}
4246
Ravneetaeb20dc2022-03-30 05:33:03 +00004247status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4248 Mutex::Autolock il(mInterfaceLock);
4249 Mutex::Autolock l(mLock);
4250
4251 if (mCameraServiceWatchdog != NULL) {
4252 mCameraServiceWatchdog->setEnabled(enabled);
4253 }
4254
4255 return OK;
4256}
4257
Shuzhen Wang16610a62022-12-15 22:38:07 -08004258void Camera3Device::setStreamUseCaseOverrides(
4259 const std::vector<int64_t>& useCaseOverrides) {
4260 Mutex::Autolock il(mInterfaceLock);
4261 Mutex::Autolock l(mLock);
4262 mStreamUseCaseOverrides = useCaseOverrides;
4263}
4264
4265void Camera3Device::clearStreamUseCaseOverrides() {
4266 Mutex::Autolock il(mInterfaceLock);
4267 Mutex::Autolock l(mLock);
4268 mStreamUseCaseOverrides.clear();
4269}
4270
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004271bool Camera3Device::hasDeviceError() {
4272 Mutex::Autolock il(mInterfaceLock);
4273 Mutex::Autolock l(mLock);
4274 return mStatus == STATUS_ERROR;
4275}
4276
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004277void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4278 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004279 return;
4280 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004281
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004282 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004283 // Skip the ones that have been submitted successfully.
4284 if (nextRequest.submitted) {
4285 continue;
4286 }
4287
4288 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004289 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4290 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004291
4292 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004293 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004294 }
4295
Emilian Peevaebbe412018-01-15 13:53:24 +00004296 cleanupPhysicalSettings(captureRequest, halRequest);
4297
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004298 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004299 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004300 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4301 }
4302
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004303 // No output buffer can be returned when using HAL buffer manager
4304 if (!mUseHalBufManager) {
4305 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4306 //Buffers that failed processing could still have
4307 //valid acquire fence.
4308 int acquireFence = (*outputBuffers)[i].acquire_fence;
4309 if (0 <= acquireFence) {
4310 close(acquireFence);
4311 outputBuffers->editItemAt(i).acquire_fence = -1;
4312 }
Emilian Peevf4816702020-04-03 15:44:51 -07004313 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004314 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4315 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004316 /*timestampIncreasing*/true, std::vector<size_t> (),
4317 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004318 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004319 }
4320
4321 if (sendRequestError) {
4322 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004323 sp<NotificationListener> listener = mListener.promote();
4324 if (listener != NULL) {
4325 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004326 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004327 captureRequest->mResultExtras);
4328 }
4329 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004330
4331 // Remove yet-to-be submitted inflight request from inflightMap
4332 {
4333 sp<Camera3Device> parent = mParent.promote();
4334 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004335 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004336 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4337 if (idx >= 0) {
4338 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4339 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4340 parent->removeInFlightMapEntryLocked(idx);
4341 }
4342 }
4343 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004344 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004345
4346 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004347 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348}
4349
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004350void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004351 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352 // Optimized a bit for the simple steady-state case (single repeating
4353 // request), to avoid putting that request in the queue temporarily.
4354 Mutex::Autolock l(mRequestLock);
4355
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356 assert(mNextRequests.empty());
4357
4358 NextRequest nextRequest;
4359 nextRequest.captureRequest = waitForNextRequestLocked();
4360 if (nextRequest.captureRequest == nullptr) {
4361 return;
4362 }
4363
Emilian Peevf4816702020-04-03 15:44:51 -07004364 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004365 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004366 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004367
4368 // Wait for additional requests
4369 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4370
4371 for (size_t i = 1; i < batchSize; i++) {
4372 NextRequest additionalRequest;
4373 additionalRequest.captureRequest = waitForNextRequestLocked();
4374 if (additionalRequest.captureRequest == nullptr) {
4375 break;
4376 }
4377
Emilian Peevf4816702020-04-03 15:44:51 -07004378 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004379 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004380 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381 }
4382
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004383 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004384 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004385 mNextRequests.size(), batchSize);
4386 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004387 }
4388
4389 return;
4390}
4391
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004392void Camera3Device::RequestThread::setRequestClearing() {
4393 Mutex::Autolock l(mRequestLock);
4394 mRequestClearing = true;
4395}
4396
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004397sp<Camera3Device::CaptureRequest>
4398 Camera3Device::RequestThread::waitForNextRequestLocked() {
4399 status_t res;
4400 sp<CaptureRequest> nextRequest;
4401
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004402 while (mRequestQueue.empty()) {
4403 if (!mRepeatingRequests.empty()) {
4404 // Always atomically enqueue all requests in a repeating request
4405 // list. Guarantees a complete in-sequence set of captures to
4406 // application.
4407 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004408 if (mFirstRepeating) {
4409 mFirstRepeating = false;
4410 } else {
4411 for (auto& request : requests) {
4412 // For repeating requests, override timestamp request using
4413 // the time a request is inserted into the request queue,
4414 // because the original repeating request will have an old
4415 // fixed timestamp.
4416 request->mRequestTimeNs = systemTime();
4417 }
4418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004419 RequestList::const_iterator firstRequest =
4420 requests.begin();
4421 nextRequest = *firstRequest;
4422 mRequestQueue.insert(mRequestQueue.end(),
4423 ++firstRequest,
4424 requests.end());
4425 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004426
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004427 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004428
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004429 break;
4430 }
4431
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004432 if (!mRequestClearing) {
4433 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4434 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004435
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004436 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4437 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004438 Mutex::Autolock pl(mPauseLock);
4439 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004440 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004441 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004442 if (mNotifyPipelineDrain) {
4443 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4444 mNotifyPipelineDrain = false;
4445 mStreamIdsToBeDrained.clear();
4446 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004447 // Let the tracker know
4448 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4449 if (statusTracker != 0) {
4450 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4451 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004452 sp<Camera3Device> parent = mParent.promote();
4453 if (parent != nullptr) {
4454 parent->mRequestBufferSM.onRequestThreadPaused();
4455 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004456 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004457 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004458 // Stop waiting for now and let thread management happen
4459 return NULL;
4460 }
4461 }
4462
4463 if (nextRequest == NULL) {
4464 // Don't have a repeating request already in hand, so queue
4465 // must have an entry now.
4466 RequestList::iterator firstRequest =
4467 mRequestQueue.begin();
4468 nextRequest = *firstRequest;
4469 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004470 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4471 sp<NotificationListener> listener = mListener.promote();
4472 if (listener != NULL) {
4473 listener->notifyRequestQueueEmpty();
4474 }
4475 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004476 }
4477
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004478 // In case we've been unpaused by setPaused clearing mDoPause, need to
4479 // update internal pause state (capture/setRepeatingRequest unpause
4480 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004481 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004482 if (mPaused) {
4483 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4484 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4485 if (statusTracker != 0) {
4486 statusTracker->markComponentActive(mStatusId);
4487 }
4488 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004489 mPaused = false;
4490
4491 // Check if we've reconfigured since last time, and reset the preview
4492 // request if so. Can't use 'NULL request == repeat' across configure calls.
4493 if (mReconfigured) {
4494 mPrevRequest.clear();
4495 mReconfigured = false;
4496 }
4497
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004498 if (nextRequest != NULL) {
4499 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004500 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4501 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004502
4503 // Since RequestThread::clear() removes buffers from the input stream,
4504 // get the right buffer here before unlocking mRequestLock
4505 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004506 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4507 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004508 if (res != OK) {
4509 // Can't get input buffer from gralloc queue - this could be due to
4510 // disconnected queue or other producer misbehavior, so not a fatal
4511 // error
4512 ALOGE("%s: Can't get input buffer, skipping request:"
4513 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004514
4515 sp<NotificationListener> listener = mListener.promote();
4516 if (listener != NULL) {
4517 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004518 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004519 nextRequest->mResultExtras);
4520 }
4521 return NULL;
4522 }
4523 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004524 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004525
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004526 return nextRequest;
4527}
4528
4529bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004530 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004531 status_t res;
4532 Mutex::Autolock l(mPauseLock);
4533 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004534 if (mPaused == false) {
4535 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004536 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004537 if (mNotifyPipelineDrain) {
4538 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4539 mNotifyPipelineDrain = false;
4540 mStreamIdsToBeDrained.clear();
4541 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004542 // Let the tracker know
4543 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4544 if (statusTracker != 0) {
4545 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4546 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004547 sp<Camera3Device> parent = mParent.promote();
4548 if (parent != nullptr) {
4549 parent->mRequestBufferSM.onRequestThreadPaused();
4550 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004551 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004553 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004554 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004555 return true;
4556 }
4557 }
4558 // We don't set mPaused to false here, because waitForNextRequest needs
4559 // to further manage the paused state in case of starvation.
4560 return false;
4561}
4562
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004563void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004564 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004565 // With work to do, mark thread as unpaused.
4566 // If paused by request (setPaused), don't resume, to avoid
4567 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004568 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004569 Mutex::Autolock p(mPauseLock);
4570 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004571 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4572 if (mPaused) {
4573 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4574 if (statusTracker != 0) {
4575 statusTracker->markComponentActive(mStatusId);
4576 }
4577 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004578 mPaused = false;
4579 }
4580}
4581
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004582void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4583 sp<Camera3Device> parent = mParent.promote();
4584 if (parent != NULL) {
4585 va_list args;
4586 va_start(args, fmt);
4587
4588 parent->setErrorStateV(fmt, args);
4589
4590 va_end(args);
4591 }
4592}
4593
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004594status_t Camera3Device::RequestThread::insertTriggers(
4595 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004596 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004597 Mutex::Autolock al(mTriggerMutex);
4598
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004599 sp<Camera3Device> parent = mParent.promote();
4600 if (parent == NULL) {
4601 CLOGE("RequestThread: Parent is gone");
4602 return DEAD_OBJECT;
4603 }
4604
Emilian Peevaebbe412018-01-15 13:53:24 +00004605 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004606 size_t count = mTriggerMap.size();
4607
4608 for (size_t i = 0; i < count; ++i) {
4609 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004610 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004611
4612 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4613 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4614 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004615 if (isAeTrigger) {
4616 request->mResultExtras.precaptureTriggerId = triggerId;
4617 mCurrentPreCaptureTriggerId = triggerId;
4618 } else {
4619 request->mResultExtras.afTriggerId = triggerId;
4620 mCurrentAfTriggerId = triggerId;
4621 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004622 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004623 }
4624
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004625 camera_metadata_entry entry = metadata.find(tag);
4626
4627 if (entry.count > 0) {
4628 /**
4629 * Already has an entry for this trigger in the request.
4630 * Rewrite it with our requested trigger value.
4631 */
4632 RequestTrigger oldTrigger = trigger;
4633
4634 oldTrigger.entryValue = entry.data.u8[0];
4635
4636 mTriggerReplacedMap.add(tag, oldTrigger);
4637 } else {
4638 /**
4639 * More typical, no trigger entry, so we just add it
4640 */
4641 mTriggerRemovedMap.add(tag, trigger);
4642 }
4643
4644 status_t res;
4645
4646 switch (trigger.getTagType()) {
4647 case TYPE_BYTE: {
4648 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4649 res = metadata.update(tag,
4650 &entryValue,
4651 /*count*/1);
4652 break;
4653 }
4654 case TYPE_INT32:
4655 res = metadata.update(tag,
4656 &trigger.entryValue,
4657 /*count*/1);
4658 break;
4659 default:
4660 ALOGE("%s: Type not supported: 0x%x",
4661 __FUNCTION__,
4662 trigger.getTagType());
4663 return INVALID_OPERATION;
4664 }
4665
4666 if (res != OK) {
4667 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4668 ", value %d", __FUNCTION__, trigger.getTagName(),
4669 trigger.entryValue);
4670 return res;
4671 }
4672
4673 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4674 trigger.getTagName(),
4675 trigger.entryValue);
4676 }
4677
4678 mTriggerMap.clear();
4679
4680 return count;
4681}
4682
4683status_t Camera3Device::RequestThread::removeTriggers(
4684 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004685 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004686 Mutex::Autolock al(mTriggerMutex);
4687
Emilian Peevaebbe412018-01-15 13:53:24 +00004688 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004689
4690 /**
4691 * Replace all old entries with their old values.
4692 */
4693 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4694 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4695
4696 status_t res;
4697
4698 uint32_t tag = trigger.metadataTag;
4699 switch (trigger.getTagType()) {
4700 case TYPE_BYTE: {
4701 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4702 res = metadata.update(tag,
4703 &entryValue,
4704 /*count*/1);
4705 break;
4706 }
4707 case TYPE_INT32:
4708 res = metadata.update(tag,
4709 &trigger.entryValue,
4710 /*count*/1);
4711 break;
4712 default:
4713 ALOGE("%s: Type not supported: 0x%x",
4714 __FUNCTION__,
4715 trigger.getTagType());
4716 return INVALID_OPERATION;
4717 }
4718
4719 if (res != OK) {
4720 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4721 ", trigger value %d", __FUNCTION__,
4722 trigger.getTagName(), trigger.entryValue);
4723 return res;
4724 }
4725 }
4726 mTriggerReplacedMap.clear();
4727
4728 /**
4729 * Remove all new entries.
4730 */
4731 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4732 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4733 status_t res = metadata.erase(trigger.metadataTag);
4734
4735 if (res != OK) {
4736 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4737 ", trigger value %d", __FUNCTION__,
4738 trigger.getTagName(), trigger.entryValue);
4739 return res;
4740 }
4741 }
4742 mTriggerRemovedMap.clear();
4743
4744 return OK;
4745}
4746
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004747status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004748 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004749 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004750 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004751 status_t res;
4752
Emilian Peevaebbe412018-01-15 13:53:24 +00004753 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004754
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004755 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004756 // exists
4757 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4758 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4759 if (afTrigger.count > 0 &&
4760 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4761 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004762 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004763 if (res != OK) return res;
4764 }
4765
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004766 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004767 // if none already exists
4768 camera_metadata_entry pcTrigger =
4769 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4770 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4771 if (pcTrigger.count > 0 &&
4772 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4773 pcId.count == 0) {
4774 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004775 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004776 if (res != OK) return res;
4777 }
4778
4779 return OK;
4780}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004781
Emilian Peevd865f0d2023-03-17 17:13:07 -07004782bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4783 ATRACE_CALL();
4784 Mutex::Autolock l(mTriggerMutex);
4785 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4786 this->mRotateAndCropOverride);
4787}
4788
4789bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4790 bool overrideToPortrait,
4791 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004792 ATRACE_CALL();
4793
Emilian Peevd865f0d2023-03-17 17:13:07 -07004794 if (overrideToPortrait) {
4795 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger18b30a72022-10-27 12:20:29 -07004796 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4797 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4798 &rotateAndCrop_u8, 1);
4799 return true;
4800 }
4801
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004802 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004803 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4804
4805 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4806 if (rotateAndCropEntry.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004807 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004808 return false;
4809 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004810 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004811 return true;
4812 }
4813 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004814 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4815 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004816 return true;
4817 }
4818 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004819
4820 return false;
4821}
4822
4823bool Camera3Device::overrideAutoframing(const sp<CaptureRequest> &request /*out*/,
4824 camera_metadata_enum_android_control_autoframing_t autoframingOverride) {
4825 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4826 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4827 if (autoframingEntry.count > 0) {
4828 if (autoframingEntry.data.u8[0] == autoframingOverride) {
4829 return false;
4830 } else {
4831 autoframingEntry.data.u8[0] = autoframingOverride;
4832 return true;
4833 }
4834 } else {
4835 uint8_t autoframing_u8 = autoframingOverride;
4836 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4837 &autoframing_u8, 1);
4838 return true;
4839 }
4840
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004841 return false;
4842}
4843
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004844bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4845 ATRACE_CALL();
4846
4847 if (request->mAutoframingAuto) {
4848 Mutex::Autolock l(mTriggerMutex);
Emilian Peevd865f0d2023-03-17 17:13:07 -07004849 return Camera3Device::overrideAutoframing(request, mAutoframingOverride);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004850 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004851
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004852 return false;
4853}
4854
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004855bool Camera3Device::RequestThread::overrideTestPattern(
4856 const sp<CaptureRequest> &request) {
4857 ATRACE_CALL();
4858
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004859 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004860
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004861 Mutex::Autolock l(mTriggerMutex);
4862
4863 bool changed = false;
4864
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004865 // For a multi-camera, the physical cameras support the same set of
4866 // test pattern modes as the logical camera.
4867 for (auto& settings : request->mSettingsList) {
4868 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004869
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004870 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4871 int32_t testPatternData[4] = {
4872 settings.mOriginalTestPatternData[0],
4873 settings.mOriginalTestPatternData[1],
4874 settings.mOriginalTestPatternData[2],
4875 settings.mOriginalTestPatternData[3]
4876 };
4877 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4878 testPatternMode = mCameraMute;
4879 testPatternData[0] = 0;
4880 testPatternData[1] = 0;
4881 testPatternData[2] = 0;
4882 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004883 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004884
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004885 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4886 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4887 if (testPatternEntry.count > 0) {
4888 if (testPatternEntry.data.i32[0] != testPatternMode) {
4889 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004890 changed = true;
4891 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004892 } else if (supportTestPatternModeKey) {
4893 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4894 &testPatternMode, 1);
4895 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004896 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004897
4898 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4899 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4900 if (testPatternColor.count >= 4) {
4901 for (size_t i = 0; i < 4; i++) {
4902 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4903 testPatternColor.data.i32[i] = testPatternData[i];
4904 changed = true;
4905 }
4906 }
4907 } else if (supportTestPatternDataKey) {
4908 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4909 testPatternData, 4);
4910 changed = true;
4911 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004912 }
4913
4914 return changed;
4915}
4916
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004917bool Camera3Device::RequestThread::overrideSettingsOverride(
4918 const sp<CaptureRequest> &request) {
4919 ATRACE_CALL();
4920
4921 if (!mSupportSettingsOverride) return false;
4922
4923 Mutex::Autolock l(mTriggerMutex);
4924
4925 // For a multi-camera, only override the logical camera's metadata.
4926 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4927 camera_metadata_entry entry = metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
4928 int32_t originalValue = request->mSettingsList.begin()->mOriginalSettingsOverride;
4929 if (mSettingsOverride != -1 &&
4930 (entry.count == 0 || entry.data.i32[0] != mSettingsOverride)) {
4931 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4932 &mSettingsOverride, 1);
4933 return true;
4934 } else if (mSettingsOverride == -1 &&
4935 (entry.count == 0 || entry.data.i32[0] != originalValue)) {
4936 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4937 &originalValue, 1);
4938 return true;
4939 }
4940
4941 return false;
4942}
4943
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004944status_t Camera3Device::RequestThread::setHalInterface(
4945 sp<HalInterface> newHalInterface) {
4946 if (newHalInterface.get() == nullptr) {
4947 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4948 return DEAD_OBJECT;
4949 }
4950
4951 mInterface = newHalInterface;
4952
4953 return OK;
4954}
4955
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004956/**
4957 * PreparerThread inner class methods
4958 */
4959
4960Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004961 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004962 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004963}
4964
4965Camera3Device::PreparerThread::~PreparerThread() {
4966 Thread::requestExitAndWait();
4967 if (mCurrentStream != nullptr) {
4968 mCurrentStream->cancelPrepare();
4969 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4970 mCurrentStream.clear();
4971 }
4972 clear();
4973}
4974
Ruben Brunkc78ac262015-08-13 17:58:46 -07004975status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004976 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004977 status_t res;
4978
4979 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004980 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004981
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004982 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004983 if (res == OK) {
4984 // No preparation needed, fire listener right off
4985 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004986 if (listener != NULL) {
4987 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004988 }
4989 return OK;
4990 } else if (res != NOT_ENOUGH_DATA) {
4991 return res;
4992 }
4993
4994 // Need to prepare, start up thread if necessary
4995 if (!mActive) {
4996 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4997 // isn't running
4998 Thread::requestExitAndWait();
4999 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5000 if (res != OK) {
5001 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005002 if (listener != NULL) {
5003 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004 }
5005 return res;
5006 }
5007 mCancelNow = false;
5008 mActive = true;
5009 ALOGV("%s: Preparer stream started", __FUNCTION__);
5010 }
5011
5012 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005013 mPendingStreams.push_back(
5014 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005015 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5016
5017 return OK;
5018}
5019
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005020void Camera3Device::PreparerThread::pause() {
5021 ATRACE_CALL();
5022
5023 Mutex::Autolock l(mLock);
5024
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005025 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
5026 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005027 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5028 int currentMaxCount = mCurrentMaxCount;
5029 mPendingStreams.clear();
5030 mCancelNow = true;
5031 while (mActive) {
5032 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5033 if (res == TIMED_OUT) {
5034 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5035 return;
5036 } else if (res != OK) {
5037 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5038 return;
5039 }
5040 }
5041
5042 //Check whether the prepare thread was able to complete the current
5043 //stream. In case work is still pending emplace it along with the rest
5044 //of the streams in the pending list.
5045 if (currentStream != nullptr) {
5046 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005047 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005048 }
5049 }
5050
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005051 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005052 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005053 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005054 }
5055}
5056
5057status_t Camera3Device::PreparerThread::resume() {
5058 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005059 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005060 status_t res;
5061
5062 Mutex::Autolock l(mLock);
5063 sp<NotificationListener> listener = mListener.promote();
5064
5065 if (mActive) {
5066 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5067 return NO_INIT;
5068 }
5069
5070 auto it = mPendingStreams.begin();
5071 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005072 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005073 if (res == OK) {
5074 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005075 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005076 }
5077 it = mPendingStreams.erase(it);
5078 } else if (res != NOT_ENOUGH_DATA) {
5079 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5080 res, strerror(-res));
5081 it = mPendingStreams.erase(it);
5082 } else {
5083 it++;
5084 }
5085 }
5086
5087 if (mPendingStreams.empty()) {
5088 return OK;
5089 }
5090
5091 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5092 if (res != OK) {
5093 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5094 __FUNCTION__, res, strerror(-res));
5095 return res;
5096 }
5097 mCancelNow = false;
5098 mActive = true;
5099 ALOGV("%s: Preparer stream started", __FUNCTION__);
5100
5101 return OK;
5102}
5103
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005104status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005105 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005106 Mutex::Autolock l(mLock);
5107
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005108 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005109 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005110 }
5111 mPendingStreams.clear();
5112 mCancelNow = true;
5113
5114 return OK;
5115}
5116
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005117void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005118 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005119 Mutex::Autolock l(mLock);
5120 mListener = listener;
5121}
5122
5123bool Camera3Device::PreparerThread::threadLoop() {
5124 status_t res;
5125 {
5126 Mutex::Autolock l(mLock);
5127 if (mCurrentStream == nullptr) {
5128 // End thread if done with work
5129 if (mPendingStreams.empty()) {
5130 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5131 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5132 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5133 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005134 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005135 return false;
5136 }
5137
5138 // Get next stream to prepare
5139 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005140 mCurrentMaxCount = std::get<0>(*it);
5141 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005142 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005143 mPendingStreams.erase(it);
5144 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5145 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5146 } else if (mCancelNow) {
5147 mCurrentStream->cancelPrepare();
5148 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5149 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5150 mCurrentStream.clear();
5151 mCancelNow = false;
5152 return true;
5153 }
5154 }
5155
5156 res = mCurrentStream->prepareNextBuffer();
5157 if (res == NOT_ENOUGH_DATA) return true;
5158 if (res != OK) {
5159 // Something bad happened; try to recover by cancelling prepare and
5160 // signalling listener anyway
5161 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5162 mCurrentStream->getId(), res, strerror(-res));
5163 mCurrentStream->cancelPrepare();
5164 }
5165
5166 // This stream has finished, notify listener
5167 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005168 sp<NotificationListener> listener = mListener.promote();
5169 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005170 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5171 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005172 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005173 }
5174
5175 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5176 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005177 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005178
5179 return true;
5180}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005181
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005182status_t Camera3Device::RequestBufferStateMachine::initialize(
5183 sp<camera3::StatusTracker> statusTracker) {
5184 if (statusTracker == nullptr) {
5185 ALOGE("%s: statusTracker is null", __FUNCTION__);
5186 return BAD_VALUE;
5187 }
5188
5189 std::lock_guard<std::mutex> lock(mLock);
5190 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005191 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005192 return OK;
5193}
5194
5195bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5196 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005197 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005198 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005199 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005200 return true;
5201 }
5202 return false;
5203}
5204
5205void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5206 std::lock_guard<std::mutex> lock(mLock);
5207 if (!mRequestBufferOngoing) {
5208 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5209 return;
5210 }
5211 mRequestBufferOngoing = false;
5212 if (mStatus == RB_STATUS_PENDING_STOP) {
5213 checkSwitchToStopLocked();
5214 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005215 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005216}
5217
5218void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5219 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005220 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005221 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005222 return;
5223}
5224
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005225void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005226 std::lock_guard<std::mutex> lock(mLock);
5227 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005228 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5229 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005230 mInflightMapEmpty = false;
5231 if (mStatus == RB_STATUS_STOPPED) {
5232 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005233 }
5234 return;
5235}
5236
5237void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5238 std::lock_guard<std::mutex> lock(mLock);
5239 mRequestThreadPaused = true;
5240 if (mStatus == RB_STATUS_PENDING_STOP) {
5241 checkSwitchToStopLocked();
5242 }
5243 return;
5244}
5245
5246void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5247 std::lock_guard<std::mutex> lock(mLock);
5248 mInflightMapEmpty = true;
5249 if (mStatus == RB_STATUS_PENDING_STOP) {
5250 checkSwitchToStopLocked();
5251 }
5252 return;
5253}
5254
5255void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5256 std::lock_guard<std::mutex> lock(mLock);
5257 if (!checkSwitchToStopLocked()) {
5258 mStatus = RB_STATUS_PENDING_STOP;
5259 }
5260 return;
5261}
5262
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005263bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5264 std::lock_guard<std::mutex> lock(mLock);
5265 if (mRequestBufferOngoing) {
5266 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5267 __FUNCTION__);
5268 return false;
5269 }
5270 mSwitchedToOffline = true;
5271 mInflightMapEmpty = true;
5272 mRequestThreadPaused = true;
5273 mStatus = RB_STATUS_STOPPED;
5274 return true;
5275}
5276
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005277void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5278 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5279 if (statusTracker != nullptr) {
5280 if (active) {
5281 statusTracker->markComponentActive(mRequestBufferStatusId);
5282 } else {
5283 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5284 }
5285 }
5286}
5287
5288bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5289 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5290 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005291 return true;
5292 }
5293 return false;
5294}
5295
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005296bool Camera3Device::startRequestBuffer() {
5297 return mRequestBufferSM.startRequestBuffer();
5298}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005299
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005300void Camera3Device::endRequestBuffer() {
5301 mRequestBufferSM.endRequestBuffer();
5302}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005303
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005304nsecs_t Camera3Device::getWaitDuration() {
5305 return kBaseGetBufferWait + getExpectedInFlightDuration();
5306}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005307
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005308void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5309 mInterface->getInflightBufferKeys(out);
5310}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005311
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005312void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5313 mInterface->getInflightRequestBufferKeys(out);
5314}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005315
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005316std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5317 std::vector<sp<Camera3StreamInterface>> ret;
5318 bool hasInputStream = mInputStream != nullptr;
5319 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5320 if (hasInputStream) {
5321 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005322 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005323 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5324 ret.push_back(mOutputStreams[i]);
5325 }
5326 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5327 ret.push_back(mDeletedStreams[i]);
5328 }
5329 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005330}
5331
Emilian Peevcc0b7952020-01-07 13:54:47 -08005332void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5333 ATRACE_CALL();
5334
5335 if (offlineStreamIds == nullptr) {
5336 return;
5337 }
5338
5339 Mutex::Autolock il(mInterfaceLock);
5340
5341 auto streamIds = mOutputStreams.getStreamIds();
5342 bool hasInputStream = mInputStream != nullptr;
5343 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5344 offlineStreamIds->push_back(mInputStream->getId());
5345 }
5346
5347 for (const auto & streamId : streamIds) {
5348 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5349 // Streams that use the camera buffer manager are currently not supported in
5350 // offline mode
5351 if (stream->getOfflineProcessingSupport() &&
5352 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5353 offlineStreamIds->push_back(streamId);
5354 }
5355 }
5356}
5357
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005358status_t Camera3Device::setRotateAndCropAutoBehavior(
5359 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5360 ATRACE_CALL();
5361 Mutex::Autolock il(mInterfaceLock);
5362 Mutex::Autolock l(mLock);
5363 if (mRequestThread == nullptr) {
5364 return INVALID_OPERATION;
5365 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005366 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5367 return BAD_VALUE;
5368 }
5369 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005370 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5371}
5372
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005373status_t Camera3Device::setAutoframingAutoBehavior(
5374 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5375 ATRACE_CALL();
5376 Mutex::Autolock il(mInterfaceLock);
5377 Mutex::Autolock l(mLock);
5378 if (mRequestThread == nullptr) {
5379 return INVALID_OPERATION;
5380 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005381 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
5382 return BAD_VALUE;
5383 }
5384 mAutoframingOverride = autoframingValue;
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005385 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5386}
5387
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005388bool Camera3Device::supportsCameraMute() {
5389 Mutex::Autolock il(mInterfaceLock);
5390 Mutex::Autolock l(mLock);
5391
5392 return mSupportCameraMute;
5393}
5394
5395status_t Camera3Device::setCameraMute(bool enabled) {
5396 ATRACE_CALL();
5397 Mutex::Autolock il(mInterfaceLock);
5398 Mutex::Autolock l(mLock);
5399
5400 if (mRequestThread == nullptr || !mSupportCameraMute) {
5401 return INVALID_OPERATION;
5402 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005403 int32_t muteMode =
5404 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5405 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5406 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5407 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005408}
5409
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005410bool Camera3Device::supportsZoomOverride() {
5411 Mutex::Autolock il(mInterfaceLock);
5412 Mutex::Autolock l(mLock);
5413
5414 return mSupportZoomOverride;
5415}
5416
5417status_t Camera3Device::setZoomOverride(int32_t zoomOverride) {
5418 ATRACE_CALL();
5419 Mutex::Autolock il(mInterfaceLock);
5420 Mutex::Autolock l(mLock);
5421
5422 if (mRequestThread == nullptr || !mSupportZoomOverride) {
5423 return INVALID_OPERATION;
5424 }
5425
5426 return mRequestThread->setZoomOverride(zoomOverride);
5427}
5428
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005429status_t Camera3Device::injectCamera(const String8& injectedCamId,
5430 sp<CameraProviderManager> manager) {
5431 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5432 ATRACE_CALL();
5433 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005434 // When the camera device is active, injectCamera() and stopInjection() will call
5435 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5436 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5437 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5438 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5439 // waitUntilStateThenRelock().
5440 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005441
5442 status_t res = NO_ERROR;
5443 if (mInjectionMethods->isInjecting()) {
5444 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5445 return OK;
5446 } else {
5447 res = mInjectionMethods->stopInjection();
5448 if (res != OK) {
5449 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5450 __FUNCTION__, res);
5451 return res;
5452 }
5453 }
5454 }
5455
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005456 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005457 if (res != OK) {
5458 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5459 __FUNCTION__, res);
5460 return res;
5461 }
5462
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005463 // When the second display of android is cast to the remote device, and the opened camera is
5464 // also cast to the second display, in this case, because the camera has configured the streams
5465 // at this time, we can directly call injectCamera() to replace the internal camera with
5466 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005467 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5468 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5469
5470 camera3::camera_stream_configuration injectionConfig;
5471 std::vector<uint32_t> injectionBufferSizes;
5472 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5473 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5474 || injectionBufferSizes.size() <= 0) {
5475 ALOGE("Failed to inject camera due to abandoned configuration! "
5476 "mOperatingMode: %d injectionConfig.num_streams: %d "
5477 "injectionBufferSizes.size(): %zu", mOperatingMode,
5478 injectionConfig.num_streams, injectionBufferSizes.size());
5479 return DEAD_OBJECT;
5480 }
5481
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005482 res = mInjectionMethods->injectCamera(
5483 injectionConfig, injectionBufferSizes);
5484 if (res != OK) {
5485 ALOGE("Can't finish inject camera process!");
5486 return res;
5487 }
5488 }
5489
5490 return OK;
5491}
5492
5493status_t Camera3Device::stopInjection() {
5494 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5495 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005496 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005497 return mInjectionMethods->stopInjection();
5498}
5499
Shuzhen Wang16610a62022-12-15 22:38:07 -08005500void Camera3Device::overrideStreamUseCaseLocked() {
5501 if (mStreamUseCaseOverrides.size() == 0) {
5502 return;
5503 }
5504
5505 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5506 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5507 // Refer to CameraService::printHelp for details.
5508 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5509 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5510 outputStreamsIndices[i] = i;
5511 }
5512
5513 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5514 [&](int a, int b) -> bool {
5515
5516 auto formatScore = [](int format) {
5517 switch (format) {
5518 case HAL_PIXEL_FORMAT_BLOB:
5519 return 4;
5520 case HAL_PIXEL_FORMAT_RAW16:
5521 case HAL_PIXEL_FORMAT_RAW10:
5522 case HAL_PIXEL_FORMAT_RAW12:
5523 return 3;
5524 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5525 return 2;
5526 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5527 return 1;
5528 default:
5529 return 0;
5530 }
5531 };
5532
5533 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5534 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5535 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5536 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5537 if (sizeA > sizeB ||
5538 (sizeA == sizeB && formatAScore >= formatBScore)) {
5539 return true;
5540 } else {
5541 return false;
5542 }
5543 });
5544
5545 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5546 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5547 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5548 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5549 }
5550}
5551
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005552}; // namespace android