blob: 9de14a264449d8d81aa7c1e04f31580229be614f [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 {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000286 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
287 /*requestThreadInvocation*/ false);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 if (res != OK) {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000289 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
290 maxExpectedDuration);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800291 // Continue to close device even in case of error
292 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700293 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000295 // Signal to request thread that we're not expecting any
296 // more requests. This will be true since once we're in
297 // disconnect and we've cleared off the request queue, the
298 // request thread can't receive any new requests through
299 // binder calls - since disconnect holds
300 // mBinderSerialization lock.
301 mRequestThread->setRequestClearing();
302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000304 if (mStatus == STATUS_ERROR) {
305 CLOGE("Shutting down in an error state");
306 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000308 if (mStatusTracker != NULL) {
309 mStatusTracker->requestExit();
310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000312 if (mRequestThread != NULL) {
313 mRequestThread->requestExit();
314 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000316 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
317 for (size_t i = 0; i < mOutputStreams.size(); i++) {
318 streams.push_back(mOutputStreams[i]);
319 }
320 if (mInputStream != nullptr) {
321 streams.push_back(mInputStream);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700322 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700323 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000324
325 // Joining done without holding mLock, otherwise deadlocks may ensue
326 // as the threads try to access parent state
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700327 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
328 // HAL may be in a bad state, so waiting for request thread
329 // (which may be stuck in the HAL processCaptureRequest call)
330 // could be dangerous.
331 mRequestThread->join();
332 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000333
334 if (mStatusTracker != NULL) {
335 mStatusTracker->join();
336 }
337
338 if (mInjectionMethods->isInjecting()) {
339 mInjectionMethods->stopInjection();
340 }
341
342 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000344 Mutex::Autolock l(mLock);
345 mRequestThread.clear();
346 Mutex::Autolock stLock(mTrackerLock);
347 mStatusTracker.clear();
348 interface = mInterface.get();
349 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800350
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000351 // Call close without internal mutex held, as the HAL close may need to
352 // wait on assorted callbacks,etc, to complete before it can return.
353 mCameraServiceWatchdog->WATCH(interface->close());
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800354
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000355 flushInflightRequests();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700356
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000357 {
358 Mutex::Autolock l(mLock);
359 mInterface->clear();
360 mOutputStreams.clear();
361 mInputStream.clear();
362 mDeletedStreams.clear();
363 mBufferManager.clear();
364 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
365 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700366
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000367 for (auto& weakStream : streams) {
368 sp<Camera3StreamInterface> stream = weakStream.promote();
369 if (stream != nullptr) {
370 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
371 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700372 }
373 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700374 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000375
376 if (mCameraServiceWatchdog != NULL) {
377 mCameraServiceWatchdog->requestExit();
378 mCameraServiceWatchdog.clear();
379 }
380
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700381 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800382}
383
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384// For dumping/debugging only -
385// try to acquire a lock a few times, eventually give up to proceed with
386// debug/dump operations
387bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
388 bool gotLock = false;
389 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
390 if (lock.tryLock() == NO_ERROR) {
391 gotLock = true;
392 break;
393 } else {
394 usleep(kDumpSleepDuration);
395 }
396 }
397 return gotLock;
398}
399
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800400nsecs_t Camera3Device::getMonoToBoottimeOffset() {
401 // try three times to get the clock offset, choose the one
402 // with the minimum gap in measurements.
403 const int tries = 3;
404 nsecs_t bestGap, measured;
405 for (int i = 0; i < tries; ++i) {
406 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
407 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
408 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
409 const nsecs_t gap = tmono2 - tmono;
410 if (i == 0 || gap < bestGap) {
411 bestGap = gap;
412 measured = tbase - ((tmono + tmono2) >> 1);
413 }
414 }
415 return measured;
416}
417
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800418ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
419 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700420 // Get max jpeg size (area-wise) for default sensor pixel mode
421 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800422 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800423 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700424 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
425 // not ultra high res sensor
426 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800427 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700428 /*isUltraHighResolution*/true);
429 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800430 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
431 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700432 return BAD_VALUE;
433 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700434 bool useMaxSensorPixelModeThreshold = false;
435 if (uhrMaxJpegResolution.width != 0 &&
436 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
437 // Use the ultra high res max jpeg size and max jpeg buffer size
438 useMaxSensorPixelModeThreshold = true;
439 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700440
Zhijun Hef7da0962014-04-24 13:27:56 -0700441 // Get max jpeg buffer size
442 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800443 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700444 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800445 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
446 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700447 return BAD_VALUE;
448 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700449 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700450
451 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
452 if (useMaxSensorPixelModeThreshold) {
453 maxJpegBufferSize =
454 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
455 maxDefaultJpegResolution, maxJpegBufferSize);
456 chosenMaxJpegResolution = uhrMaxJpegResolution;
457 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800458 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700459
460 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700461 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700462 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800463 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
464 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700465 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800466 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
467 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700468 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700469 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700470 return jpegBufferSize;
471}
472
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800473ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700474 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800475 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700476 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800477 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
478 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700479 return BAD_VALUE;
480 }
481 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
482 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
483 return maxBytesForPointCloud;
484}
485
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800486ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
487 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800488 const int PER_CONFIGURATION_SIZE = 3;
489 const int WIDTH_OFFSET = 0;
490 const int HEIGHT_OFFSET = 1;
491 const int SIZE_OFFSET = 2;
492 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800493 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800494 camera3::SessionConfigurationUtils::getAppropriateModeTag(
495 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
496 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800497 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800498 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800499 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
500 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800501 return BAD_VALUE;
502 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700503
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800504 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
505 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
506 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
507 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
508 }
509 }
510
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
512 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800513 return BAD_VALUE;
514}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700515
Jing Mikec7f9b132023-03-12 11:12:04 +0800516status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800517 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700518
519 // Try to lock, but continue in case of failure (to avoid blocking in
520 // deadlocks)
521 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
522 bool gotLock = tryLockSpinRightRound(mLock);
523
524 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800525 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
526 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700527 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800528 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
529 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700530
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800531 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700532
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800533 String16 templatesOption("-t");
534 int n = args.size();
535 for (int i = 0; i < n; i++) {
536 if (args[i] == templatesOption) {
537 dumpTemplates = true;
538 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000539 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700540 if (i + 1 < n) {
541 String8 monitorTags = String8(args[i + 1]);
542 if (monitorTags == "off") {
543 mTagMonitor.disableMonitoring();
544 } else {
545 mTagMonitor.parseTagsToMonitor(monitorTags);
546 }
547 } else {
548 mTagMonitor.disableMonitoring();
549 }
550 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800551 }
552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800553 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800554
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800555 const char *status =
556 mStatus == STATUS_ERROR ? "ERROR" :
557 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700558 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
559 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800560 mStatus == STATUS_ACTIVE ? "ACTIVE" :
561 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700562
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800563 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700564 if (mStatus == STATUS_ERROR) {
565 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
566 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800567 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800568 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000569 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
570 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
571 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800572 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800573
574 if (mInputStream != NULL) {
575 write(fd, lines.string(), lines.size());
576 mInputStream->dump(fd, args);
577 } else {
578 lines.appendFormat(" No input stream.\n");
579 write(fd, lines.string(), lines.size());
580 }
581 for (size_t i = 0; i < mOutputStreams.size(); i++) {
582 mOutputStreams[i]->dump(fd,args);
583 }
584
Zhijun He431503c2016-03-07 17:30:16 -0800585 if (mBufferManager != NULL) {
586 lines = String8(" Camera3 Buffer Manager:\n");
587 write(fd, lines.string(), lines.size());
588 mBufferManager->dump(fd, args);
589 }
Zhijun He125684a2015-12-26 15:07:30 -0800590
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700591 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700592 if (mInFlightLock.try_lock()) {
593 if (mInFlightMap.size() == 0) {
594 lines.append(" None\n");
595 } else {
596 for (size_t i = 0; i < mInFlightMap.size(); i++) {
597 InFlightRequest r = mInFlightMap.valueAt(i);
598 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
599 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
600 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
601 r.numBuffersLeft);
602 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700603 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700604 mInFlightLock.unlock();
605 } else {
606 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700607 }
608 write(fd, lines.string(), lines.size());
609
Shuzhen Wang686f6442017-06-20 16:16:04 -0700610 if (mRequestThread != NULL) {
611 mRequestThread->dumpCaptureRequestLatency(fd,
612 " ProcessCaptureRequest latency histogram:");
613 }
614
Igor Murashkin1e479c02013-09-06 16:55:14 -0700615 {
616 lines = String8(" Last request sent:\n");
617 write(fd, lines.string(), lines.size());
618
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700619 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700620 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
621 }
622
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800623 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700624 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800625 "TEMPLATE_PREVIEW",
626 "TEMPLATE_STILL_CAPTURE",
627 "TEMPLATE_VIDEO_RECORD",
628 "TEMPLATE_VIDEO_SNAPSHOT",
629 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800630 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800631 };
632
Emilian Peevf4816702020-04-03 15:44:51 -0700633 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800634 camera_metadata_t *templateRequest = nullptr;
635 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700636 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800637 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800639 lines.append(" Not supported\n");
640 write(fd, lines.string(), lines.size());
641 } else {
642 write(fd, lines.string(), lines.size());
643 dump_indented_camera_metadata(templateRequest,
644 fd, /*verbosity*/2, /*indentation*/8);
645 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800646 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800647 }
648 }
649
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700650 mTagMonitor.dumpMonitoredMetadata(fd);
651
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800652 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800653 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800655 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800656 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800657
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700658 if (gotLock) mLock.unlock();
659 if (gotInterfaceLock) mInterfaceLock.unlock();
660
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800661 return OK;
662}
663
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700664status_t Camera3Device::startWatchingTags(const String8 &tags) {
665 mTagMonitor.parseTagsToMonitor(tags);
666 return OK;
667}
668
669status_t Camera3Device::stopWatchingTags() {
670 mTagMonitor.disableMonitoring();
671 return OK;
672}
673
674status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
675 mTagMonitor.getLatestMonitoredTagEvents(out);
676 return OK;
677}
678
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800679const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800680 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800681 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
682 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700683 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800684 mStatus == STATUS_ERROR ?
685 "when in error state" : "before init");
686 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700687 if (physicalId.isEmpty()) {
688 return mDeviceInfo;
689 } else {
690 std::string id(physicalId.c_str());
691 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
692 return mPhysicalDeviceInfoMap.at(id);
693 } else {
694 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
695 return mDeviceInfo;
696 }
697 }
698}
699
700const CameraMetadata& Camera3Device::info() const {
701 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800702 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800703}
704
Jianing Wei90e59c92014-03-12 18:29:36 -0700705status_t Camera3Device::checkStatusOkToCaptureLocked() {
706 switch (mStatus) {
707 case STATUS_ERROR:
708 CLOGE("Device has encountered a serious error");
709 return INVALID_OPERATION;
710 case STATUS_UNINITIALIZED:
711 CLOGE("Device not initialized");
712 return INVALID_OPERATION;
713 case STATUS_UNCONFIGURED:
714 case STATUS_CONFIGURED:
715 case STATUS_ACTIVE:
716 // OK
717 break;
718 default:
719 SET_ERR_L("Unexpected status: %d", mStatus);
720 return INVALID_OPERATION;
721 }
722 return OK;
723}
724
725status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000726 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700727 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700728 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700729 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700730 if (requestList == NULL) {
731 CLOGE("requestList cannot be NULL.");
732 return BAD_VALUE;
733 }
734
Jianing Weicb0652e2014-03-12 18:29:36 -0700735 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000736 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700737 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
738 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
739 ++metadataIt, ++surfaceMapIt) {
740 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700741 if (newRequest == 0) {
742 CLOGE("Can't create capture request");
743 return BAD_VALUE;
744 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700745
Shuzhen Wang9d066012016-09-30 11:30:20 -0700746 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700747 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700748
Jianing Weicb0652e2014-03-12 18:29:36 -0700749 // Setup burst Id and request Id
750 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800751 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
752 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700753 CLOGE("RequestID does not exist in metadata");
754 return BAD_VALUE;
755 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800756 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700757
Jianing Wei90e59c92014-03-12 18:29:36 -0700758 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700759
760 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700761 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700762 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
763 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
764 return BAD_VALUE;
765 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700766
767 // Setup batch size if this is a high speed video recording request.
768 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
769 auto firstRequest = requestList->begin();
770 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
771 if (outputStream->isVideoStream()) {
772 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800773 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700774 break;
775 }
776 }
777 }
778
Jianing Wei90e59c92014-03-12 18:29:36 -0700779 return OK;
780}
781
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800782status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800784
Emilian Peevaebbe412018-01-15 13:53:24 +0000785 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700786 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000787 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700788
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800789 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700790}
791
Emilian Peevaebbe412018-01-15 13:53:24 +0000792void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700793 std::list<const SurfaceMap>& surfaceMaps,
794 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000795 PhysicalCameraSettingsList requestList;
796 requestList.push_back({std::string(getId().string()), request});
797 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798
799 SurfaceMap surfaceMap;
800 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
801 // With no surface list passed in, stream and surface will have 1-to-1
802 // mapping. So the surface index is 0 for each stream in the surfaceMap.
803 for (size_t i = 0; i < streams.count; i++) {
804 surfaceMap[streams.data.i32[i]].push_back(0);
805 }
806 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800807}
808
Jianing Wei90e59c92014-03-12 18:29:36 -0700809status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000810 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700811 const std::list<const SurfaceMap> &surfaceMaps,
812 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700813 /*out*/
814 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700815 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700816 nsecs_t requestTimeNs = systemTime();
817
Jianing Wei90e59c92014-03-12 18:29:36 -0700818 Mutex::Autolock il(mInterfaceLock);
819 Mutex::Autolock l(mLock);
820
821 status_t res = checkStatusOkToCaptureLocked();
822 if (res != OK) {
823 // error logged by previous call
824 return res;
825 }
826
827 RequestList requestList;
828
Shuzhen Wang0129d522016-10-30 22:43:41 -0700829 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700830 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 if (res != OK) {
832 // error logged by previous call
833 return res;
834 }
835
836 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700837 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700838 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700839 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700840 }
841
842 if (res == OK) {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000843 waitUntilStateThenRelock(/*active*/true, kActiveTimeout, /*requestThreadInvocation*/false);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 if (res != OK) {
845 SET_ERR_L("Can't transition to active in %f seconds!",
846 kActiveTimeout/1e9);
847 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800848 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700849 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850 } else {
851 CLOGE("Cannot queue request. Impossible.");
852 return BAD_VALUE;
853 }
854
855 return res;
856}
857
Emilian Peevaebbe412018-01-15 13:53:24 +0000858status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700860 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700861 ATRACE_CALL();
862
Emilian Peevaebbe412018-01-15 13:53:24 +0000863 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700864}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800865
Jianing Weicb0652e2014-03-12 18:29:36 -0700866status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
867 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800868 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800869
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700871 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000872 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700873
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700875 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876}
877
Emilian Peevaebbe412018-01-15 13:53:24 +0000878status_t Camera3Device::setStreamingRequestList(
879 const List<const PhysicalCameraSettingsList> &requestsList,
880 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700881 ATRACE_CALL();
882
Emilian Peevaebbe412018-01-15 13:53:24 +0000883 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885
886sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000887 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800888 status_t res;
889
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700890 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800891 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
892 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700894 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700895 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800896 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700897 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800898 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700899 } else if (mStatus == STATUS_UNCONFIGURED) {
900 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700901 CLOGE("No streams configured");
902 return NULL;
903 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800904 }
905
Shuzhen Wang0129d522016-10-30 22:43:41 -0700906 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800907 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800908}
909
Jianing Weicb0652e2014-03-12 18:29:36 -0700910status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800911 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700912 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800913 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800915 switch (mStatus) {
916 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700917 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800918 return INVALID_OPERATION;
919 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700920 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800921 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700922 case STATUS_UNCONFIGURED:
923 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800924 case STATUS_ACTIVE:
925 // OK
926 break;
927 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700928 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800929 return INVALID_OPERATION;
930 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800931 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700932
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700933 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800934}
935
936status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
937 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700938 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800939
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700940 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800941}
942
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700943status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800944 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700945 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700946 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700947 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700948 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800949 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
950 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700951
952 status_t res;
953 bool wasActive = false;
954
955 switch (mStatus) {
956 case STATUS_ERROR:
957 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
958 return INVALID_OPERATION;
959 case STATUS_UNINITIALIZED:
960 ALOGE("%s: Device not initialized", __FUNCTION__);
961 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700962 case STATUS_UNCONFIGURED:
963 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700964 // OK
965 break;
966 case STATUS_ACTIVE:
967 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000968 res = internalPauseAndWaitLocked(maxExpectedDuration,
969 /*requestThreadInvocation*/ false);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700970 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700971 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700972 return res;
973 }
974 wasActive = true;
975 break;
976 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700977 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700978 return INVALID_OPERATION;
979 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700980 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700981
982 if (mInputStream != 0) {
983 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
984 return INVALID_OPERATION;
985 }
986
987 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
988 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700989 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700990
991 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800992 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700993
994 *id = mNextStreamId++;
995
996 // Continue captures if active at start
997 if (wasActive) {
998 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100999 // Reuse current operating mode and session parameters for new stream config
1000 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001001 if (res != OK) {
1002 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1003 __FUNCTION__, mNextStreamId, strerror(-res), res);
1004 return res;
1005 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001006 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001007 }
1008
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001009 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001010 return OK;
1011}
1012
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001013status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001014 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001015 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001016 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001017 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1018 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001019 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001020 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001021 ATRACE_CALL();
1022
1023 if (consumer == nullptr) {
1024 ALOGE("%s: consumer must not be null", __FUNCTION__);
1025 return BAD_VALUE;
1026 }
1027
1028 std::vector<sp<Surface>> consumers;
1029 consumers.push_back(consumer);
1030
1031 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001032 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001033 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001034 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001035}
1036
1037static bool isRawFormat(int format) {
1038 switch (format) {
1039 case HAL_PIXEL_FORMAT_RAW16:
1040 case HAL_PIXEL_FORMAT_RAW12:
1041 case HAL_PIXEL_FORMAT_RAW10:
1042 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1043 return true;
1044 default:
1045 return false;
1046 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001047}
1048
1049status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1050 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001051 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001052 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001053 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001054 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001055 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001056 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001057
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001058 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001059 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001061 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001062 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001063 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001064 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001065 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001066 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001067 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1068 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001069
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001070 status_t res;
1071 bool wasActive = false;
1072
1073 switch (mStatus) {
1074 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001075 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001076 return INVALID_OPERATION;
1077 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001078 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001080 case STATUS_UNCONFIGURED:
1081 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001082 // OK
1083 break;
1084 case STATUS_ACTIVE:
1085 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001086 res = internalPauseAndWaitLocked(maxExpectedDuration,
1087 /*requestThreadInvocation*/ false);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001089 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001090 return res;
1091 }
1092 wasActive = true;
1093 break;
1094 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001095 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001096 return INVALID_OPERATION;
1097 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001098 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001099
1100 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001101
Shuzhen Wang0129d522016-10-30 22:43:41 -07001102 if (consumers.size() == 0 && !hasDeferredConsumer) {
1103 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1104 return BAD_VALUE;
1105 }
Zhijun He5d677d12016-05-29 16:52:39 -07001106
Shuzhen Wang0129d522016-10-30 22:43:41 -07001107 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001108 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1109 return BAD_VALUE;
1110 }
1111
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001112 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1113 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1114 // be found in only one sensor pixel mode.
1115 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1116 return BAD_VALUE;
1117 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001118 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001119 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001120 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001121 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001122 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001123 if (blobBufferSize <= 0) {
1124 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1125 return BAD_VALUE;
1126 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001127 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1128 blobBufferSize = width * height;
1129 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001130 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001131 if (blobBufferSize <= 0) {
1132 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1133 return BAD_VALUE;
1134 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001135 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001136 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001137 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001138 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001139 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001140 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001141 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001142 bool maxResolution =
1143 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1144 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001145 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1146 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001147 if (rawOpaqueBufferSize <= 0) {
1148 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1149 return BAD_VALUE;
1150 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001151 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001152 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001153 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001154 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001155 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001156 } else if (isShared) {
1157 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1158 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001159 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001160 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001161 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001162 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001163 newStream = new Camera3OutputStream(mNextStreamId,
1164 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001165 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001166 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001167 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001168 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001169 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001170 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001171 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001172 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001173 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174 }
Emilian Peev40ead602017-09-26 15:46:36 +01001175
1176 size_t consumerCount = consumers.size();
1177 for (size_t i = 0; i < consumerCount; i++) {
1178 int id = newStream->getSurfaceId(consumers[i]);
1179 if (id < 0) {
1180 SET_ERR_L("Invalid surface id");
1181 return BAD_VALUE;
1182 }
1183 if (surfaceIds != nullptr) {
1184 surfaceIds->push_back(id);
1185 }
1186 }
1187
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001188 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189
Emilian Peev08dd2452017-04-06 16:55:14 +01001190 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001191
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001192 newStream->setImageDumpMask(mImageDumpMask);
1193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 res = mOutputStreams.add(mNextStreamId, newStream);
1195 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001196 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return res;
1198 }
1199
Shuzhen Wang316781a2020-08-18 18:11:01 -07001200 mSessionStatsBuilder.addStream(mNextStreamId);
1201
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001203 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204
1205 // Continue captures if active at start
1206 if (wasActive) {
1207 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001208 // Reuse current operating mode and session parameters for new stream config
1209 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001211 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1212 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 return res;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001217 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219}
1220
Emilian Peev710c1422017-08-30 11:19:38 +01001221status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001222 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001223 if (nullptr == streamInfo) {
1224 return BAD_VALUE;
1225 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 switch (mStatus) {
1230 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
1233 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001234 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 case STATUS_UNCONFIGURED:
1237 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 case STATUS_ACTIVE:
1239 // OK
1240 break;
1241 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001242 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return INVALID_OPERATION;
1244 }
1245
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001246 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1247 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001248 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001249 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 }
1251
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001252 streamInfo->width = stream->getWidth();
1253 streamInfo->height = stream->getHeight();
1254 streamInfo->format = stream->getFormat();
1255 streamInfo->dataSpace = stream->getDataSpace();
1256 streamInfo->formatOverridden = stream->isFormatOverridden();
1257 streamInfo->originalFormat = stream->getOriginalFormat();
1258 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1259 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001260 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001261 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001263}
1264
1265status_t Camera3Device::setStreamTransform(int id,
1266 int transform) {
1267 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001268 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001270
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 switch (mStatus) {
1272 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001273 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return INVALID_OPERATION;
1275 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001276 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001278 case STATUS_UNCONFIGURED:
1279 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 case STATUS_ACTIVE:
1281 // OK
1282 break;
1283 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001284 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 return INVALID_OPERATION;
1286 }
1287
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001288 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1289 if (stream == nullptr) {
1290 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291 return BAD_VALUE;
1292 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001293 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001294}
1295
1296status_t Camera3Device::deleteStream(int id) {
1297 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001298 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 Mutex::Autolock l(mLock);
1300 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001301
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001302 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304 // CameraDevice semantics require device to already be idle before
1305 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001307 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001308 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 }
1310
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001311 if (mStatus == STATUS_ERROR) {
1312 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1313 __FUNCTION__, mId.string());
1314 return -EBUSY;
1315 }
1316
Igor Murashkin2fba5842013-04-22 14:03:54 -07001317 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001318 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001319 if (mInputStream != NULL && id == mInputStream->getId()) {
1320 deletedStream = mInputStream;
1321 mInputStream.clear();
1322 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001323 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001324 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001325 return BAD_VALUE;
1326 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001327 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001328 }
1329
1330 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001331 if (stream != nullptr) {
1332 deletedStream = stream;
1333 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001334 }
1335
1336 // Free up the stream endpoint so that it can be used by some other stream
1337 res = deletedStream->disconnect();
1338 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001339 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001340 // fall through since we want to still list the stream as deleted.
1341 }
1342 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001343 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001344
1345 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346}
1347
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001348status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001349 ATRACE_CALL();
1350 ALOGV("%s: E", __FUNCTION__);
1351
1352 Mutex::Autolock il(mInterfaceLock);
1353 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001354
Emilian Peev811d2952018-05-25 11:08:40 +01001355 // In case the client doesn't include any session parameter, try a
1356 // speculative configuration using the values from the last cached
1357 // default request.
1358 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001359 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001360 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1361 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1362 mLastTemplateId);
1363 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1364 operatingMode);
1365 }
1366
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001367 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1368}
1369
1370status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1371 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001372 //Filter out any incoming session parameters
1373 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001374 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1375 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001376 CameraMetadata filteredParams(availableSessionKeys.count);
1377 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1378 filteredParams.getAndLock());
1379 set_camera_metadata_vendor_id(meta, mVendorTagId);
1380 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001381 if (availableSessionKeys.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001382 bool rotateAndCropSessionKey = false;
1383 bool autoframingSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001384 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1385 camera_metadata_ro_entry entry = params.find(
1386 availableSessionKeys.data.i32[i]);
1387 if (entry.count > 0) {
1388 filteredParams.update(entry);
1389 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07001390 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1391 rotateAndCropSessionKey = true;
1392 }
1393 if (ANDROID_CONTROL_AUTOFRAMING == availableSessionKeys.data.i32[i]) {
1394 autoframingSessionKey = true;
1395 }
1396 }
1397
1398 if (rotateAndCropSessionKey || autoframingSessionKey) {
1399 sp<CaptureRequest> request = new CaptureRequest();
1400 PhysicalCameraSettings settingsList;
1401 settingsList.metadata = filteredParams;
1402 request->mSettingsList.push_back(settingsList);
1403
1404 if (rotateAndCropSessionKey) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001405 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1406 if (rotateAndCropEntry.count > 0 &&
1407 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1408 request->mRotateAndCropAuto = true;
1409 } else {
1410 request->mRotateAndCropAuto = false;
1411 }
1412
1413 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1414 }
1415
1416 if (autoframingSessionKey) {
1417 auto autoframingEntry = filteredParams.find(ANDROID_CONTROL_AUTOFRAMING);
1418 if (autoframingEntry.count > 0 &&
1419 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
1420 overrideAutoframing(request, mAutoframingOverride);
1421 }
1422 }
1423
1424 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001425 }
1426 }
1427
1428 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001429}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001430
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001431status_t Camera3Device::getInputBufferProducer(
1432 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001433 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001434 Mutex::Autolock il(mInterfaceLock);
1435 Mutex::Autolock l(mLock);
1436
1437 if (producer == NULL) {
1438 return BAD_VALUE;
1439 } else if (mInputStream == NULL) {
1440 return INVALID_OPERATION;
1441 }
1442
1443 return mInputStream->getInputBufferProducer(producer);
1444}
1445
Emilian Peevf4816702020-04-03 15:44:51 -07001446status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001447 CameraMetadata *request) {
1448 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001449 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001450
Emilian Peevf4816702020-04-03 15:44:51 -07001451 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001452 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001453 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001454 return BAD_VALUE;
1455 }
1456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001457 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001459 {
1460 Mutex::Autolock l(mLock);
1461 switch (mStatus) {
1462 case STATUS_ERROR:
1463 CLOGE("Device has encountered a serious error");
1464 return INVALID_OPERATION;
1465 case STATUS_UNINITIALIZED:
1466 CLOGE("Device is not initialized!");
1467 return INVALID_OPERATION;
1468 case STATUS_UNCONFIGURED:
1469 case STATUS_CONFIGURED:
1470 case STATUS_ACTIVE:
1471 // OK
1472 break;
1473 default:
1474 SET_ERR_L("Unexpected status: %d", mStatus);
1475 return INVALID_OPERATION;
1476 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001478 if (!mRequestTemplateCache[templateId].isEmpty()) {
1479 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001480 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001481 return OK;
1482 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001483 }
1484
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001485 camera_metadata_t *rawRequest;
1486 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001487 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001488
1489 {
1490 Mutex::Autolock l(mLock);
1491 if (res == BAD_VALUE) {
1492 ALOGI("%s: template %d is not supported on this camera device",
1493 __FUNCTION__, templateId);
1494 return res;
1495 } else if (res != OK) {
1496 CLOGE("Unable to construct request template %d: %s (%d)",
1497 templateId, strerror(-res), res);
1498 return res;
1499 }
1500
1501 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1502 mRequestTemplateCache[templateId].acquire(rawRequest);
1503
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001504 // Override the template request with zoomRatioMapper
1505 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1506 &mRequestTemplateCache[templateId]);
1507 if (res != OK) {
1508 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1509 templateId, strerror(-res), res);
1510 return res;
1511 }
1512
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001513 // Fill in JPEG_QUALITY if not available
1514 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1515 static const uint8_t kDefaultJpegQuality = 95;
1516 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1517 &kDefaultJpegQuality, 1);
1518 }
1519
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001520 // Fill in AUTOFRAMING if not available
1521 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1522 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1523 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1524 &kDefaultAutoframingMode, 1);
1525 }
1526
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001527 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001528 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001530 return OK;
1531}
1532
1533status_t Camera3Device::waitUntilDrained() {
1534 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001536 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001538
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001539 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001540}
1541
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001542status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 switch (mStatus) {
1544 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001545 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 ALOGV("%s: Already idle", __FUNCTION__);
1547 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001548 case STATUS_CONFIGURED:
1549 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 case STATUS_ERROR:
1551 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 break;
1554 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001558 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1559 maxExpectedDuration);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001560 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1561 /*requestThreadInvocation*/ false);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001562 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001563 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001564 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1565 res);
1566 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 return res;
1568}
1569
Ruben Brunk183f0562015-08-12 12:55:02 -07001570void Camera3Device::internalUpdateStatusLocked(Status status) {
1571 mStatus = status;
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001572 mStatusIsInternal = mPauseStateNotify ? true : false;
1573 mRecentStatusUpdates.add({mStatus, mStatusIsInternal});
Ruben Brunk183f0562015-08-12 12:55:02 -07001574 mStatusChanged.broadcast();
1575}
1576
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001577// Pause to reconfigure
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001578status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration,
1579 bool requestThreadInvocation) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001580 if (mRequestThread.get() != nullptr) {
1581 mRequestThread->setPaused(true);
1582 } else {
1583 return NO_INIT;
1584 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001586 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1587 maxExpectedDuration);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001588 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1589 requestThreadInvocation);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001591 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001593 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 }
1595
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001596 return res;
1597}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001599// Resume after internalPauseAndWaitLocked
1600status_t Camera3Device::internalResumeLocked() {
1601 status_t res;
1602
1603 mRequestThread->setPaused(false);
1604
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001605 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1606 kActiveTimeout);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001607 // internalResumeLocked is always called from a binder thread.
1608 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout,
1609 /*requestThreadInvocation*/ false);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001610 if (res != OK) {
1611 SET_ERR_L("Can't transition to active in %f seconds!",
1612 kActiveTimeout/1e9);
1613 }
1614 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001615 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616}
1617
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001618status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout,
1619 bool requestThreadInvocation) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001621
1622 size_t startIndex = 0;
1623 if (mStatusWaiters == 0) {
1624 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1625 // this status list
1626 mRecentStatusUpdates.clear();
1627 } else {
1628 // If other threads are waiting on updates to this status list, set the position of the
1629 // first element that this list will check rather than clearing the list.
1630 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 }
1632
Ruben Brunk183f0562015-08-12 12:55:02 -07001633 mStatusWaiters++;
1634
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001635 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001636 if (!active && mUseHalBufManager) {
1637 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001638 if (mStatus == STATUS_ACTIVE) {
1639 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001640 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001641 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001642 mRequestBufferSM.onWaitUntilIdle();
1643 }
1644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001646 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001647 do {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001648 if (active == (mStatus == STATUS_ACTIVE) &&
1649 (requestThreadInvocation || !mStatusIsInternal)) {
Ruben Brunk183f0562015-08-12 12:55:02 -07001650 // Desired state is current
1651 break;
1652 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001653
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001654 nsecs_t timeElapsed = systemTime() - startTime;
1655 nsecs_t timeToWait = timeout - timeElapsed;
1656 if (timeToWait <= 0) {
1657 // Thread woke up spuriously but has timed out since.
1658 // Force out of loop with TIMED_OUT result.
1659 res = TIMED_OUT;
1660 break;
1661 }
1662 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663 if (res != OK) break;
1664
Ruben Brunk183f0562015-08-12 12:55:02 -07001665 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1666 // transitions.
1667 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1668 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1669 __FUNCTION__);
1670
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001671 // Encountered desired state since we began waiting. Internal invocations coming from
1672 // request threads (such as reconfigureCamera) should be woken up immediately, whereas
1673 // invocations from binder threads (such as createInputStream) should only be woken up if
1674 // they are not paused. This avoids intermediate pause signals from reconfigureCamera as it
1675 // changes the status to active right after.
Ruben Brunk183f0562015-08-12 12:55:02 -07001676 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001677 if (active == (mRecentStatusUpdates[i].status == STATUS_ACTIVE) &&
1678 (requestThreadInvocation || !mRecentStatusUpdates[i].isInternal)) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001679 stateSeen = true;
1680 break;
1681 }
1682 }
1683 } while (!stateSeen);
1684
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001685 if (signalPipelineDrain) {
1686 mRequestThread->resetPipelineDrain();
1687 }
1688
Ruben Brunk183f0562015-08-12 12:55:02 -07001689 mStatusWaiters--;
1690
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 return res;
1692}
1693
1694
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001695status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001697 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001699 if (listener != NULL && mListener != NULL) {
1700 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1701 }
1702 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001703 mRequestThread->setNotificationListener(listener);
1704 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001705
1706 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707}
1708
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001709bool Camera3Device::willNotify3A() {
1710 return false;
1711}
1712
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001713status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001714 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001715 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001717 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001718 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1719 if (st == std::cv_status::timeout) {
1720 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001721 }
1722 }
1723 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724}
1725
Jianing Weicb0652e2014-03-12 18:29:36 -07001726status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001728 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001730 if (mResultQueue.empty()) {
1731 return NOT_ENOUGH_DATA;
1732 }
1733
Jianing Weicb0652e2014-03-12 18:29:36 -07001734 if (frame == NULL) {
1735 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1736 return BAD_VALUE;
1737 }
1738
1739 CaptureResult &result = *(mResultQueue.begin());
1740 frame->mResultExtras = result.mResultExtras;
1741 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001742 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001743 mResultQueue.erase(mResultQueue.begin());
1744
1745 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746}
1747
1748status_t Camera3Device::triggerAutofocus(uint32_t id) {
1749 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001752 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1753 // Mix-in this trigger into the next request and only the next request.
1754 RequestTrigger trigger[] = {
1755 {
1756 ANDROID_CONTROL_AF_TRIGGER,
1757 ANDROID_CONTROL_AF_TRIGGER_START
1758 },
1759 {
1760 ANDROID_CONTROL_AF_TRIGGER_ID,
1761 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001762 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001763 };
1764
1765 return mRequestThread->queueTrigger(trigger,
1766 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001767}
1768
1769status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1770 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001772
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001773 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1774 // Mix-in this trigger into the next request and only the next request.
1775 RequestTrigger trigger[] = {
1776 {
1777 ANDROID_CONTROL_AF_TRIGGER,
1778 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1779 },
1780 {
1781 ANDROID_CONTROL_AF_TRIGGER_ID,
1782 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001783 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001784 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001786 return mRequestThread->queueTrigger(trigger,
1787 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001788}
1789
1790status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1791 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001792 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001793
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001794 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1795 // Mix-in this trigger into the next request and only the next request.
1796 RequestTrigger trigger[] = {
1797 {
1798 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1799 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1800 },
1801 {
1802 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1803 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001804 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001805 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001807 return mRequestThread->queueTrigger(trigger,
1808 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001809}
1810
Jianing Weicb0652e2014-03-12 18:29:36 -07001811status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001812 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001813 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001815
Zhijun He7ef20392014-04-21 16:04:17 -07001816 {
1817 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001818
1819 // b/116514106 "disconnect()" can get called twice for the same device. The
1820 // camera device will not be initialized during the second run.
1821 if (mStatus == STATUS_UNINITIALIZED) {
1822 return OK;
1823 }
1824
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001825 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001826
1827 // Stop session and stream counter
1828 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001829 }
1830
Ravneetdbd5b242022-03-02 07:22:46 +00001831 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001832 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001833 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1834 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1835
1836 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001837}
1838
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001839status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001840 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1841}
1842
1843status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001844 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001845 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001846 Mutex::Autolock il(mInterfaceLock);
1847 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001848
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001849 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1850 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001851 CLOGE("Stream %d does not exist", streamId);
1852 return BAD_VALUE;
1853 }
1854
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001855 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001856 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001857 return BAD_VALUE;
1858 }
1859
1860 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001861 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001862 return BAD_VALUE;
1863 }
1864
Ruben Brunkc78ac262015-08-13 17:58:46 -07001865 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001866}
1867
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001868status_t Camera3Device::tearDown(int streamId) {
1869 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001870 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001871 Mutex::Autolock il(mInterfaceLock);
1872 Mutex::Autolock l(mLock);
1873
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001874 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1875 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001876 CLOGE("Stream %d does not exist", streamId);
1877 return BAD_VALUE;
1878 }
1879
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001880 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1881 CLOGE("Stream %d is a target of a in-progress request", streamId);
1882 return BAD_VALUE;
1883 }
1884
1885 return stream->tearDown();
1886}
1887
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001888status_t Camera3Device::addBufferListenerForStream(int streamId,
1889 wp<Camera3StreamBufferListener> listener) {
1890 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001891 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001892 Mutex::Autolock il(mInterfaceLock);
1893 Mutex::Autolock l(mLock);
1894
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001895 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1896 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001897 CLOGE("Stream %d does not exist", streamId);
1898 return BAD_VALUE;
1899 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001900 stream->addBufferListener(listener);
1901
1902 return OK;
1903}
1904
Austin Borger4a870a32022-02-25 01:48:41 +00001905float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1906 camera_metadata_entry minDurations =
1907 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1908 for (size_t i = 0; i < minDurations.count; i += 4) {
1909 if (minDurations.data.i64[i] == stream->getFormat()
1910 && minDurations.data.i64[i+1] == stream->getWidth()
1911 && minDurations.data.i64[i+2] == stream->getHeight()) {
1912 int64_t minFrameDuration = minDurations.data.i64[i+3];
1913 return 1e9f / minFrameDuration;
1914 }
1915 }
1916 return 0.0f;
1917}
1918
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001920 * Methods called by subclasses
1921 */
1922
1923void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001924 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001925 std::vector<int> streamIds;
1926 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001927 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001928
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 {
1930 // Need mLock to safely update state and synchronize to current
1931 // state of methods in flight.
1932 Mutex::Autolock l(mLock);
1933 // We can get various system-idle notices from the status tracker
1934 // while starting up. Only care about them if we've actually sent
1935 // in some requests recently.
1936 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1937 return;
1938 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001939 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1940 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001941 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001942
1943 // Skip notifying listener if we're doing some user-transparent
1944 // state changes
1945 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001946
Austin Borger4a870a32022-02-25 01:48:41 +00001947 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1948 auto stream = mOutputStreams[i];
1949 if (stream.get() == nullptr) continue;
1950
1951 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1952 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1953
1954 // Populate stream statistics in case of Idle
1955 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001956 streamIds.push_back(stream->getId());
1957 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1958 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001959 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001960 if (camera3Stream != nullptr) {
1961 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001962 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001963 }
1964 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001965 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001966 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001967 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001968 stream->getDynamicRangeProfile(), streamUseCase,
1969 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001970 }
1971 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001972 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001973
1974 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001975 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001976 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001977 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001978 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001979 status_t res = OK;
1980 if (listener != nullptr) {
1981 if (idle) {
1982 // Get session stats from the builder, and notify the listener.
1983 int64_t requestCount, resultErrorCount;
1984 bool deviceError;
1985 std::map<int, StreamStats> streamStatsMap;
1986 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1987 &deviceError, &streamStatsMap);
1988 for (size_t i = 0; i < streamIds.size(); i++) {
1989 int streamId = streamIds[i];
1990 auto stats = streamStatsMap.find(streamId);
1991 if (stats != streamStatsMap.end()) {
1992 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1993 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1994 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1995 streamStats[i].mHistogramType =
1996 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1997 streamStats[i].mHistogramBins.assign(
1998 stats->second.mCaptureLatencyBins.begin(),
1999 stats->second.mCaptureLatencyBins.end());
2000 streamStats[i].mHistogramCounts.assign(
2001 stats->second.mCaptureLatencyHistogram.begin(),
2002 stats->second.mCaptureLatencyHistogram.end());
2003 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002004 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002005 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2006 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00002007 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002008 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002009 }
2010 if (res != OK) {
2011 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2012 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002013 }
2014}
2015
Shuzhen Wang758c2152017-01-10 18:26:18 -08002016status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002017 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002018 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002019 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2020 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002021
2022 if (surfaceIds == nullptr) {
2023 return BAD_VALUE;
2024 }
2025
Zhijun He5d677d12016-05-29 16:52:39 -07002026 Mutex::Autolock il(mInterfaceLock);
2027 Mutex::Autolock l(mLock);
2028
Shuzhen Wang758c2152017-01-10 18:26:18 -08002029 if (consumers.size() == 0) {
2030 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002031 return BAD_VALUE;
2032 }
2033
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002034 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2035 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002036 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002037 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002038 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002039
2040 // isConsumerConfigurationDeferred will be off after setConsumers
2041 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002042 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002043 if (res != OK) {
2044 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2045 return res;
2046 }
2047
Emilian Peev40ead602017-09-26 15:46:36 +01002048 for (auto &consumer : consumers) {
2049 int id = stream->getSurfaceId(consumer);
2050 if (id < 0) {
2051 CLOGE("Invalid surface id!");
2052 return BAD_VALUE;
2053 }
2054 surfaceIds->push_back(id);
2055 }
2056
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002057 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002058 if (!stream->isConfiguring()) {
2059 CLOGE("Stream %d was already fully configured.", streamId);
2060 return INVALID_OPERATION;
2061 }
Zhijun He5d677d12016-05-29 16:52:39 -07002062
Shuzhen Wang0129d522016-10-30 22:43:41 -07002063 res = stream->finishConfiguration();
2064 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002065 // If finishConfiguration fails due to abandoned surface, do not set
2066 // device to error state.
2067 bool isSurfaceAbandoned =
2068 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2069 if (!isSurfaceAbandoned) {
2070 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2071 stream->getId(), strerror(-res), res);
2072 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002073 return res;
2074 }
Zhijun He5d677d12016-05-29 16:52:39 -07002075 }
2076
2077 return OK;
2078}
2079
Emilian Peev40ead602017-09-26 15:46:36 +01002080status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2081 const std::vector<OutputStreamInfo> &outputInfo,
2082 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2083 Mutex::Autolock il(mInterfaceLock);
2084 Mutex::Autolock l(mLock);
2085
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002086 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2087 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002088 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002089 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002090 }
2091
2092 for (const auto &it : removedSurfaceIds) {
2093 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2094 CLOGE("Shared surface still part of a pending request!");
2095 return -EBUSY;
2096 }
2097 }
2098
Emilian Peev40ead602017-09-26 15:46:36 +01002099 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2100 if (res != OK) {
2101 CLOGE("Stream %d failed to update stream (error %d %s) ",
2102 streamId, res, strerror(-res));
2103 if (res == UNKNOWN_ERROR) {
2104 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2105 __FUNCTION__);
2106 }
2107 return res;
2108 }
2109
2110 return res;
2111}
2112
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002113status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2114 Mutex::Autolock il(mInterfaceLock);
2115 Mutex::Autolock l(mLock);
2116
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002117 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2118 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002119 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2120 return BAD_VALUE;
2121 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002122
2123 if (dropping) {
2124 mSessionStatsBuilder.stopCounter(streamId);
2125 } else {
2126 mSessionStatsBuilder.startCounter(streamId);
2127 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002128 return stream->dropBuffers(dropping);
2129}
2130
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002131/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 * Camera3Device private methods
2133 */
2134
2135sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002136 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002137 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002139 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002140 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002141
2142 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002143 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144 if (inputStreams.count > 0) {
2145 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002146 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002147 CLOGE("Request references unknown input stream %d",
2148 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149 return NULL;
2150 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002152 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002153 SET_ERR_L("%s: input stream %d is not configured!",
2154 __FUNCTION__, mInputStream->getId());
2155 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002157 // Check if stream prepare is blocking requests.
2158 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002159 CLOGE("Request references an input stream that's being prepared!");
2160 return NULL;
2161 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162
2163 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002164 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 }
2166
2167 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002168 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002170 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002171 return NULL;
2172 }
2173
2174 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002175 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2176 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002177 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002178 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002179 return NULL;
2180 }
Zhijun He5d677d12016-05-29 16:52:39 -07002181 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002182 auto iter = surfaceMap.find(streams.data.i32[i]);
2183 if (iter != surfaceMap.end()) {
2184 const std::vector<size_t>& surfaces = iter->second;
2185 for (const auto& surface : surfaces) {
2186 if (stream->isConsumerConfigurationDeferred(surface)) {
2187 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2188 "due to deferred consumer", stream->getId(), surface);
2189 return NULL;
2190 }
2191 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002192 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002193 }
2194
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002196 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2197 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002199 // Check if stream prepare is blocking requests.
2200 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002201 CLOGE("Request references an output stream that's being prepared!");
2202 return NULL;
2203 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002204
2205 newRequest->mOutputStreams.push(stream);
2206 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002207 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002208 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002209
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002210 auto rotateAndCropEntry =
2211 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2212 if (rotateAndCropEntry.count > 0 &&
2213 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2214 newRequest->mRotateAndCropAuto = true;
2215 } else {
2216 newRequest->mRotateAndCropAuto = false;
2217 }
2218
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002219 auto autoframingEntry =
2220 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2221 if (autoframingEntry.count > 0 &&
2222 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2223 newRequest->mAutoframingAuto = true;
2224 } else {
2225 newRequest->mAutoframingAuto = false;
2226 }
2227
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002228 auto zoomRatioEntry =
2229 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2230 if (zoomRatioEntry.count > 0 &&
2231 zoomRatioEntry.data.f[0] == 1.0f) {
2232 newRequest->mZoomRatioIs1x = true;
2233 } else {
2234 newRequest->mZoomRatioIs1x = false;
2235 }
2236
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002237 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002238 for (auto& settings : newRequest->mSettingsList) {
2239 auto testPatternModeEntry =
2240 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2241 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2242 testPatternModeEntry.data.i32[0] :
2243 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002244
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002245 auto testPatternDataEntry =
2246 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2247 if (testPatternDataEntry.count >= 4) {
2248 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2249 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2250 } else {
2251 settings.mOriginalTestPatternData[0] = 0;
2252 settings.mOriginalTestPatternData[1] = 0;
2253 settings.mOriginalTestPatternData[2] = 0;
2254 settings.mOriginalTestPatternData[3] = 0;
2255 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002256 }
2257 }
2258
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002259 if (mSupportZoomOverride) {
2260 for (auto& settings : newRequest->mSettingsList) {
2261 auto settingsOverrideEntry =
2262 settings.metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
2263 settings.mOriginalSettingsOverride = settingsOverrideEntry.count > 0 ?
2264 settingsOverrideEntry.data.i32[0] :
2265 ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
2266 }
2267 }
2268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002269 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002270}
2271
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002272void Camera3Device::cancelStreamsConfigurationLocked() {
2273 int res = OK;
2274 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2275 res = mInputStream->cancelConfiguration();
2276 if (res != OK) {
2277 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2278 mInputStream->getId(), strerror(-res), res);
2279 }
2280 }
2281
2282 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002283 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002284 if (outputStream->isConfiguring()) {
2285 res = outputStream->cancelConfiguration();
2286 if (res != OK) {
2287 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2288 outputStream->getId(), strerror(-res), res);
2289 }
2290 }
2291 }
2292
2293 // Return state to that at start of call, so that future configures
2294 // properly clean things up
2295 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2296 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002297
2298 res = mPreparerThread->resume();
2299 if (res != OK) {
2300 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2301 }
2302}
2303
Emilian Peev0d0191e2020-04-21 17:01:18 -07002304bool Camera3Device::checkAbandonedStreamsLocked() {
2305 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2306 return true;
2307 }
2308
2309 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2310 auto stream = mOutputStreams[i];
2311 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2312 return true;
2313 }
2314 }
2315
2316 return false;
2317}
2318
Emilian Peev3bead5f2020-05-28 17:29:08 -07002319bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002320 ATRACE_CALL();
2321 bool ret = false;
2322
Shuzhen Wang316781a2020-08-18 18:11:01 -07002323 nsecs_t startTime = systemTime();
2324
Bharatt Kukreja5681f782023-01-18 21:56:28 +00002325 // We must not hold mInterfaceLock here since this function is called from
2326 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2327 // deadlocks (http://b/143513518)
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002328 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2329
2330 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002331 if (checkAbandonedStreamsLocked()) {
2332 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2333 __FUNCTION__);
2334 return true;
2335 }
2336
Emilian Peev3bead5f2020-05-28 17:29:08 -07002337 status_t rc = NO_ERROR;
2338 bool markClientActive = false;
2339 if (mStatus == STATUS_ACTIVE) {
2340 markClientActive = true;
2341 mPauseStateNotify = true;
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00002342 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
Emilian Peev3bead5f2020-05-28 17:29:08 -07002343
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00002344 // This is essentially the same as calling rc = internalPauseAndWaitLocked(..), except that
2345 // we don't want to call setPaused(true) to avoid it interfering with setPaused() called
2346 // from createInputStream/createStream.
2347 rc = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
2348 /*requestThreadInvocation*/ true);
2349 if (rc != OK) {
2350 mStatusTracker->dumpActiveComponents();
2351 SET_ERR_L("Can't idle device in %f seconds!",
2352 maxExpectedDuration/1e9);
2353 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07002354 }
2355
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002356 if (rc == NO_ERROR) {
2357 mNeedConfig = true;
2358 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2359 if (rc == NO_ERROR) {
2360 ret = true;
2361 mPauseStateNotify = false;
2362 //Moving to active state while holding 'mLock' is important.
2363 //There could be pending calls to 'create-/deleteStream' which
2364 //will trigger another stream configuration while the already
2365 //present streams end up with outstanding buffers that will
2366 //not get drained.
2367 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002368 } else if (rc == DEAD_OBJECT) {
2369 // DEAD_OBJECT can be returned if either the consumer surface is
2370 // abandoned, or the HAL has died.
2371 // - If the HAL has died, configureStreamsLocked call will set
2372 // device to error state,
2373 // - If surface is abandoned, we should not set device to error
2374 // state.
2375 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002376 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002377 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002378 }
2379 } else {
2380 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2381 }
2382
Austin Borger74fca042022-05-23 12:41:21 -07002383 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002384 ns2ms(systemTime() - startTime));
2385
Emilian Peev3bead5f2020-05-28 17:29:08 -07002386 if (markClientActive) {
2387 mStatusTracker->markComponentActive(clientStatusId);
2388 }
2389
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002390 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002391}
2392
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002393status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002394 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002395 ATRACE_CALL();
2396 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002397
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002398 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002399 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002400 return INVALID_OPERATION;
2401 }
2402
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002403 if (operatingMode < 0) {
2404 CLOGE("Invalid operating mode: %d", operatingMode);
2405 return BAD_VALUE;
2406 }
2407
2408 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002409 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002410
2411 if (mOperatingMode != operatingMode) {
2412 mNeedConfig = true;
2413 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2414 mOperatingMode = operatingMode;
2415 }
2416
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002417 // Reset min expected duration when session is reconfigured.
2418 mMinExpectedDuration = 0;
2419
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002420 // In case called from configureStreams, abort queued input buffers not belonging to
2421 // any pending requests.
2422 if (mInputStream != NULL && notifyRequestThread) {
2423 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002424 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002425 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002426 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002427 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002428 if (res != OK) {
2429 // Exhausted acquiring all input buffers.
2430 break;
2431 }
2432
Emilian Peevf4816702020-04-03 15:44:51 -07002433 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002434 res = mInputStream->returnInputBuffer(inputBuffer);
2435 if (res != OK) {
2436 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2437 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2438 }
2439 }
2440 }
2441
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002442 if (!mNeedConfig) {
2443 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2444 return OK;
2445 }
2446
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002447 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002448 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002449 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2450 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002451 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002452 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002453 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002454 }
2455
Shuzhen Wang16610a62022-12-15 22:38:07 -08002456 // Override stream use case based on "adb shell command"
2457 overrideStreamUseCaseLocked();
2458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002460 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002461
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002462 mPreparerThread->pause();
2463
Emilian Peevf4816702020-04-03 15:44:51 -07002464 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002465 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002467 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002468
Emilian Peevf4816702020-04-03 15:44:51 -07002469 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002470 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002471 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002472
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002473
2474 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002475 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 inputStream = mInputStream->startConfiguration();
2477 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002478 CLOGE("Can't start input stream configuration");
2479 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002480 return INVALID_OPERATION;
2481 }
2482 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002483
2484 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002485 }
2486
Shuzhen Wang99080502021-03-07 21:08:20 -08002487 mGroupIdPhysicalCameraMap.clear();
Emilian Peevd865f0d2023-03-17 17:13:07 -07002488 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002489 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002490
2491 // Don't configure bidi streams twice, nor add them twice to the list
2492 if (mOutputStreams[i].get() ==
2493 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2494
2495 config.num_streams--;
2496 continue;
2497 }
2498
Emilian Peevf4816702020-04-03 15:44:51 -07002499 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002500 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002501 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502 CLOGE("Can't start output stream configuration");
2503 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002504 return INVALID_OPERATION;
2505 }
2506 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002507
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002508 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002509 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2510 // always occupy the initial entry.
Emilian Peeve579d8b2023-02-28 14:16:08 -08002511 if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2512 (outputStream->data_space ==
2513 static_cast<android_dataspace_t>(
2514 aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002515 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002516 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2517 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002518 } else if (outputStream->data_space ==
2519 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2520 bufferSizes[k] = outputStream->width * outputStream->height;
2521 } else {
2522 ALOGW("%s: Blob dataSpace %d not supported",
2523 __FUNCTION__, outputStream->data_space);
2524 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002525 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002526
2527 if (mOutputStreams[i]->isMultiResolution()) {
2528 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2529 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2530 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2531 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002532
2533 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07002534 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002535 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002536 }
2537
2538 config.streams = streams.editArray();
2539
2540 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002541 // max_buffers, usage, and priv fields, as well as data_space and format
2542 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002543
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002544 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002545 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002546 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002547 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002548
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002549 if (res == BAD_VALUE) {
2550 // HAL rejected this set of streams as unsupported, clean up config
2551 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002552 CLOGE("Set of requested inputs/outputs not supported by HAL");
2553 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002554 return BAD_VALUE;
2555 } else if (res != OK) {
2556 // Some other kind of error from configure_streams - this is not
2557 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002558 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2559 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 return res;
2561 }
2562
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002563 // Finish all stream configuration immediately.
2564 // TODO: Try to relax this later back to lazy completion, which should be
2565 // faster
2566
Igor Murashkin073f8572013-05-02 14:59:28 -07002567 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002568 bool streamReConfigured = false;
2569 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002570 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002571 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002572 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002573 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002574 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2575 return DEAD_OBJECT;
2576 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002577 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002578 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002579 if (streamReConfigured) {
2580 mInterface->onStreamReConfigured(mInputStream->getId());
2581 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002582 }
2583
2584 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002585 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002586 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002587 bool streamReConfigured = false;
2588 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002589 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002590 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002591 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002592 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002593 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2594 return DEAD_OBJECT;
2595 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002596 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002597 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002598 if (streamReConfigured) {
2599 mInterface->onStreamReConfigured(outputStream->getId());
2600 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002601 }
2602 }
2603
Emilian Peevd865f0d2023-03-17 17:13:07 -07002604 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002605
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606 // Request thread needs to know to avoid using repeat-last-settings protocol
2607 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002608 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002609 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2610 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002611 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612
Zhijun He90f7c372016-08-16 16:19:43 -07002613 char value[PROPERTY_VALUE_MAX];
2614 property_get("camera.fifo.disable", value, "0");
2615 int32_t disableFifo = atoi(value);
2616 if (disableFifo != 1) {
2617 // Boost priority of request thread to SCHED_FIFO.
2618 pid_t requestThreadTid = mRequestThread->getTid();
2619 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002620 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002621 if (res != OK) {
2622 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2623 strerror(-res), res);
2624 } else {
2625 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2626 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002627 }
2628
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002629 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002630 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2631 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2632 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2633 sessionParams.unlock(newSessionParams);
2634 mSessionParams.unlock(currentSessionParams);
2635 if (updateSessionParams) {
2636 mSessionParams = sessionParams;
2637 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002638
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002639 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002642 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002643
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002644 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002645
Zhijun He0a210512014-07-24 13:45:15 -07002646 // tear down the deleted streams after configure streams.
2647 mDeletedStreams.clear();
2648
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002649 auto rc = mPreparerThread->resume();
2650 if (rc != OK) {
2651 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2652 return rc;
2653 }
2654
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002655 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002656 mRequestBufferSM.onStreamsConfigured();
2657 }
2658
Cliff Wu3b268182021-07-06 15:44:43 +08002659 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002660 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002661 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002662 // configure the injection streams.
2663 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002664 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002665 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2666 res = mInjectionMethods->injectCamera(config, bufferSizes);
2667 if (res != OK) {
2668 ALOGE("Can't finish inject camera process!");
2669 return res;
2670 }
Cliff Wu3b268182021-07-06 15:44:43 +08002671 } else {
2672 // First run configureStreamsLocked() and then call injectCamera() case:
2673 // If the stream configuration has been completed and camera deive is active, but the
2674 // injection camera has not been injected yet, we need to store the stream configuration of
2675 // the internal camera (because the stream configuration of the injection camera is based
2676 // on the internal camera). When injecting occurs later, this configuration can be used by
2677 // the injection camera.
2678 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2679 " injection camera has not been injected yet.", __FUNCTION__);
2680 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002681 }
2682
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002684}
2685
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002686status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002687 ATRACE_CALL();
2688 status_t res;
2689
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002690 if (mFakeStreamId != NO_STREAM) {
2691 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002692 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002693 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002694 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002695 return INVALID_OPERATION;
2696 }
2697
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002698 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002699
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002700 sp<Camera3OutputStreamInterface> fakeStream =
2701 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002702
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002703 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002704 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002705 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002706 return res;
2707 }
2708
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002709 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002710 mNextStreamId++;
2711
2712 return OK;
2713}
2714
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002715status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002716 ATRACE_CALL();
2717 status_t res;
2718
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002719 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002720 if (mOutputStreams.size() == 1) return OK;
2721
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002722 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002723
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002724 // Ok, have a fake stream and there's at least one other output stream,
2725 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002726
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002727 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002728 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002729 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002730 return INVALID_OPERATION;
2731 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002732 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002733
2734 // Free up the stream endpoint so that it can be used by some other stream
2735 res = deletedStream->disconnect();
2736 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002737 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002738 // fall through since we want to still list the stream as deleted.
2739 }
2740 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002741 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002742
2743 return res;
2744}
2745
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002746void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002747 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002748 Mutex::Autolock l(mLock);
2749 va_list args;
2750 va_start(args, fmt);
2751
2752 setErrorStateLockedV(fmt, args);
2753
2754 va_end(args);
2755}
2756
2757void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002758 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002759 Mutex::Autolock l(mLock);
2760 setErrorStateLockedV(fmt, args);
2761}
2762
2763void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2764 va_list args;
2765 va_start(args, fmt);
2766
2767 setErrorStateLockedV(fmt, args);
2768
2769 va_end(args);
2770}
2771
2772void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002773 // Print out all error messages to log
2774 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002775 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002776
2777 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002778 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002779
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002780 mErrorCause = errorCause;
2781
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002782 if (mRequestThread != nullptr) {
2783 mRequestThread->setPaused(true);
2784 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002785 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002786
2787 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002788 sp<NotificationListener> listener = mListener.promote();
2789 if (listener != NULL) {
2790 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002791 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002792 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002793 }
2794
2795 // Save stack trace. View by dumping it later.
2796 CameraTraces::saveTrace();
2797 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002798}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002799
2800/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002801 * In-flight request management
2802 */
2803
Jianing Weicb0652e2014-03-12 18:29:36 -07002804status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002805 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002806 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002807 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002808 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002809 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002810 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002811 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002812 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002813
2814 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002815 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002816 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002817 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2818 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002819 if (res < 0) return res;
2820
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002821 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002822 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2823 // avoid a deadlock during reprocess requests.
2824 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002825 if (mStatusTracker != nullptr) {
2826 mStatusTracker->markComponentActive(mInFlightStatusId);
2827 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002828 }
2829
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002830 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002831 return OK;
2832}
2833
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002834void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002835 // Indicate idle inFlightMap to the status tracker
2836 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002837 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002838 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2839 // avoid a deadlock during reprocess requests.
2840 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002841 if (mStatusTracker != nullptr) {
2842 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2843 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002844 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002845 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002846}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002847
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002848void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002849 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002850 // something has likely gone wrong. This might still be legit only if application send in
2851 // a long burst of long exposure requests.
2852 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2853 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2854 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2855 mInFlightMap.size(), mExpectedInflightDuration);
2856 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2857 kInFlightWarnLimitHighSpeed) {
2858 CLOGW("In-flight list too large for high speed configuration: %zu,"
2859 "total inflight duration %" PRIu64,
2860 mInFlightMap.size(), mExpectedInflightDuration);
2861 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002862 }
2863}
2864
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002865void Camera3Device::onInflightMapFlushedLocked() {
2866 mExpectedInflightDuration = 0;
2867}
2868
2869void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002870 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002871 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2872 mInFlightMap.removeItemsAt(idx, 1);
2873
2874 onInflightEntryRemovedLocked(duration);
2875}
2876
2877
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002878void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002879 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002880 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002881 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002882 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002883 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002884 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002885
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002886 FlushInflightReqStates states {
2887 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002888 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002889
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002890 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002891}
2892
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002893CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002894 ALOGV("%s", __FUNCTION__);
2895
Igor Murashkin1e479c02013-09-06 16:55:14 -07002896 CameraMetadata retVal;
2897
2898 if (mRequestThread != NULL) {
2899 retVal = mRequestThread->getLatestRequest();
2900 }
2901
Igor Murashkin1e479c02013-09-06 16:55:14 -07002902 return retVal;
2903}
2904
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002905void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002906 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002907 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002908 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2909 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002910
2911 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002912 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002913}
2914
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002915void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002916 std::vector<native_handle_t*> *handles, bool closeFd) {
2917 if (handles == nullptr) {
2918 return;
2919 }
2920 if (closeFd) {
2921 for (auto& handle : *handles) {
2922 native_handle_close(handle);
2923 }
2924 }
2925 for (auto& handle : *handles) {
2926 native_handle_delete(handle);
2927 }
2928 handles->clear();
2929 return;
2930}
2931
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002932/**
2933 * HalInterface inner class methods
2934 */
2935
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002936void Camera3Device::HalInterface::getInflightBufferKeys(
2937 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002938 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002939 return;
2940}
2941
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002942void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2943 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002944 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002945 return;
2946}
2947
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002948bool Camera3Device::HalInterface::verifyBufferIds(
2949 int32_t streamId, std::vector<uint64_t>& bufIds) {
2950 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002951}
2952
2953status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002954 int32_t frameNumber, int32_t streamId,
2955 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002956 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002957}
2958
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002959status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002960 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002961 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002962}
2963
2964// Find and pop a buffer_handle_t based on bufferId
2965status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002966 uint64_t bufferId,
2967 /*out*/ buffer_handle_t** buffer,
2968 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002969 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002970}
2971
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002972std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2973 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002974 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002975}
2976
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002977uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2978 const native_handle_t* handle) {
2979 return mBufferRecords.removeOneBufferCache(streamId, handle);
2980}
2981
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002982void Camera3Device::HalInterface::onBufferFreed(
2983 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002984 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2985 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2986 if (bufferId != BUFFER_ID_NO_BUFFER) {
2987 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002988 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002989}
2990
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002991void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002992 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2993 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2994 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002995 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2996 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002997}
2998
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002999/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003000 * RequestThread inner class methods
3001 */
3002
3003Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003004 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003005 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07003006 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07003007 bool supportCameraMute,
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003008 bool overrideToPortrait,
3009 bool supportSettingsOverride) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003010 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003011 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003012 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003013 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003014 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003015 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003016 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003017 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003018 mReconfigured(false),
3019 mDoPause(false),
3020 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003021 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003022 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003023 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003024 mCurrentAfTriggerId(0),
3025 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003026 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00003027 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07003028 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003029 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003030 mCameraMuteChanged(false),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003031 mSettingsOverride(ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003032 mRepeatingLastFrameNumber(
3033 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003034 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003035 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003036 mRequestLatency(kRequestLatencyBinSize),
3037 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003038 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07003039 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07003040 mSupportCameraMute(supportCameraMute),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003041 mOverrideToPortrait(overrideToPortrait),
3042 mSupportSettingsOverride(supportSettingsOverride) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003043 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08003044 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003045}
3046
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003047Camera3Device::RequestThread::~RequestThread() {}
3048
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003049void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003050 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003051 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003052 Mutex::Autolock l(mRequestLock);
3053 mListener = listener;
3054}
3055
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003056void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08003057 const CameraMetadata& sessionParams,
3058 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003059 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003060 Mutex::Autolock l(mRequestLock);
3061 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003062 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08003063 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003064 // Prepare video stream for high speed recording.
3065 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003066 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003067}
3068
Jianing Wei90e59c92014-03-12 18:29:36 -07003069status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003070 List<sp<CaptureRequest> > &requests,
3071 /*out*/
3072 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003073 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003074 Mutex::Autolock l(mRequestLock);
3075 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3076 ++it) {
3077 mRequestQueue.push_back(*it);
3078 }
3079
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003080 if (lastFrameNumber != NULL) {
3081 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3082 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3083 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3084 *lastFrameNumber);
3085 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003086
Jianing Wei90e59c92014-03-12 18:29:36 -07003087 unpauseForNewRequests();
3088
3089 return OK;
3090}
3091
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003092
3093status_t Camera3Device::RequestThread::queueTrigger(
3094 RequestTrigger trigger[],
3095 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003096 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003097 Mutex::Autolock l(mTriggerMutex);
3098 status_t ret;
3099
3100 for (size_t i = 0; i < count; ++i) {
3101 ret = queueTriggerLocked(trigger[i]);
3102
3103 if (ret != OK) {
3104 return ret;
3105 }
3106 }
3107
3108 return OK;
3109}
3110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003111const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3112 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003113 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003114 if (d != nullptr) return d->mId;
3115 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003116}
3117
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003118status_t Camera3Device::RequestThread::queueTriggerLocked(
3119 RequestTrigger trigger) {
3120
3121 uint32_t tag = trigger.metadataTag;
3122 ssize_t index = mTriggerMap.indexOfKey(tag);
3123
3124 switch (trigger.getTagType()) {
3125 case TYPE_BYTE:
3126 // fall-through
3127 case TYPE_INT32:
3128 break;
3129 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003130 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3131 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003132 return INVALID_OPERATION;
3133 }
3134
3135 /**
3136 * Collect only the latest trigger, since we only have 1 field
3137 * in the request settings per trigger tag, and can't send more than 1
3138 * trigger per request.
3139 */
3140 if (index != NAME_NOT_FOUND) {
3141 mTriggerMap.editValueAt(index) = trigger;
3142 } else {
3143 mTriggerMap.add(tag, trigger);
3144 }
3145
3146 return OK;
3147}
3148
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003149status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003150 const RequestList &requests,
3151 /*out*/
3152 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003153 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003154 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003155 if (lastFrameNumber != NULL) {
3156 *lastFrameNumber = mRepeatingLastFrameNumber;
3157 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003158 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003159 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003160 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3161 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003162
3163 unpauseForNewRequests();
3164
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003165 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003166 return OK;
3167}
3168
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003169bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003170 if (mRepeatingRequests.empty()) {
3171 return false;
3172 }
3173 int32_t requestId = requestIn->mResultExtras.requestId;
3174 const RequestList &repeatRequests = mRepeatingRequests;
3175 // All repeating requests are guaranteed to have same id so only check first quest
3176 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3177 return (firstRequest->mResultExtras.requestId == requestId);
3178}
3179
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003180status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003181 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003182 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003183 return clearRepeatingRequestsLocked(lastFrameNumber);
3184
3185}
3186
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003187status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3188 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003189 std::vector<int32_t> streamIds;
3190 for (const auto& request : mRepeatingRequests) {
3191 for (const auto& stream : request->mOutputStreams) {
3192 streamIds.push_back(stream->getId());
3193 }
3194 }
3195
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003196 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003197 if (lastFrameNumber != NULL) {
3198 *lastFrameNumber = mRepeatingLastFrameNumber;
3199 }
Emilian Peev2295df72021-11-12 18:14:10 -08003200
3201 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3202
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003203 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003204 return OK;
3205}
3206
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003207status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003208 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003209 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003210 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003211 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003212
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003213 // Send errors for all requests pending in the request queue, including
3214 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003215 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003216 if (listener != NULL) {
3217 for (RequestList::iterator it = mRequestQueue.begin();
3218 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003219 // Abort the input buffers for reprocess requests.
3220 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003221 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003222 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003223 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003224 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003225 if (res != OK) {
3226 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3227 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3228 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003229 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003230 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3231 if (res != OK) {
3232 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3233 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3234 }
3235 }
3236 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003237 // Set the frame number this request would have had, if it
3238 // had been submitted; this frame number will not be reused.
3239 // The requestId and burstId fields were set when the request was
3240 // submitted originally (in convertMetadataListToRequestListLocked)
3241 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003242 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003243 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003244 }
3245 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003246 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003247
3248 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003249 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003250 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003251 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003252 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003253 return OK;
3254}
3255
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003256status_t Camera3Device::RequestThread::flush() {
3257 ATRACE_CALL();
3258 Mutex::Autolock l(mFlushLock);
3259
Emilian Peev08dd2452017-04-06 16:55:14 +01003260 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003261}
3262
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003263void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003264 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003265 Mutex::Autolock l(mPauseLock);
3266 mDoPause = paused;
3267 mDoPauseSignal.signal();
3268}
3269
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003270status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3271 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003272 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003273 Mutex::Autolock l(mLatestRequestMutex);
3274 status_t res;
3275 while (mLatestRequestId != requestId) {
3276 nsecs_t startTime = systemTime();
3277
3278 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3279 if (res != OK) return res;
3280
3281 timeout -= (systemTime() - startTime);
3282 }
3283
3284 return OK;
3285}
3286
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003287void Camera3Device::RequestThread::requestExit() {
3288 // Call parent to set up shutdown
3289 Thread::requestExit();
3290 // The exit from any possible waits
3291 mDoPauseSignal.signal();
3292 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003293
3294 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3295 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003296}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003297
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003298void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003299 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003300 bool surfaceAbandoned = false;
3301 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003302 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003303 {
3304 Mutex::Autolock l(mRequestLock);
3305 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3306 // repeating requests.
3307 for (const auto& request : mRepeatingRequests) {
3308 for (const auto& s : request->mOutputStreams) {
3309 if (s->isAbandoned()) {
3310 surfaceAbandoned = true;
3311 clearRepeatingRequestsLocked(&lastFrameNumber);
3312 break;
3313 }
3314 }
3315 if (surfaceAbandoned) {
3316 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003317 }
3318 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003319 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003320 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003321
3322 if (listener != NULL && surfaceAbandoned) {
3323 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003324 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003325}
3326
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003327bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003328 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003329 status_t res;
3330 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003331 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003332 uint32_t numRequestProcessed = 0;
3333 for (size_t i = 0; i < batchSize; i++) {
3334 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003335 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003336 }
3337
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003338 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3339
3340 bool triggerRemoveFailed = false;
3341 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3342 for (size_t i = 0; i < numRequestProcessed; i++) {
3343 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3344 nextRequest.submitted = true;
3345
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003346 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003347
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003348 if (!triggerRemoveFailed) {
3349 // Remove any previously queued triggers (after unlock)
3350 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3351 if (removeTriggerRes != OK) {
3352 triggerRemoveFailed = true;
3353 triggerFailedRequest = nextRequest;
3354 }
3355 }
3356 }
3357
3358 if (triggerRemoveFailed) {
3359 SET_ERR("RequestThread: Unable to remove triggers "
3360 "(capture request %d, HAL device: %s (%d)",
3361 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3362 cleanUpFailedRequests(/*sendRequestError*/ false);
3363 return false;
3364 }
3365
3366 if (res != OK) {
3367 // Should only get a failure here for malformed requests or device-level
3368 // errors, so consider all errors fatal. Bad metadata failures should
3369 // come through notify.
3370 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3371 mNextRequests[numRequestProcessed].halRequest.frame_number,
3372 strerror(-res), res);
3373 cleanUpFailedRequests(/*sendRequestError*/ false);
3374 return false;
3375 }
3376 return true;
3377}
3378
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003379Camera3Device::RequestThread::ExpectedDurationInfo
3380 Camera3Device::RequestThread::calculateExpectedDurationRange(
3381 const camera_metadata_t *request) {
3382 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003383 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003384 InFlightRequest::kDefaultMaxExpectedDuration,
3385 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003386 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3387 find_camera_metadata_ro_entry(request,
3388 ANDROID_CONTROL_AE_MODE,
3389 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003390 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003391
3392 switch (e.data.u8[0]) {
3393 case ANDROID_CONTROL_AE_MODE_OFF:
3394 find_camera_metadata_ro_entry(request,
3395 ANDROID_SENSOR_EXPOSURE_TIME,
3396 &e);
3397 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003398 expectedDurationInfo.minDuration = e.data.i64[0];
3399 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003400 }
3401 find_camera_metadata_ro_entry(request,
3402 ANDROID_SENSOR_FRAME_DURATION,
3403 &e);
3404 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003405 expectedDurationInfo.minDuration =
3406 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3407 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003408 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003409 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003410 break;
3411 default:
3412 find_camera_metadata_ro_entry(request,
3413 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3414 &e);
3415 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003416 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3417 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003418 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003419 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003420 break;
3421 }
3422
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003423 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003424}
3425
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003426bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3427 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3428 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3429 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3430 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3431 return true;
3432 }
3433
3434 return false;
3435}
3436
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003437void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3438 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003439 camera_capture_request_t& halRequest = nextRequest.halRequest;
3440 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003441 Mutex::Autolock al(mLatestRequestMutex);
3442
Shuzhen Wang83bff122020-11-20 15:51:39 -08003443 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003444 mLatestRequest.acquire(cloned);
3445
3446 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003447 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3448 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3449 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003450 CameraMetadata(cloned));
3451 }
3452
3453 sp<Camera3Device> parent = mParent.promote();
3454 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003455 int32_t inputStreamId = -1;
3456 if (halRequest.input_buffer != nullptr) {
3457 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3458 }
3459
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003460 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003461 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003462 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3463 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003464 }
3465 }
3466
Shuzhen Wang83bff122020-11-20 15:51:39 -08003467 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003468 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003469 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003470 }
3471
Shuzhen Wang83bff122020-11-20 15:51:39 -08003472 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003473}
3474
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003475bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3476 ATRACE_CALL();
3477 bool updatesDetected = false;
3478
Emilian Peev4ec17882019-01-24 17:16:58 -08003479 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003480 for (auto tag : mSessionParamKeys) {
3481 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003482 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003483
3484 if (entry.count > 0) {
3485 bool isDifferent = false;
3486 if (lastEntry.count > 0) {
3487 // Have a last value, compare to see if changed
3488 if (lastEntry.type == entry.type &&
3489 lastEntry.count == entry.count) {
3490 // Same type and count, compare values
3491 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3492 size_t entryBytes = bytesPerValue * lastEntry.count;
3493 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3494 if (cmp != 0) {
3495 isDifferent = true;
3496 }
3497 } else {
3498 // Count or type has changed
3499 isDifferent = true;
3500 }
3501 } else {
3502 // No last entry, so always consider to be different
3503 isDifferent = true;
3504 }
3505
3506 if (isDifferent) {
3507 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003508 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3509 updatesDetected = true;
3510 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003511 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003512 }
3513 } else if (lastEntry.count > 0) {
3514 // Value has been removed
3515 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003516 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003517 updatesDetected = true;
3518 }
3519 }
3520
Emilian Peev4ec17882019-01-24 17:16:58 -08003521 bool reconfigureRequired;
3522 if (updatesDetected) {
3523 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3524 updatedParams);
3525 mLatestSessionParams = updatedParams;
3526 } else {
3527 reconfigureRequired = false;
3528 }
3529
3530 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003531}
3532
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003533bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003534 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003535 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003536 // Any function called from threadLoop() must not hold mInterfaceLock since
3537 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3538 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003539
3540 // Handle paused state.
3541 if (waitIfPaused()) {
3542 return true;
3543 }
3544
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003545 // Wait for the next batch of requests.
3546 waitForNextRequestBatch();
3547 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003548 return true;
3549 }
3550
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003551 // Get the latest request ID, if any
3552 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003553 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003554 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003555 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003556 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003557 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003558 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3559 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003560 }
3561
Emilian Peevd865f0d2023-03-17 17:13:07 -07003562 for (size_t i = 0; i < mNextRequests.size(); i++) {
3563 auto& nextRequest = mNextRequests.editItemAt(i);
3564 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3565 // Do not override rotate&crop for stream configurations that include
3566 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3567 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3568 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3569 overrideAutoRotateAndCrop(captureRequest);
3570 captureRequest->mAutoframingChanged = overrideAutoframing(captureRequest);
3571 }
3572
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003573 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3574 // or a single request from streaming or burst. In either case the first element
3575 // should contain the latest camera settings that we need to check for any session
3576 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003577 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003578 res = OK;
3579
3580 //Input stream buffers are already acquired at this point so an input stream
3581 //will not be able to move to idle state unless we force it.
3582 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3583 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3584 if (res != OK) {
3585 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3586 cleanUpFailedRequests(/*sendRequestError*/ false);
3587 return false;
3588 }
3589 }
3590
3591 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003592 sp<Camera3Device> parent = mParent.promote();
3593 if (parent != nullptr) {
3594 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003595 }
3596
3597 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3598 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3599 if (res != OK) {
3600 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3601 cleanUpFailedRequests(/*sendRequestError*/ false);
3602 return false;
3603 }
3604 }
3605 }
3606 }
3607
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003608 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003609 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003610 if (res == TIMED_OUT) {
3611 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003612 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003613 // Check if any stream is abandoned.
3614 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003615 return true;
3616 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003617 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003618 return false;
3619 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003620
Zhijun Hecc27e112013-10-03 16:12:43 -07003621 // Inform waitUntilRequestProcessed thread of a new request ID
3622 {
3623 Mutex::Autolock al(mLatestRequestMutex);
3624
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003625 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003626 mLatestRequestSignal.signal();
3627 }
3628
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003629 // Submit a batch of requests to HAL.
3630 // Use flush lock only when submitting multilple requests in a batch.
3631 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3632 // which may take a long time to finish so synchronizing flush() and
3633 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3634 // For now, only synchronize for high speed recording and we should figure something out for
3635 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003636 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003637
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003638 if (useFlushLock) {
3639 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003640 }
3641
Zhijun Hef0645c12016-08-02 00:58:11 -07003642 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003643 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003644
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003645 sp<Camera3Device> parent = mParent.promote();
3646 if (parent != nullptr) {
3647 parent->mRequestBufferSM.onSubmittingRequest();
3648 }
3649
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003650 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003651 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003652 submitRequestSuccess = sendRequestsBatch();
3653
Shuzhen Wang686f6442017-06-20 16:16:04 -07003654 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3655 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003656
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003657 if (useFlushLock) {
3658 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003659 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003660
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003661 // Unset as current request
3662 {
3663 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003664 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003665 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003666 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003667
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003668 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003669}
3670
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003671status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3672 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3673 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3674 ANDROID_SCALER_CROP_REGION_SET};
3675 if (request == nullptr) {
3676 ALOGE("%s request metadata nullptr", __FUNCTION__);
3677 return BAD_VALUE;
3678 }
3679 status_t res = OK;
3680 for (const auto &key : kFwkOnlyRegionKeys) {
3681 if (request->exists(key)) {
3682 res = request->erase(key);
3683 if (res != OK) {
3684 return res;
3685 }
3686 }
3687 }
3688 return OK;
3689}
3690
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003691status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003692 ATRACE_CALL();
3693
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003694 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003695 for (size_t i = 0; i < mNextRequests.size(); i++) {
3696 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003697 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003698 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3699 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003700
3701 // Prepare a request to HAL
3702 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3703
3704 // Insert any queued triggers (before metadata is locked)
3705 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003706 if (res < 0) {
3707 SET_ERR("RequestThread: Unable to insert triggers "
3708 "(capture request %d, HAL device: %s (%d)",
3709 halRequest->frame_number, strerror(-res), res);
3710 return INVALID_OPERATION;
3711 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003712
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003713 int triggerCount = res;
3714 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3715 mPrevTriggers = triggerCount;
3716
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003717 bool testPatternChanged = overrideTestPattern(captureRequest);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003718 bool settingsOverrideChanged = overrideSettingsOverride(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003719
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003720 // If the request is the same as last, or we had triggers now or last time or
3721 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003722 bool newRequest =
Emilian Peevd865f0d2023-03-17 17:13:07 -07003723 (mPrevRequest != captureRequest || triggersMixedIn ||
3724 captureRequest->mRotateAndCropChanged ||
3725 captureRequest->mAutoframingChanged ||
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003726 testPatternChanged || settingsOverrideChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003727 // Request settings are all the same within one batch, so only treat the first
3728 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003729 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003730 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003731 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003732 /**
3733 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003734 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003735 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003736 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003737 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003738 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003739 "(capture request %d, HAL device: %s (%d)",
3740 halRequest->frame_number, strerror(-res), res);
3741 return INVALID_OPERATION;
3742 }
3743
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003744 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003745 sp<Camera3Device> parent = mParent.promote();
3746 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003747 List<PhysicalCameraSettings>::iterator it;
3748 for (it = captureRequest->mSettingsList.begin();
3749 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003750 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3751 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003752 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3753 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3754 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3755 res);
3756 return INVALID_OPERATION;
3757 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003758 continue;
3759 }
3760
3761 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3762 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3763 updateCaptureRequest(&(it->metadata));
3764 if (res != OK) {
3765 SET_ERR("RequestThread: Unable to correct capture requests "
3766 "for scaler crop region and metering regions for request "
3767 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3768 res);
3769 return INVALID_OPERATION;
3770 }
3771 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003772 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3773 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3774 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3775 res);
3776 return INVALID_OPERATION;
3777 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003778 }
3779 }
3780
3781 // Correct metadata regions for distortion correction if enabled
3782 for (it = captureRequest->mSettingsList.begin();
3783 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003784 if (parent->mDistortionMappers.find(it->cameraId) ==
3785 parent->mDistortionMappers.end()) {
3786 continue;
3787 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003788
3789 if (!captureRequest->mDistortionCorrectionUpdated) {
3790 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3791 &(it->metadata));
3792 if (res != OK) {
3793 SET_ERR("RequestThread: Unable to correct capture requests "
3794 "for lens distortion for request %d: %s (%d)",
3795 halRequest->frame_number, strerror(-res), res);
3796 return INVALID_OPERATION;
3797 }
3798 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003799 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003800 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003801
3802 for (it = captureRequest->mSettingsList.begin();
3803 it != captureRequest->mSettingsList.end(); it++) {
3804 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3805 parent->mZoomRatioMappers.end()) {
3806 continue;
3807 }
3808
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003809 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003810 cameraIdsWithZoom.insert(it->cameraId);
3811 }
3812
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003813 if (!captureRequest->mZoomRatioUpdated) {
3814 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3815 &(it->metadata));
3816 if (res != OK) {
3817 SET_ERR("RequestThread: Unable to correct capture requests "
3818 "for zoom ratio for request %d: %s (%d)",
3819 halRequest->frame_number, strerror(-res), res);
3820 return INVALID_OPERATION;
3821 }
3822 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003823 }
3824 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003825 if (captureRequest->mRotateAndCropAuto &&
3826 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003827 for (it = captureRequest->mSettingsList.begin();
3828 it != captureRequest->mSettingsList.end(); it++) {
3829 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3830 if (mapper != parent->mRotateAndCropMappers.end()) {
3831 res = mapper->second.updateCaptureRequest(&(it->metadata));
3832 if (res != OK) {
3833 SET_ERR("RequestThread: Unable to correct capture requests "
3834 "for rotate-and-crop for request %d: %s (%d)",
3835 halRequest->frame_number, strerror(-res), res);
3836 return INVALID_OPERATION;
3837 }
3838 }
3839 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003840 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003841 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003842
3843 for (it = captureRequest->mSettingsList.begin();
3844 it != captureRequest->mSettingsList.end(); it++) {
3845 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3846 mVndkVersion, it->metadata, false /*isStatic*/);
3847 if (res != OK) {
3848 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3849 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3850 return INVALID_OPERATION;
3851 }
3852 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003853 }
3854 }
3855
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003856 /**
3857 * The request should be presorted so accesses in HAL
3858 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3859 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003860 captureRequest->mSettingsList.begin()->metadata.sort();
3861 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003862 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003863 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003864 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3865
3866 IF_ALOGV() {
3867 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3868 find_camera_metadata_ro_entry(
3869 halRequest->settings,
3870 ANDROID_CONTROL_AF_TRIGGER,
3871 &e
3872 );
3873 if (e.count > 0) {
3874 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3875 __FUNCTION__,
3876 halRequest->frame_number,
3877 e.data.u8[0]);
3878 }
3879 }
3880 } else {
3881 // leave request.settings NULL to indicate 'reuse latest given'
3882 ALOGVV("%s: Request settings are REUSED",
3883 __FUNCTION__);
3884 }
3885
Emilian Peevaebbe412018-01-15 13:53:24 +00003886 if (captureRequest->mSettingsList.size() > 1) {
3887 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3888 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003889 if (newRequest) {
3890 halRequest->physcam_settings =
3891 new const camera_metadata* [halRequest->num_physcam_settings];
3892 } else {
3893 halRequest->physcam_settings = nullptr;
3894 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003895 auto it = ++captureRequest->mSettingsList.begin();
3896 size_t i = 0;
3897 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3898 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003899 if (newRequest) {
3900 it->metadata.sort();
3901 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3902 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003903 }
3904 }
3905
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003906 uint32_t totalNumBuffers = 0;
3907
3908 // Fill in buffers
3909 if (captureRequest->mInputStream != NULL) {
3910 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003911
3912 halRequest->input_width = captureRequest->mInputBufferSize.width;
3913 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003914 totalNumBuffers += 1;
3915 } else {
3916 halRequest->input_buffer = NULL;
3917 }
3918
Emilian Peevf4816702020-04-03 15:44:51 -07003919 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003920 captureRequest->mOutputStreams.size());
3921 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003922 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003923
3924 sp<Camera3Device> parent = mParent.promote();
3925 if (parent == NULL) {
3926 // Should not happen, and nowhere to send errors to, so just log it
3927 CLOGE("RequestThread: Parent is gone");
3928 return INVALID_OPERATION;
3929 }
3930 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3931
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003932 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003933 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003934 sp<Camera3OutputStreamInterface> outputStream =
3935 captureRequest->mOutputStreams.editItemAt(j);
3936 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003937
3938 // Prepare video buffers for high speed recording on the first video request.
3939 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3940 // Only try to prepare video stream on the first video request.
3941 mPrepareVideoStream = false;
3942
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003943 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3944 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003945 while (res == NOT_ENOUGH_DATA) {
3946 res = outputStream->prepareNextBuffer();
3947 }
3948 if (res != OK) {
3949 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3950 __FUNCTION__, strerror(-res), res);
3951 outputStream->cancelPrepare();
3952 }
3953 }
3954
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003955 std::vector<size_t> uniqueSurfaceIds;
3956 res = outputStream->getUniqueSurfaceIds(
3957 captureRequest->mOutputSurfaces[streamId],
3958 &uniqueSurfaceIds);
3959 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3960 if (res != OK && res != INVALID_OPERATION) {
3961 ALOGE("%s: failed to query stream %d unique surface IDs",
3962 __FUNCTION__, streamId);
3963 return res;
3964 }
3965 if (res == OK) {
3966 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3967 }
3968
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003969 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003970 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003971 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003972 return TIMED_OUT;
3973 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003974 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003975 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003976 buffer.stream = outputStream->asHalStream();
3977 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003978 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003979 buffer.acquire_fence = -1;
3980 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003981 // Mark the output stream as unpreparable to block clients from calling
3982 // 'prepare' after this request reaches CameraHal and before the respective
3983 // buffers are requested.
3984 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003985 } else {
3986 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3987 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003988 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003989 if (res != OK) {
3990 // Can't get output buffer from gralloc queue - this could be due to
3991 // abandoned queue or other consumer misbehavior, so not a fatal
3992 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003993 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003994 " %s (%d)", strerror(-res), res);
3995
3996 return TIMED_OUT;
3997 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003998 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003999
4000 {
4001 sp<Camera3Device> parent = mParent.promote();
4002 if (parent != nullptr) {
4003 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4004 for (const auto& settings : captureRequest->mSettingsList) {
4005 if ((streamCameraId.isEmpty() &&
4006 parent->getId() == settings.cameraId.c_str()) ||
4007 streamCameraId == settings.cameraId.c_str()) {
4008 outputStream->fireBufferRequestForFrameNumber(
4009 captureRequest->mResultExtras.frameNumber,
4010 settings.metadata);
4011 }
4012 }
4013 }
4014 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004015
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004016 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08004017 int32_t streamGroupId = outputStream->getHalStreamGroupId();
4018 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
4019 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
4020 } else if (!physicalCameraId.isEmpty()) {
4021 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004022 }
4023 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004024 }
4025 totalNumBuffers += halRequest->num_output_buffers;
4026
4027 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004028 // If this request list is for constrained high speed recording (not
4029 // preview), and the current request is not the last one in the batch,
4030 // do not send callback to the app.
4031 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004032 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004033 hasCallback = false;
4034 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004035 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004036 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004037 const camera_metadata_t* settings = halRequest->settings;
4038 bool shouldUnlockSettings = false;
4039 if (settings == nullptr) {
4040 shouldUnlockSettings = true;
4041 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4042 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004043 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4044 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004045 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004046 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4047 isStillCapture = true;
4048 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4049 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004050
Emilian Peevaf8416e2021-02-04 17:52:43 -08004051 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004052 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004053 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4054 isZslCapture = true;
4055 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004056 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004057 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004058 res = parent->registerInFlight(halRequest->frame_number,
4059 totalNumBuffers, captureRequest->mResultExtras,
4060 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004061 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004062 expectedDurationInfo.minDuration,
4063 expectedDurationInfo.maxDuration,
4064 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004065 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004066 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
4067 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004068 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004069 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004070 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4071 ", burstId = %" PRId32 ".",
4072 __FUNCTION__,
4073 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4074 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004075
4076 if (shouldUnlockSettings) {
4077 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4078 }
4079
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004080 if (res != OK) {
4081 SET_ERR("RequestThread: Unable to register new in-flight request:"
4082 " %s (%d)", strerror(-res), res);
4083 return INVALID_OPERATION;
4084 }
4085 }
4086
4087 return OK;
4088}
4089
Igor Murashkin1e479c02013-09-06 16:55:14 -07004090CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004091 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004092 Mutex::Autolock al(mLatestRequestMutex);
4093
4094 ALOGV("RequestThread::%s", __FUNCTION__);
4095
4096 return mLatestRequest;
4097}
4098
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004099bool Camera3Device::RequestThread::isStreamPending(
4100 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004101 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004102 Mutex::Autolock l(mRequestLock);
4103
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004104 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004105 if (!nextRequest.submitted) {
4106 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4107 if (stream == s) return true;
4108 }
4109 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004110 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004111 }
4112
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004113 for (const auto& request : mRequestQueue) {
4114 for (const auto& s : request->mOutputStreams) {
4115 if (stream == s) return true;
4116 }
4117 if (stream == request->mInputStream) return true;
4118 }
4119
4120 for (const auto& request : mRepeatingRequests) {
4121 for (const auto& s : request->mOutputStreams) {
4122 if (stream == s) return true;
4123 }
4124 if (stream == request->mInputStream) return true;
4125 }
4126
4127 return false;
4128}
Jianing Weicb0652e2014-03-12 18:29:36 -07004129
Emilian Peev40ead602017-09-26 15:46:36 +01004130bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4131 ATRACE_CALL();
4132 Mutex::Autolock l(mRequestLock);
4133
4134 for (const auto& nextRequest : mNextRequests) {
4135 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4136 if (s.first == streamId) {
4137 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4138 if (it != s.second.end()) {
4139 return true;
4140 }
4141 }
4142 }
4143 }
4144
4145 for (const auto& request : mRequestQueue) {
4146 for (const auto& s : request->mOutputSurfaces) {
4147 if (s.first == streamId) {
4148 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4149 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004150 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004151 }
4152 }
4153 }
4154 }
4155
4156 for (const auto& request : mRepeatingRequests) {
4157 for (const auto& s : request->mOutputSurfaces) {
4158 if (s.first == streamId) {
4159 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4160 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004161 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004162 }
4163 }
4164 }
4165 }
4166
4167 return false;
4168}
4169
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004170void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4171 if (!mUseHalBufManager) {
4172 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4173 return;
4174 }
4175
4176 Mutex::Autolock pl(mPauseLock);
4177 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004178 mInterface->signalPipelineDrain(streamIds);
4179 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004180 }
4181 // If request thread is still busy, wait until paused then notify HAL
4182 mNotifyPipelineDrain = true;
4183 mStreamIdsToBeDrained = streamIds;
4184}
4185
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004186void Camera3Device::RequestThread::resetPipelineDrain() {
4187 Mutex::Autolock pl(mPauseLock);
4188 mNotifyPipelineDrain = false;
4189 mStreamIdsToBeDrained.clear();
4190}
4191
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004192void Camera3Device::RequestThread::clearPreviousRequest() {
4193 Mutex::Autolock l(mRequestLock);
4194 mPrevRequest.clear();
4195}
4196
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004197status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4198 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4199 ATRACE_CALL();
4200 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004201 mRotateAndCropOverride = rotateAndCropValue;
4202 return OK;
4203}
4204
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004205status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4206 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4207 ATRACE_CALL();
4208 Mutex::Autolock l(mTriggerMutex);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004209 mAutoframingOverride = autoframingValue;
4210 return OK;
4211}
4212
Emilian Peeve23f1d92021-09-20 14:56:01 -07004213status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4214 ATRACE_CALL();
4215 Mutex::Autolock l(mTriggerMutex);
4216 mComposerOutput = composerSurfacePresent;
4217 return OK;
4218}
4219
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004220status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004221 ATRACE_CALL();
4222 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004223 if (muteMode != mCameraMute) {
4224 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004225 mCameraMuteChanged = true;
4226 }
4227 return OK;
4228}
4229
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004230status_t Camera3Device::RequestThread::setZoomOverride(int32_t zoomOverride) {
4231 ATRACE_CALL();
4232 Mutex::Autolock l(mTriggerMutex);
4233 mSettingsOverride = zoomOverride;
4234 return OK;
4235}
4236
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004237nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004238 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004239 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004240 return mExpectedInflightDuration > kMinInflightDuration ?
4241 mExpectedInflightDuration : kMinInflightDuration;
4242}
4243
Emilian Peevaebbe412018-01-15 13:53:24 +00004244void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004245 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004246 if ((request == nullptr) || (halRequest == nullptr)) {
4247 ALOGE("%s: Invalid request!", __FUNCTION__);
4248 return;
4249 }
4250
4251 if (halRequest->num_physcam_settings > 0) {
4252 if (halRequest->physcam_id != nullptr) {
4253 delete [] halRequest->physcam_id;
4254 halRequest->physcam_id = nullptr;
4255 }
4256 if (halRequest->physcam_settings != nullptr) {
4257 auto it = ++(request->mSettingsList.begin());
4258 size_t i = 0;
4259 for (; it != request->mSettingsList.end(); it++, i++) {
4260 it->metadata.unlock(halRequest->physcam_settings[i]);
4261 }
4262 delete [] halRequest->physcam_settings;
4263 halRequest->physcam_settings = nullptr;
4264 }
4265 }
4266}
4267
Ravneetaeb20dc2022-03-30 05:33:03 +00004268status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4269 Mutex::Autolock il(mInterfaceLock);
4270 Mutex::Autolock l(mLock);
4271
4272 if (mCameraServiceWatchdog != NULL) {
4273 mCameraServiceWatchdog->setEnabled(enabled);
4274 }
4275
4276 return OK;
4277}
4278
Shuzhen Wang16610a62022-12-15 22:38:07 -08004279void Camera3Device::setStreamUseCaseOverrides(
4280 const std::vector<int64_t>& useCaseOverrides) {
4281 Mutex::Autolock il(mInterfaceLock);
4282 Mutex::Autolock l(mLock);
4283 mStreamUseCaseOverrides = useCaseOverrides;
4284}
4285
4286void Camera3Device::clearStreamUseCaseOverrides() {
4287 Mutex::Autolock il(mInterfaceLock);
4288 Mutex::Autolock l(mLock);
4289 mStreamUseCaseOverrides.clear();
4290}
4291
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004292bool Camera3Device::hasDeviceError() {
4293 Mutex::Autolock il(mInterfaceLock);
4294 Mutex::Autolock l(mLock);
4295 return mStatus == STATUS_ERROR;
4296}
4297
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004298void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4299 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004300 return;
4301 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004302
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004303 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004304 // Skip the ones that have been submitted successfully.
4305 if (nextRequest.submitted) {
4306 continue;
4307 }
4308
4309 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004310 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4311 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004312
4313 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004314 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004315 }
4316
Emilian Peevaebbe412018-01-15 13:53:24 +00004317 cleanupPhysicalSettings(captureRequest, halRequest);
4318
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004319 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004320 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004321 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4322 }
4323
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004324 // No output buffer can be returned when using HAL buffer manager
4325 if (!mUseHalBufManager) {
4326 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4327 //Buffers that failed processing could still have
4328 //valid acquire fence.
4329 int acquireFence = (*outputBuffers)[i].acquire_fence;
4330 if (0 <= acquireFence) {
4331 close(acquireFence);
4332 outputBuffers->editItemAt(i).acquire_fence = -1;
4333 }
Emilian Peevf4816702020-04-03 15:44:51 -07004334 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004335 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4336 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004337 /*timestampIncreasing*/true, std::vector<size_t> (),
4338 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004339 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004340 }
4341
4342 if (sendRequestError) {
4343 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004344 sp<NotificationListener> listener = mListener.promote();
4345 if (listener != NULL) {
4346 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004347 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004348 captureRequest->mResultExtras);
4349 }
4350 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004351
4352 // Remove yet-to-be submitted inflight request from inflightMap
4353 {
4354 sp<Camera3Device> parent = mParent.promote();
4355 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004356 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004357 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4358 if (idx >= 0) {
4359 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4360 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4361 parent->removeInFlightMapEntryLocked(idx);
4362 }
4363 }
4364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004365 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004366
4367 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004368 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004369}
4370
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004371void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004372 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004373 // Optimized a bit for the simple steady-state case (single repeating
4374 // request), to avoid putting that request in the queue temporarily.
4375 Mutex::Autolock l(mRequestLock);
4376
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004377 assert(mNextRequests.empty());
4378
4379 NextRequest nextRequest;
4380 nextRequest.captureRequest = waitForNextRequestLocked();
4381 if (nextRequest.captureRequest == nullptr) {
4382 return;
4383 }
4384
Emilian Peevf4816702020-04-03 15:44:51 -07004385 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004386 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004387 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004388
4389 // Wait for additional requests
4390 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4391
4392 for (size_t i = 1; i < batchSize; i++) {
4393 NextRequest additionalRequest;
4394 additionalRequest.captureRequest = waitForNextRequestLocked();
4395 if (additionalRequest.captureRequest == nullptr) {
4396 break;
4397 }
4398
Emilian Peevf4816702020-04-03 15:44:51 -07004399 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004400 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004401 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004402 }
4403
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004404 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004405 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004406 mNextRequests.size(), batchSize);
4407 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004408 }
4409
4410 return;
4411}
4412
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004413void Camera3Device::RequestThread::setRequestClearing() {
4414 Mutex::Autolock l(mRequestLock);
4415 mRequestClearing = true;
4416}
4417
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004418sp<Camera3Device::CaptureRequest>
4419 Camera3Device::RequestThread::waitForNextRequestLocked() {
4420 status_t res;
4421 sp<CaptureRequest> nextRequest;
4422
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004423 while (mRequestQueue.empty()) {
4424 if (!mRepeatingRequests.empty()) {
4425 // Always atomically enqueue all requests in a repeating request
4426 // list. Guarantees a complete in-sequence set of captures to
4427 // application.
4428 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004429 if (mFirstRepeating) {
4430 mFirstRepeating = false;
4431 } else {
4432 for (auto& request : requests) {
4433 // For repeating requests, override timestamp request using
4434 // the time a request is inserted into the request queue,
4435 // because the original repeating request will have an old
4436 // fixed timestamp.
4437 request->mRequestTimeNs = systemTime();
4438 }
4439 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004440 RequestList::const_iterator firstRequest =
4441 requests.begin();
4442 nextRequest = *firstRequest;
4443 mRequestQueue.insert(mRequestQueue.end(),
4444 ++firstRequest,
4445 requests.end());
4446 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004447
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004448 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 break;
4451 }
4452
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004453 if (!mRequestClearing) {
4454 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4455 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004457 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4458 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004459 Mutex::Autolock pl(mPauseLock);
4460 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004461 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004462 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004463 if (mNotifyPipelineDrain) {
4464 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4465 mNotifyPipelineDrain = false;
4466 mStreamIdsToBeDrained.clear();
4467 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004468 // Let the tracker know
4469 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4470 if (statusTracker != 0) {
4471 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4472 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004473 sp<Camera3Device> parent = mParent.promote();
4474 if (parent != nullptr) {
4475 parent->mRequestBufferSM.onRequestThreadPaused();
4476 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004477 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004478 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 // Stop waiting for now and let thread management happen
4480 return NULL;
4481 }
4482 }
4483
4484 if (nextRequest == NULL) {
4485 // Don't have a repeating request already in hand, so queue
4486 // must have an entry now.
4487 RequestList::iterator firstRequest =
4488 mRequestQueue.begin();
4489 nextRequest = *firstRequest;
4490 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004491 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4492 sp<NotificationListener> listener = mListener.promote();
4493 if (listener != NULL) {
4494 listener->notifyRequestQueueEmpty();
4495 }
4496 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004497 }
4498
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004499 // In case we've been unpaused by setPaused clearing mDoPause, need to
4500 // update internal pause state (capture/setRepeatingRequest unpause
4501 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004502 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004503 if (mPaused) {
4504 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4505 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4506 if (statusTracker != 0) {
4507 statusTracker->markComponentActive(mStatusId);
4508 }
4509 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004510 mPaused = false;
4511
4512 // Check if we've reconfigured since last time, and reset the preview
4513 // request if so. Can't use 'NULL request == repeat' across configure calls.
4514 if (mReconfigured) {
4515 mPrevRequest.clear();
4516 mReconfigured = false;
4517 }
4518
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004519 if (nextRequest != NULL) {
4520 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004521 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4522 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004523
4524 // Since RequestThread::clear() removes buffers from the input stream,
4525 // get the right buffer here before unlocking mRequestLock
4526 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004527 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4528 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004529 if (res != OK) {
4530 // Can't get input buffer from gralloc queue - this could be due to
4531 // disconnected queue or other producer misbehavior, so not a fatal
4532 // error
4533 ALOGE("%s: Can't get input buffer, skipping request:"
4534 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004535
4536 sp<NotificationListener> listener = mListener.promote();
4537 if (listener != NULL) {
4538 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004539 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004540 nextRequest->mResultExtras);
4541 }
4542 return NULL;
4543 }
4544 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004545 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004546
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004547 return nextRequest;
4548}
4549
4550bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004551 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004552 status_t res;
4553 Mutex::Autolock l(mPauseLock);
4554 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004555 if (mPaused == false) {
4556 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004557 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004558 if (mNotifyPipelineDrain) {
4559 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4560 mNotifyPipelineDrain = false;
4561 mStreamIdsToBeDrained.clear();
4562 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004563 // Let the tracker know
4564 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4565 if (statusTracker != 0) {
4566 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4567 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004568 sp<Camera3Device> parent = mParent.promote();
4569 if (parent != nullptr) {
4570 parent->mRequestBufferSM.onRequestThreadPaused();
4571 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004572 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004573
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004574 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004575 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004576 return true;
4577 }
4578 }
4579 // We don't set mPaused to false here, because waitForNextRequest needs
4580 // to further manage the paused state in case of starvation.
4581 return false;
4582}
4583
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004584void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004585 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004586 // With work to do, mark thread as unpaused.
4587 // If paused by request (setPaused), don't resume, to avoid
4588 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004589 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004590 Mutex::Autolock p(mPauseLock);
4591 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004592 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4593 if (mPaused) {
4594 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4595 if (statusTracker != 0) {
4596 statusTracker->markComponentActive(mStatusId);
4597 }
4598 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004599 mPaused = false;
4600 }
4601}
4602
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004603void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4604 sp<Camera3Device> parent = mParent.promote();
4605 if (parent != NULL) {
4606 va_list args;
4607 va_start(args, fmt);
4608
4609 parent->setErrorStateV(fmt, args);
4610
4611 va_end(args);
4612 }
4613}
4614
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004615status_t Camera3Device::RequestThread::insertTriggers(
4616 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004617 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004618 Mutex::Autolock al(mTriggerMutex);
4619
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004620 sp<Camera3Device> parent = mParent.promote();
4621 if (parent == NULL) {
4622 CLOGE("RequestThread: Parent is gone");
4623 return DEAD_OBJECT;
4624 }
4625
Emilian Peevaebbe412018-01-15 13:53:24 +00004626 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004627 size_t count = mTriggerMap.size();
4628
4629 for (size_t i = 0; i < count; ++i) {
4630 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004631 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004632
4633 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4634 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4635 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004636 if (isAeTrigger) {
4637 request->mResultExtras.precaptureTriggerId = triggerId;
4638 mCurrentPreCaptureTriggerId = triggerId;
4639 } else {
4640 request->mResultExtras.afTriggerId = triggerId;
4641 mCurrentAfTriggerId = triggerId;
4642 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004643 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004644 }
4645
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004646 camera_metadata_entry entry = metadata.find(tag);
4647
4648 if (entry.count > 0) {
4649 /**
4650 * Already has an entry for this trigger in the request.
4651 * Rewrite it with our requested trigger value.
4652 */
4653 RequestTrigger oldTrigger = trigger;
4654
4655 oldTrigger.entryValue = entry.data.u8[0];
4656
4657 mTriggerReplacedMap.add(tag, oldTrigger);
4658 } else {
4659 /**
4660 * More typical, no trigger entry, so we just add it
4661 */
4662 mTriggerRemovedMap.add(tag, trigger);
4663 }
4664
4665 status_t res;
4666
4667 switch (trigger.getTagType()) {
4668 case TYPE_BYTE: {
4669 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4670 res = metadata.update(tag,
4671 &entryValue,
4672 /*count*/1);
4673 break;
4674 }
4675 case TYPE_INT32:
4676 res = metadata.update(tag,
4677 &trigger.entryValue,
4678 /*count*/1);
4679 break;
4680 default:
4681 ALOGE("%s: Type not supported: 0x%x",
4682 __FUNCTION__,
4683 trigger.getTagType());
4684 return INVALID_OPERATION;
4685 }
4686
4687 if (res != OK) {
4688 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4689 ", value %d", __FUNCTION__, trigger.getTagName(),
4690 trigger.entryValue);
4691 return res;
4692 }
4693
4694 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4695 trigger.getTagName(),
4696 trigger.entryValue);
4697 }
4698
4699 mTriggerMap.clear();
4700
4701 return count;
4702}
4703
4704status_t Camera3Device::RequestThread::removeTriggers(
4705 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004706 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004707 Mutex::Autolock al(mTriggerMutex);
4708
Emilian Peevaebbe412018-01-15 13:53:24 +00004709 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004710
4711 /**
4712 * Replace all old entries with their old values.
4713 */
4714 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4715 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4716
4717 status_t res;
4718
4719 uint32_t tag = trigger.metadataTag;
4720 switch (trigger.getTagType()) {
4721 case TYPE_BYTE: {
4722 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4723 res = metadata.update(tag,
4724 &entryValue,
4725 /*count*/1);
4726 break;
4727 }
4728 case TYPE_INT32:
4729 res = metadata.update(tag,
4730 &trigger.entryValue,
4731 /*count*/1);
4732 break;
4733 default:
4734 ALOGE("%s: Type not supported: 0x%x",
4735 __FUNCTION__,
4736 trigger.getTagType());
4737 return INVALID_OPERATION;
4738 }
4739
4740 if (res != OK) {
4741 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4742 ", trigger value %d", __FUNCTION__,
4743 trigger.getTagName(), trigger.entryValue);
4744 return res;
4745 }
4746 }
4747 mTriggerReplacedMap.clear();
4748
4749 /**
4750 * Remove all new entries.
4751 */
4752 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4753 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4754 status_t res = metadata.erase(trigger.metadataTag);
4755
4756 if (res != OK) {
4757 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4758 ", trigger value %d", __FUNCTION__,
4759 trigger.getTagName(), trigger.entryValue);
4760 return res;
4761 }
4762 }
4763 mTriggerRemovedMap.clear();
4764
4765 return OK;
4766}
4767
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004768status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004769 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004770 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004771 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004772 status_t res;
4773
Emilian Peevaebbe412018-01-15 13:53:24 +00004774 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004775
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004776 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004777 // exists
4778 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4779 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4780 if (afTrigger.count > 0 &&
4781 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4782 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004783 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004784 if (res != OK) return res;
4785 }
4786
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004787 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004788 // if none already exists
4789 camera_metadata_entry pcTrigger =
4790 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4791 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4792 if (pcTrigger.count > 0 &&
4793 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4794 pcId.count == 0) {
4795 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004796 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004797 if (res != OK) return res;
4798 }
4799
4800 return OK;
4801}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004802
Emilian Peevd865f0d2023-03-17 17:13:07 -07004803bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4804 ATRACE_CALL();
4805 Mutex::Autolock l(mTriggerMutex);
4806 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4807 this->mRotateAndCropOverride);
4808}
4809
4810bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4811 bool overrideToPortrait,
4812 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004813 ATRACE_CALL();
4814
Emilian Peevd865f0d2023-03-17 17:13:07 -07004815 if (overrideToPortrait) {
4816 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger18b30a72022-10-27 12:20:29 -07004817 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4818 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4819 &rotateAndCrop_u8, 1);
4820 return true;
4821 }
4822
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004823 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004824 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4825
4826 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4827 if (rotateAndCropEntry.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004828 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004829 return false;
4830 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004831 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004832 return true;
4833 }
4834 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004835 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4836 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004837 return true;
4838 }
4839 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004840
4841 return false;
4842}
4843
4844bool Camera3Device::overrideAutoframing(const sp<CaptureRequest> &request /*out*/,
4845 camera_metadata_enum_android_control_autoframing_t autoframingOverride) {
4846 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4847 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4848 if (autoframingEntry.count > 0) {
4849 if (autoframingEntry.data.u8[0] == autoframingOverride) {
4850 return false;
4851 } else {
4852 autoframingEntry.data.u8[0] = autoframingOverride;
4853 return true;
4854 }
4855 } else {
4856 uint8_t autoframing_u8 = autoframingOverride;
4857 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4858 &autoframing_u8, 1);
4859 return true;
4860 }
4861
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004862 return false;
4863}
4864
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004865bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4866 ATRACE_CALL();
4867
4868 if (request->mAutoframingAuto) {
4869 Mutex::Autolock l(mTriggerMutex);
Emilian Peevd865f0d2023-03-17 17:13:07 -07004870 return Camera3Device::overrideAutoframing(request, mAutoframingOverride);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004871 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004872
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004873 return false;
4874}
4875
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004876bool Camera3Device::RequestThread::overrideTestPattern(
4877 const sp<CaptureRequest> &request) {
4878 ATRACE_CALL();
4879
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004880 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004881
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004882 Mutex::Autolock l(mTriggerMutex);
4883
4884 bool changed = false;
4885
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004886 // For a multi-camera, the physical cameras support the same set of
4887 // test pattern modes as the logical camera.
4888 for (auto& settings : request->mSettingsList) {
4889 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004890
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004891 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4892 int32_t testPatternData[4] = {
4893 settings.mOriginalTestPatternData[0],
4894 settings.mOriginalTestPatternData[1],
4895 settings.mOriginalTestPatternData[2],
4896 settings.mOriginalTestPatternData[3]
4897 };
4898 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4899 testPatternMode = mCameraMute;
4900 testPatternData[0] = 0;
4901 testPatternData[1] = 0;
4902 testPatternData[2] = 0;
4903 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004904 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004905
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004906 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4907 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4908 if (testPatternEntry.count > 0) {
4909 if (testPatternEntry.data.i32[0] != testPatternMode) {
4910 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004911 changed = true;
4912 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004913 } else if (supportTestPatternModeKey) {
4914 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4915 &testPatternMode, 1);
4916 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004917 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004918
4919 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4920 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4921 if (testPatternColor.count >= 4) {
4922 for (size_t i = 0; i < 4; i++) {
4923 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4924 testPatternColor.data.i32[i] = testPatternData[i];
4925 changed = true;
4926 }
4927 }
4928 } else if (supportTestPatternDataKey) {
4929 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4930 testPatternData, 4);
4931 changed = true;
4932 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004933 }
4934
4935 return changed;
4936}
4937
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004938bool Camera3Device::RequestThread::overrideSettingsOverride(
4939 const sp<CaptureRequest> &request) {
4940 ATRACE_CALL();
4941
4942 if (!mSupportSettingsOverride) return false;
4943
4944 Mutex::Autolock l(mTriggerMutex);
4945
4946 // For a multi-camera, only override the logical camera's metadata.
4947 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4948 camera_metadata_entry entry = metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
4949 int32_t originalValue = request->mSettingsList.begin()->mOriginalSettingsOverride;
4950 if (mSettingsOverride != -1 &&
4951 (entry.count == 0 || entry.data.i32[0] != mSettingsOverride)) {
4952 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4953 &mSettingsOverride, 1);
4954 return true;
4955 } else if (mSettingsOverride == -1 &&
4956 (entry.count == 0 || entry.data.i32[0] != originalValue)) {
4957 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4958 &originalValue, 1);
4959 return true;
4960 }
4961
4962 return false;
4963}
4964
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004965status_t Camera3Device::RequestThread::setHalInterface(
4966 sp<HalInterface> newHalInterface) {
4967 if (newHalInterface.get() == nullptr) {
4968 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4969 return DEAD_OBJECT;
4970 }
4971
4972 mInterface = newHalInterface;
4973
4974 return OK;
4975}
4976
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004977/**
4978 * PreparerThread inner class methods
4979 */
4980
4981Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004982 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004983 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004984}
4985
4986Camera3Device::PreparerThread::~PreparerThread() {
4987 Thread::requestExitAndWait();
4988 if (mCurrentStream != nullptr) {
4989 mCurrentStream->cancelPrepare();
4990 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4991 mCurrentStream.clear();
4992 }
4993 clear();
4994}
4995
Ruben Brunkc78ac262015-08-13 17:58:46 -07004996status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004997 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004998 status_t res;
4999
5000 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005001 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005002
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005003 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004 if (res == OK) {
5005 // No preparation needed, fire listener right off
5006 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005007 if (listener != NULL) {
5008 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005009 }
5010 return OK;
5011 } else if (res != NOT_ENOUGH_DATA) {
5012 return res;
5013 }
5014
5015 // Need to prepare, start up thread if necessary
5016 if (!mActive) {
5017 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5018 // isn't running
5019 Thread::requestExitAndWait();
5020 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5021 if (res != OK) {
5022 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005023 if (listener != NULL) {
5024 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005025 }
5026 return res;
5027 }
5028 mCancelNow = false;
5029 mActive = true;
5030 ALOGV("%s: Preparer stream started", __FUNCTION__);
5031 }
5032
5033 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005034 mPendingStreams.push_back(
5035 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005036 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5037
5038 return OK;
5039}
5040
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005041void Camera3Device::PreparerThread::pause() {
5042 ATRACE_CALL();
5043
5044 Mutex::Autolock l(mLock);
5045
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005046 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
5047 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005048 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5049 int currentMaxCount = mCurrentMaxCount;
5050 mPendingStreams.clear();
5051 mCancelNow = true;
5052 while (mActive) {
5053 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5054 if (res == TIMED_OUT) {
5055 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5056 return;
5057 } else if (res != OK) {
5058 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5059 return;
5060 }
5061 }
5062
5063 //Check whether the prepare thread was able to complete the current
5064 //stream. In case work is still pending emplace it along with the rest
5065 //of the streams in the pending list.
5066 if (currentStream != nullptr) {
5067 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005068 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005069 }
5070 }
5071
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005072 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005073 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005074 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005075 }
5076}
5077
5078status_t Camera3Device::PreparerThread::resume() {
5079 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005080 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005081 status_t res;
5082
5083 Mutex::Autolock l(mLock);
5084 sp<NotificationListener> listener = mListener.promote();
5085
5086 if (mActive) {
5087 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5088 return NO_INIT;
5089 }
5090
5091 auto it = mPendingStreams.begin();
5092 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005093 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005094 if (res == OK) {
5095 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005096 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005097 }
5098 it = mPendingStreams.erase(it);
5099 } else if (res != NOT_ENOUGH_DATA) {
5100 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5101 res, strerror(-res));
5102 it = mPendingStreams.erase(it);
5103 } else {
5104 it++;
5105 }
5106 }
5107
5108 if (mPendingStreams.empty()) {
5109 return OK;
5110 }
5111
5112 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5113 if (res != OK) {
5114 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5115 __FUNCTION__, res, strerror(-res));
5116 return res;
5117 }
5118 mCancelNow = false;
5119 mActive = true;
5120 ALOGV("%s: Preparer stream started", __FUNCTION__);
5121
5122 return OK;
5123}
5124
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005125status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005126 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005127 Mutex::Autolock l(mLock);
5128
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005129 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005130 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005131 }
5132 mPendingStreams.clear();
5133 mCancelNow = true;
5134
5135 return OK;
5136}
5137
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005138void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005139 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005140 Mutex::Autolock l(mLock);
5141 mListener = listener;
5142}
5143
5144bool Camera3Device::PreparerThread::threadLoop() {
5145 status_t res;
5146 {
5147 Mutex::Autolock l(mLock);
5148 if (mCurrentStream == nullptr) {
5149 // End thread if done with work
5150 if (mPendingStreams.empty()) {
5151 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5152 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5153 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5154 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005155 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005156 return false;
5157 }
5158
5159 // Get next stream to prepare
5160 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005161 mCurrentMaxCount = std::get<0>(*it);
5162 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005163 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005164 mPendingStreams.erase(it);
5165 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5166 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5167 } else if (mCancelNow) {
5168 mCurrentStream->cancelPrepare();
5169 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5170 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5171 mCurrentStream.clear();
5172 mCancelNow = false;
5173 return true;
5174 }
5175 }
5176
5177 res = mCurrentStream->prepareNextBuffer();
5178 if (res == NOT_ENOUGH_DATA) return true;
5179 if (res != OK) {
5180 // Something bad happened; try to recover by cancelling prepare and
5181 // signalling listener anyway
5182 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5183 mCurrentStream->getId(), res, strerror(-res));
5184 mCurrentStream->cancelPrepare();
5185 }
5186
5187 // This stream has finished, notify listener
5188 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005189 sp<NotificationListener> listener = mListener.promote();
5190 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005191 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5192 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005193 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005194 }
5195
5196 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5197 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005198 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005199
5200 return true;
5201}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005202
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005203status_t Camera3Device::RequestBufferStateMachine::initialize(
5204 sp<camera3::StatusTracker> statusTracker) {
5205 if (statusTracker == nullptr) {
5206 ALOGE("%s: statusTracker is null", __FUNCTION__);
5207 return BAD_VALUE;
5208 }
5209
5210 std::lock_guard<std::mutex> lock(mLock);
5211 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005212 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005213 return OK;
5214}
5215
5216bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5217 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005218 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005219 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005220 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005221 return true;
5222 }
5223 return false;
5224}
5225
5226void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5227 std::lock_guard<std::mutex> lock(mLock);
5228 if (!mRequestBufferOngoing) {
5229 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5230 return;
5231 }
5232 mRequestBufferOngoing = false;
5233 if (mStatus == RB_STATUS_PENDING_STOP) {
5234 checkSwitchToStopLocked();
5235 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005236 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005237}
5238
5239void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5240 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005241 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005242 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005243 return;
5244}
5245
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005246void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005247 std::lock_guard<std::mutex> lock(mLock);
5248 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005249 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5250 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005251 mInflightMapEmpty = false;
5252 if (mStatus == RB_STATUS_STOPPED) {
5253 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005254 }
5255 return;
5256}
5257
5258void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5259 std::lock_guard<std::mutex> lock(mLock);
5260 mRequestThreadPaused = true;
5261 if (mStatus == RB_STATUS_PENDING_STOP) {
5262 checkSwitchToStopLocked();
5263 }
5264 return;
5265}
5266
5267void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5268 std::lock_guard<std::mutex> lock(mLock);
5269 mInflightMapEmpty = true;
5270 if (mStatus == RB_STATUS_PENDING_STOP) {
5271 checkSwitchToStopLocked();
5272 }
5273 return;
5274}
5275
5276void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5277 std::lock_guard<std::mutex> lock(mLock);
5278 if (!checkSwitchToStopLocked()) {
5279 mStatus = RB_STATUS_PENDING_STOP;
5280 }
5281 return;
5282}
5283
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005284bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5285 std::lock_guard<std::mutex> lock(mLock);
5286 if (mRequestBufferOngoing) {
5287 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5288 __FUNCTION__);
5289 return false;
5290 }
5291 mSwitchedToOffline = true;
5292 mInflightMapEmpty = true;
5293 mRequestThreadPaused = true;
5294 mStatus = RB_STATUS_STOPPED;
5295 return true;
5296}
5297
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005298void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5299 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5300 if (statusTracker != nullptr) {
5301 if (active) {
5302 statusTracker->markComponentActive(mRequestBufferStatusId);
5303 } else {
5304 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5305 }
5306 }
5307}
5308
5309bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5310 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5311 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005312 return true;
5313 }
5314 return false;
5315}
5316
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005317bool Camera3Device::startRequestBuffer() {
5318 return mRequestBufferSM.startRequestBuffer();
5319}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005320
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005321void Camera3Device::endRequestBuffer() {
5322 mRequestBufferSM.endRequestBuffer();
5323}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005324
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005325nsecs_t Camera3Device::getWaitDuration() {
5326 return kBaseGetBufferWait + getExpectedInFlightDuration();
5327}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005328
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005329void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5330 mInterface->getInflightBufferKeys(out);
5331}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005332
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005333void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5334 mInterface->getInflightRequestBufferKeys(out);
5335}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005336
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005337std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5338 std::vector<sp<Camera3StreamInterface>> ret;
5339 bool hasInputStream = mInputStream != nullptr;
5340 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5341 if (hasInputStream) {
5342 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005343 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005344 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5345 ret.push_back(mOutputStreams[i]);
5346 }
5347 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5348 ret.push_back(mDeletedStreams[i]);
5349 }
5350 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005351}
5352
Emilian Peevcc0b7952020-01-07 13:54:47 -08005353void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5354 ATRACE_CALL();
5355
5356 if (offlineStreamIds == nullptr) {
5357 return;
5358 }
5359
5360 Mutex::Autolock il(mInterfaceLock);
5361
5362 auto streamIds = mOutputStreams.getStreamIds();
5363 bool hasInputStream = mInputStream != nullptr;
5364 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5365 offlineStreamIds->push_back(mInputStream->getId());
5366 }
5367
5368 for (const auto & streamId : streamIds) {
5369 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5370 // Streams that use the camera buffer manager are currently not supported in
5371 // offline mode
5372 if (stream->getOfflineProcessingSupport() &&
5373 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5374 offlineStreamIds->push_back(streamId);
5375 }
5376 }
5377}
5378
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005379status_t Camera3Device::setRotateAndCropAutoBehavior(
5380 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5381 ATRACE_CALL();
5382 Mutex::Autolock il(mInterfaceLock);
5383 Mutex::Autolock l(mLock);
5384 if (mRequestThread == nullptr) {
5385 return INVALID_OPERATION;
5386 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005387 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5388 return BAD_VALUE;
5389 }
5390 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005391 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5392}
5393
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005394status_t Camera3Device::setAutoframingAutoBehavior(
5395 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5396 ATRACE_CALL();
5397 Mutex::Autolock il(mInterfaceLock);
5398 Mutex::Autolock l(mLock);
5399 if (mRequestThread == nullptr) {
5400 return INVALID_OPERATION;
5401 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005402 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
5403 return BAD_VALUE;
5404 }
5405 mAutoframingOverride = autoframingValue;
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005406 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5407}
5408
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005409bool Camera3Device::supportsCameraMute() {
5410 Mutex::Autolock il(mInterfaceLock);
5411 Mutex::Autolock l(mLock);
5412
5413 return mSupportCameraMute;
5414}
5415
5416status_t Camera3Device::setCameraMute(bool enabled) {
5417 ATRACE_CALL();
5418 Mutex::Autolock il(mInterfaceLock);
5419 Mutex::Autolock l(mLock);
5420
5421 if (mRequestThread == nullptr || !mSupportCameraMute) {
5422 return INVALID_OPERATION;
5423 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005424 int32_t muteMode =
5425 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5426 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5427 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5428 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005429}
5430
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005431bool Camera3Device::supportsZoomOverride() {
5432 Mutex::Autolock il(mInterfaceLock);
5433 Mutex::Autolock l(mLock);
5434
5435 return mSupportZoomOverride;
5436}
5437
5438status_t Camera3Device::setZoomOverride(int32_t zoomOverride) {
5439 ATRACE_CALL();
5440 Mutex::Autolock il(mInterfaceLock);
5441 Mutex::Autolock l(mLock);
5442
5443 if (mRequestThread == nullptr || !mSupportZoomOverride) {
5444 return INVALID_OPERATION;
5445 }
5446
5447 return mRequestThread->setZoomOverride(zoomOverride);
5448}
5449
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005450status_t Camera3Device::injectCamera(const String8& injectedCamId,
5451 sp<CameraProviderManager> manager) {
5452 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5453 ATRACE_CALL();
5454 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005455 // When the camera device is active, injectCamera() and stopInjection() will call
5456 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5457 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5458 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5459 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5460 // waitUntilStateThenRelock().
5461 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005462
5463 status_t res = NO_ERROR;
5464 if (mInjectionMethods->isInjecting()) {
5465 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5466 return OK;
5467 } else {
5468 res = mInjectionMethods->stopInjection();
5469 if (res != OK) {
5470 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5471 __FUNCTION__, res);
5472 return res;
5473 }
5474 }
5475 }
5476
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005477 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005478 if (res != OK) {
5479 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5480 __FUNCTION__, res);
5481 return res;
5482 }
5483
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005484 // When the second display of android is cast to the remote device, and the opened camera is
5485 // also cast to the second display, in this case, because the camera has configured the streams
5486 // at this time, we can directly call injectCamera() to replace the internal camera with
5487 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005488 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5489 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5490
5491 camera3::camera_stream_configuration injectionConfig;
5492 std::vector<uint32_t> injectionBufferSizes;
5493 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5494 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5495 || injectionBufferSizes.size() <= 0) {
5496 ALOGE("Failed to inject camera due to abandoned configuration! "
5497 "mOperatingMode: %d injectionConfig.num_streams: %d "
5498 "injectionBufferSizes.size(): %zu", mOperatingMode,
5499 injectionConfig.num_streams, injectionBufferSizes.size());
5500 return DEAD_OBJECT;
5501 }
5502
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005503 res = mInjectionMethods->injectCamera(
5504 injectionConfig, injectionBufferSizes);
5505 if (res != OK) {
5506 ALOGE("Can't finish inject camera process!");
5507 return res;
5508 }
5509 }
5510
5511 return OK;
5512}
5513
5514status_t Camera3Device::stopInjection() {
5515 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5516 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005517 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005518 return mInjectionMethods->stopInjection();
5519}
5520
Shuzhen Wang16610a62022-12-15 22:38:07 -08005521void Camera3Device::overrideStreamUseCaseLocked() {
5522 if (mStreamUseCaseOverrides.size() == 0) {
5523 return;
5524 }
5525
5526 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5527 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5528 // Refer to CameraService::printHelp for details.
5529 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5530 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5531 outputStreamsIndices[i] = i;
5532 }
5533
5534 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5535 [&](int a, int b) -> bool {
5536
5537 auto formatScore = [](int format) {
5538 switch (format) {
5539 case HAL_PIXEL_FORMAT_BLOB:
5540 return 4;
5541 case HAL_PIXEL_FORMAT_RAW16:
5542 case HAL_PIXEL_FORMAT_RAW10:
5543 case HAL_PIXEL_FORMAT_RAW12:
5544 return 3;
5545 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5546 return 2;
5547 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5548 return 1;
5549 default:
5550 return 0;
5551 }
5552 };
5553
5554 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5555 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5556 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5557 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5558 if (sizeA > sizeB ||
5559 (sizeA == sizeB && formatAScore >= formatBScore)) {
5560 return true;
5561 } else {
5562 return false;
5563 }
5564 });
5565
5566 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5567 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5568 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5569 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5570 }
5571}
5572
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005573}; // namespace android