blob: 153e99936676dfba88f9538721cc9bfd26437b78 [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),
Austin Borgerc8099762023-01-12 17:08:46 -0800106 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800107{
108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
112Camera3Device::~Camera3Device()
113{
114 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700116 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800117}
118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800120 return mId;
121}
122
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123status_t Camera3Device::initializeCommonLocked() {
124
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 /** Start up status tracker thread */
126 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800127 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700128 if (res != OK) {
129 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
130 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700132 mStatusTracker.clear();
133 return res;
134 }
135
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700136 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700137 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700138
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700139 if (mUseHalBufManager) {
140 res = mRequestBufferSM.initialize(mStatusTracker);
141 if (res != OK) {
142 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
143 strerror(-res), res);
144 mInterface->close();
145 mStatusTracker.clear();
146 return res;
147 }
148 }
149
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800150 /** Create buffer manager */
151 mBufferManager = new Camera3BufferManager();
152
153 Vector<int32_t> sessionParamKeys;
154 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
155 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
156 if (sessionKeysEntry.count > 0) {
157 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
158 }
159
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700160 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
161 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
162 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
163 if (availableTestPatternModes.data.i32[i] ==
164 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
165 mSupportCameraMute = true;
166 mSupportTestPatternSolidColor = true;
167 break;
168 } else if (availableTestPatternModes.data.i32[i] ==
169 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
170 mSupportCameraMute = true;
171 mSupportTestPatternSolidColor = false;
172 }
173 }
174
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700175 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800176 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700177 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger18b30a72022-10-27 12:20:29 -0700178 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800179 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800180 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700181 SET_ERR_L("Unable to start request queue thread: %s (%d)",
182 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800183 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800184 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800185 return res;
186 }
187
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700188 mPreparerThread = new PreparerThread();
189
Ruben Brunk183f0562015-08-12 12:55:02 -0700190 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800191 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400192 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700193 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700194 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800195 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800196
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800198 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800199 camera_metadata_entry timestampSource =
200 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
201 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
202 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800203 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800204 }
205
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700206 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100207 camera_metadata_entry partialResultsCount =
208 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
209 if (partialResultsCount.count > 0) {
210 mNumPartialResults = partialResultsCount.data.i32[0];
211 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700212 }
213
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800214 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
215 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700216 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700217 if (res != OK) {
218 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
219 return res;
220 }
221 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800222
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800223 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800224 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800225
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800226 if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700227 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
228 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
229 }
230
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800231 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
232 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
233 }
234
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800235 // Hidl/AidlCamera3DeviceInjectionMethods
236 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800237
Ravneetaeb20dc2022-03-30 05:33:03 +0000238 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800239 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700240 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
241 if (res != OK) {
242 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
243 strerror(-res), res);
244 return res;
245 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000246
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800247 return OK;
248}
249
250status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700251 return disconnectImpl();
252}
253
254status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800255 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700256 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800257
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700258 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700259 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800261 Mutex::Autolock il(mInterfaceLock);
262 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
263 {
264 Mutex::Autolock l(mLock);
265 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700266
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000267 if (mRequestThread != NULL) {
268 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
269 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800270 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000271 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800272 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000273 } else {
274 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
275 if (res != OK) {
276 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
277 maxExpectedDuration);
278 // Continue to close device even in case of error
279 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800280 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000282 // Signal to request thread that we're not expecting any
283 // more requests. This will be true since once we're in
284 // disconnect and we've cleared off the request queue, the
285 // request thread can't receive any new requests through
286 // binder calls - since disconnect holds
287 // mBinderSerialization lock.
288 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700289 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800290
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800291 if (mStatus == STATUS_ERROR) {
292 CLOGE("Shutting down in an error state");
293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800295 if (mStatusTracker != NULL) {
296 mStatusTracker->requestExit();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 if (mRequestThread != NULL) {
300 mRequestThread->requestExit();
301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800303 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
304 for (size_t i = 0; i < mOutputStreams.size(); i++) {
305 streams.push_back(mOutputStreams[i]);
306 }
307 if (mInputStream != nullptr) {
308 streams.push_back(mInputStream);
309 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800312 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
313 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
315 // HAL may be in a bad state, so waiting for request thread
316 // (which may be stuck in the HAL processCaptureRequest call)
317 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800318 // give up mInterfaceLock here and then lock it again. Could this lead
319 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 mRequestThread->join();
321 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700322 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 Mutex::Autolock il(mInterfaceLock);
324 if (mStatusTracker != NULL) {
325 mStatusTracker->join();
326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800328 if (mInjectionMethods->isInjecting()) {
329 mInjectionMethods->stopInjection();
330 }
331
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800332 HalInterface* interface;
333 {
334 Mutex::Autolock l(mLock);
335 mRequestThread.clear();
336 Mutex::Autolock stLock(mTrackerLock);
337 mStatusTracker.clear();
338 interface = mInterface.get();
339 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700340
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800341 // Call close without internal mutex held, as the HAL close may need to
342 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000343 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700344
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800345 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800346
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800347 {
348 Mutex::Autolock l(mLock);
349 mInterface->clear();
350 mOutputStreams.clear();
351 mInputStream.clear();
352 mDeletedStreams.clear();
353 mBufferManager.clear();
354 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
355 }
356
357 for (auto& weakStream : streams) {
358 sp<Camera3StreamInterface> stream = weakStream.promote();
359 if (stream != nullptr) {
360 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
361 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
362 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700363 }
364 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700365 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000366
367 if (mCameraServiceWatchdog != NULL) {
368 mCameraServiceWatchdog->requestExit();
369 mCameraServiceWatchdog.clear();
370 }
371
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700372 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800373}
374
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700375// For dumping/debugging only -
376// try to acquire a lock a few times, eventually give up to proceed with
377// debug/dump operations
378bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
379 bool gotLock = false;
380 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
381 if (lock.tryLock() == NO_ERROR) {
382 gotLock = true;
383 break;
384 } else {
385 usleep(kDumpSleepDuration);
386 }
387 }
388 return gotLock;
389}
390
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800391nsecs_t Camera3Device::getMonoToBoottimeOffset() {
392 // try three times to get the clock offset, choose the one
393 // with the minimum gap in measurements.
394 const int tries = 3;
395 nsecs_t bestGap, measured;
396 for (int i = 0; i < tries; ++i) {
397 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
398 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
399 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
400 const nsecs_t gap = tmono2 - tmono;
401 if (i == 0 || gap < bestGap) {
402 bestGap = gap;
403 measured = tbase - ((tmono + tmono2) >> 1);
404 }
405 }
406 return measured;
407}
408
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800409ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
410 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411 // Get max jpeg size (area-wise) for default sensor pixel mode
412 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800413 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800414 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700415 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
416 // not ultra high res sensor
417 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800418 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700419 /*isUltraHighResolution*/true);
420 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800421 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
422 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700423 return BAD_VALUE;
424 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700425 bool useMaxSensorPixelModeThreshold = false;
426 if (uhrMaxJpegResolution.width != 0 &&
427 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
428 // Use the ultra high res max jpeg size and max jpeg buffer size
429 useMaxSensorPixelModeThreshold = true;
430 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700431
Zhijun Hef7da0962014-04-24 13:27:56 -0700432 // Get max jpeg buffer size
433 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700435 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800436 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
437 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700438 return BAD_VALUE;
439 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700440 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700441
442 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
443 if (useMaxSensorPixelModeThreshold) {
444 maxJpegBufferSize =
445 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
446 maxDefaultJpegResolution, maxJpegBufferSize);
447 chosenMaxJpegResolution = uhrMaxJpegResolution;
448 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800449 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700450
451 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700452 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700453 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800454 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
455 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700456 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800457 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
458 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700459 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700460 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700461 return jpegBufferSize;
462}
463
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800464ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700465 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800466 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700467 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800468 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
469 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700470 return BAD_VALUE;
471 }
472 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
473 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
474 return maxBytesForPointCloud;
475}
476
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800477ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
478 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800479 const int PER_CONFIGURATION_SIZE = 3;
480 const int WIDTH_OFFSET = 0;
481 const int HEIGHT_OFFSET = 1;
482 const int SIZE_OFFSET = 2;
483 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800484 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800485 camera3::SessionConfigurationUtils::getAppropriateModeTag(
486 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
487 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800488 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800489 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
491 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800492 return BAD_VALUE;
493 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700494
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800495 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
496 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
497 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
498 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
499 }
500 }
501
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
503 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800504 return BAD_VALUE;
505}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700506
Jing Mikec7f9b132023-03-12 11:12:04 +0800507status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800508 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700509
510 // Try to lock, but continue in case of failure (to avoid blocking in
511 // deadlocks)
512 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
513 bool gotLock = tryLockSpinRightRound(mLock);
514
515 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800516 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
517 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700518 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800519 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
520 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700521
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800522 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700523
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800524 String16 templatesOption("-t");
525 int n = args.size();
526 for (int i = 0; i < n; i++) {
527 if (args[i] == templatesOption) {
528 dumpTemplates = true;
529 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000530 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700531 if (i + 1 < n) {
532 String8 monitorTags = String8(args[i + 1]);
533 if (monitorTags == "off") {
534 mTagMonitor.disableMonitoring();
535 } else {
536 mTagMonitor.parseTagsToMonitor(monitorTags);
537 }
538 } else {
539 mTagMonitor.disableMonitoring();
540 }
541 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800542 }
543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800544 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800545
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800546 const char *status =
547 mStatus == STATUS_ERROR ? "ERROR" :
548 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700549 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
550 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800551 mStatus == STATUS_ACTIVE ? "ACTIVE" :
552 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700555 if (mStatus == STATUS_ERROR) {
556 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
557 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800558 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800559 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000560 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
561 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
562 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800564
565 if (mInputStream != NULL) {
566 write(fd, lines.string(), lines.size());
567 mInputStream->dump(fd, args);
568 } else {
569 lines.appendFormat(" No input stream.\n");
570 write(fd, lines.string(), lines.size());
571 }
572 for (size_t i = 0; i < mOutputStreams.size(); i++) {
573 mOutputStreams[i]->dump(fd,args);
574 }
575
Zhijun He431503c2016-03-07 17:30:16 -0800576 if (mBufferManager != NULL) {
577 lines = String8(" Camera3 Buffer Manager:\n");
578 write(fd, lines.string(), lines.size());
579 mBufferManager->dump(fd, args);
580 }
Zhijun He125684a2015-12-26 15:07:30 -0800581
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700582 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700583 if (mInFlightLock.try_lock()) {
584 if (mInFlightMap.size() == 0) {
585 lines.append(" None\n");
586 } else {
587 for (size_t i = 0; i < mInFlightMap.size(); i++) {
588 InFlightRequest r = mInFlightMap.valueAt(i);
589 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
590 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
591 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
592 r.numBuffersLeft);
593 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700594 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700595 mInFlightLock.unlock();
596 } else {
597 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700598 }
599 write(fd, lines.string(), lines.size());
600
Shuzhen Wang686f6442017-06-20 16:16:04 -0700601 if (mRequestThread != NULL) {
602 mRequestThread->dumpCaptureRequestLatency(fd,
603 " ProcessCaptureRequest latency histogram:");
604 }
605
Igor Murashkin1e479c02013-09-06 16:55:14 -0700606 {
607 lines = String8(" Last request sent:\n");
608 write(fd, lines.string(), lines.size());
609
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700610 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700611 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
612 }
613
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800614 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700615 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800616 "TEMPLATE_PREVIEW",
617 "TEMPLATE_STILL_CAPTURE",
618 "TEMPLATE_VIDEO_RECORD",
619 "TEMPLATE_VIDEO_SNAPSHOT",
620 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800621 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800622 };
623
Emilian Peevf4816702020-04-03 15:44:51 -0700624 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 camera_metadata_t *templateRequest = nullptr;
626 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700627 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800628 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800629 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800630 lines.append(" Not supported\n");
631 write(fd, lines.string(), lines.size());
632 } else {
633 write(fd, lines.string(), lines.size());
634 dump_indented_camera_metadata(templateRequest,
635 fd, /*verbosity*/2, /*indentation*/8);
636 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800637 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 }
639 }
640
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700641 mTagMonitor.dumpMonitoredMetadata(fd);
642
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800643 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800644 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800645 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800646 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800648
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700649 if (gotLock) mLock.unlock();
650 if (gotInterfaceLock) mInterfaceLock.unlock();
651
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800652 return OK;
653}
654
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700655status_t Camera3Device::startWatchingTags(const String8 &tags) {
656 mTagMonitor.parseTagsToMonitor(tags);
657 return OK;
658}
659
660status_t Camera3Device::stopWatchingTags() {
661 mTagMonitor.disableMonitoring();
662 return OK;
663}
664
665status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
666 mTagMonitor.getLatestMonitoredTagEvents(out);
667 return OK;
668}
669
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800670const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800671 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
673 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700674 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 mStatus == STATUS_ERROR ?
676 "when in error state" : "before init");
677 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700678 if (physicalId.isEmpty()) {
679 return mDeviceInfo;
680 } else {
681 std::string id(physicalId.c_str());
682 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
683 return mPhysicalDeviceInfoMap.at(id);
684 } else {
685 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
686 return mDeviceInfo;
687 }
688 }
689}
690
691const CameraMetadata& Camera3Device::info() const {
692 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800693 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800694}
695
Jianing Wei90e59c92014-03-12 18:29:36 -0700696status_t Camera3Device::checkStatusOkToCaptureLocked() {
697 switch (mStatus) {
698 case STATUS_ERROR:
699 CLOGE("Device has encountered a serious error");
700 return INVALID_OPERATION;
701 case STATUS_UNINITIALIZED:
702 CLOGE("Device not initialized");
703 return INVALID_OPERATION;
704 case STATUS_UNCONFIGURED:
705 case STATUS_CONFIGURED:
706 case STATUS_ACTIVE:
707 // OK
708 break;
709 default:
710 SET_ERR_L("Unexpected status: %d", mStatus);
711 return INVALID_OPERATION;
712 }
713 return OK;
714}
715
716status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000717 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700718 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700719 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700720 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700721 if (requestList == NULL) {
722 CLOGE("requestList cannot be NULL.");
723 return BAD_VALUE;
724 }
725
Jianing Weicb0652e2014-03-12 18:29:36 -0700726 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000727 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700728 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
729 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
730 ++metadataIt, ++surfaceMapIt) {
731 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700732 if (newRequest == 0) {
733 CLOGE("Can't create capture request");
734 return BAD_VALUE;
735 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700736
Shuzhen Wang9d066012016-09-30 11:30:20 -0700737 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700738 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700739
Jianing Weicb0652e2014-03-12 18:29:36 -0700740 // Setup burst Id and request Id
741 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800742 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
743 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700744 CLOGE("RequestID does not exist in metadata");
745 return BAD_VALUE;
746 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800747 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700748
Jianing Wei90e59c92014-03-12 18:29:36 -0700749 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700750
751 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700752 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
754 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
755 return BAD_VALUE;
756 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700757
758 // Setup batch size if this is a high speed video recording request.
759 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
760 auto firstRequest = requestList->begin();
761 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
762 if (outputStream->isVideoStream()) {
763 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800764 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700765 break;
766 }
767 }
768 }
769
Jianing Wei90e59c92014-03-12 18:29:36 -0700770 return OK;
771}
772
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800773status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800774 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800775
Emilian Peevaebbe412018-01-15 13:53:24 +0000776 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000778 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700779
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800780 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700781}
782
Emilian Peevaebbe412018-01-15 13:53:24 +0000783void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 std::list<const SurfaceMap>& surfaceMaps,
785 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000786 PhysicalCameraSettingsList requestList;
787 requestList.push_back({std::string(getId().string()), request});
788 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700789
790 SurfaceMap surfaceMap;
791 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
792 // With no surface list passed in, stream and surface will have 1-to-1
793 // mapping. So the surface index is 0 for each stream in the surfaceMap.
794 for (size_t i = 0; i < streams.count; i++) {
795 surfaceMap[streams.data.i32[i]].push_back(0);
796 }
797 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800798}
799
Jianing Wei90e59c92014-03-12 18:29:36 -0700800status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000801 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700802 const std::list<const SurfaceMap> &surfaceMaps,
803 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700804 /*out*/
805 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700806 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700807 nsecs_t requestTimeNs = systemTime();
808
Jianing Wei90e59c92014-03-12 18:29:36 -0700809 Mutex::Autolock il(mInterfaceLock);
810 Mutex::Autolock l(mLock);
811
812 status_t res = checkStatusOkToCaptureLocked();
813 if (res != OK) {
814 // error logged by previous call
815 return res;
816 }
817
818 RequestList requestList;
819
Shuzhen Wang0129d522016-10-30 22:43:41 -0700820 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700821 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700822 if (res != OK) {
823 // error logged by previous call
824 return res;
825 }
826
827 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700828 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700829 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700830 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 }
832
833 if (res == OK) {
834 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
835 if (res != OK) {
836 SET_ERR_L("Can't transition to active in %f seconds!",
837 kActiveTimeout/1e9);
838 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800839 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700840 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 } else {
842 CLOGE("Cannot queue request. Impossible.");
843 return BAD_VALUE;
844 }
845
846 return res;
847}
848
Emilian Peevaebbe412018-01-15 13:53:24 +0000849status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700850 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700851 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700852 ATRACE_CALL();
853
Emilian Peevaebbe412018-01-15 13:53:24 +0000854 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700855}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Jianing Weicb0652e2014-03-12 18:29:36 -0700857status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
858 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800859 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000863 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700864
Emilian Peevaebbe412018-01-15 13:53:24 +0000865 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700866 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800867}
868
Emilian Peevaebbe412018-01-15 13:53:24 +0000869status_t Camera3Device::setStreamingRequestList(
870 const List<const PhysicalCameraSettingsList> &requestsList,
871 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700872 ATRACE_CALL();
873
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700875}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876
877sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800879 status_t res;
880
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700881 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800882 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
883 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000884 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700885 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700886 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700888 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800889 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700890 } else if (mStatus == STATUS_UNCONFIGURED) {
891 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700892 CLOGE("No streams configured");
893 return NULL;
894 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800895 }
896
Shuzhen Wang0129d522016-10-30 22:43:41 -0700897 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800898 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800899}
900
Jianing Weicb0652e2014-03-12 18:29:36 -0700901status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700903 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800904 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800905
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800906 switch (mStatus) {
907 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700908 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800909 return INVALID_OPERATION;
910 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700911 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800912 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700913 case STATUS_UNCONFIGURED:
914 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800915 case STATUS_ACTIVE:
916 // OK
917 break;
918 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700919 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800920 return INVALID_OPERATION;
921 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800922 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700923
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700924 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925}
926
927status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
928 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700929 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800930
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700931 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800932}
933
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800935 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700936 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700937 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700938 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700939 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800940 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
941 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942
943 status_t res;
944 bool wasActive = false;
945
946 switch (mStatus) {
947 case STATUS_ERROR:
948 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
949 return INVALID_OPERATION;
950 case STATUS_UNINITIALIZED:
951 ALOGE("%s: Device not initialized", __FUNCTION__);
952 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700953 case STATUS_UNCONFIGURED:
954 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955 // OK
956 break;
957 case STATUS_ACTIVE:
958 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700959 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700960 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700961 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700962 return res;
963 }
964 wasActive = true;
965 break;
966 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700967 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700968 return INVALID_OPERATION;
969 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700970 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700971
972 if (mInputStream != 0) {
973 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
974 return INVALID_OPERATION;
975 }
976
977 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
978 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700979 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700980
981 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800982 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700983
984 *id = mNextStreamId++;
985
986 // Continue captures if active at start
987 if (wasActive) {
988 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100989 // Reuse current operating mode and session parameters for new stream config
990 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700991 if (res != OK) {
992 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
993 __FUNCTION__, mNextStreamId, strerror(-res), res);
994 return res;
995 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700996 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700997 }
998
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800999 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001000 return OK;
1001}
1002
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001003status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001004 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001005 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001006 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001007 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1008 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001009 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001010 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001011 ATRACE_CALL();
1012
1013 if (consumer == nullptr) {
1014 ALOGE("%s: consumer must not be null", __FUNCTION__);
1015 return BAD_VALUE;
1016 }
1017
1018 std::vector<sp<Surface>> consumers;
1019 consumers.push_back(consumer);
1020
1021 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001022 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001023 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001024 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001025}
1026
1027static bool isRawFormat(int format) {
1028 switch (format) {
1029 case HAL_PIXEL_FORMAT_RAW16:
1030 case HAL_PIXEL_FORMAT_RAW12:
1031 case HAL_PIXEL_FORMAT_RAW10:
1032 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1033 return true;
1034 default:
1035 return false;
1036 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001037}
1038
1039status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1040 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001041 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001042 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001043 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001044 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001045 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001046 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001047
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001048 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001049 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001051 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001052 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001053 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001054 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001055 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001056 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001057 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1058 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001059
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 status_t res;
1061 bool wasActive = false;
1062
1063 switch (mStatus) {
1064 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001065 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066 return INVALID_OPERATION;
1067 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001068 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001070 case STATUS_UNCONFIGURED:
1071 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001072 // OK
1073 break;
1074 case STATUS_ACTIVE:
1075 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001076 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001078 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 return res;
1080 }
1081 wasActive = true;
1082 break;
1083 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001084 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001085 return INVALID_OPERATION;
1086 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001087 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088
1089 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001090
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 if (consumers.size() == 0 && !hasDeferredConsumer) {
1092 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1093 return BAD_VALUE;
1094 }
Zhijun He5d677d12016-05-29 16:52:39 -07001095
Shuzhen Wang0129d522016-10-30 22:43:41 -07001096 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001097 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1098 return BAD_VALUE;
1099 }
1100
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001101 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1102 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1103 // be found in only one sensor pixel mode.
1104 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1105 return BAD_VALUE;
1106 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001107 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001108 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001109 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001110 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001111 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001112 if (blobBufferSize <= 0) {
1113 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1114 return BAD_VALUE;
1115 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001116 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1117 blobBufferSize = width * height;
1118 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001119 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001120 if (blobBufferSize <= 0) {
1121 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1122 return BAD_VALUE;
1123 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001124 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001125 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001126 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001127 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001128 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001129 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001130 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001131 bool maxResolution =
1132 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1133 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001134 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1135 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001136 if (rawOpaqueBufferSize <= 0) {
1137 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1138 return BAD_VALUE;
1139 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001140 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001141 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001142 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001143 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001144 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001145 } else if (isShared) {
1146 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1147 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001148 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001149 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001150 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001151 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001152 newStream = new Camera3OutputStream(mNextStreamId,
1153 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001154 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001155 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001156 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001157 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001158 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001159 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001160 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001161 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001162 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163 }
Emilian Peev40ead602017-09-26 15:46:36 +01001164
1165 size_t consumerCount = consumers.size();
1166 for (size_t i = 0; i < consumerCount; i++) {
1167 int id = newStream->getSurfaceId(consumers[i]);
1168 if (id < 0) {
1169 SET_ERR_L("Invalid surface id");
1170 return BAD_VALUE;
1171 }
1172 if (surfaceIds != nullptr) {
1173 surfaceIds->push_back(id);
1174 }
1175 }
1176
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001177 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178
Emilian Peev08dd2452017-04-06 16:55:14 +01001179 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001180
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001181 newStream->setImageDumpMask(mImageDumpMask);
1182
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183 res = mOutputStreams.add(mNextStreamId, newStream);
1184 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001185 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 return res;
1187 }
1188
Shuzhen Wang316781a2020-08-18 18:11:01 -07001189 mSessionStatsBuilder.addStream(mNextStreamId);
1190
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001192 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193
1194 // Continue captures if active at start
1195 if (wasActive) {
1196 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001197 // Reuse current operating mode and session parameters for new stream config
1198 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1201 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return res;
1203 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001204 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001206 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001208}
1209
Emilian Peev710c1422017-08-30 11:19:38 +01001210status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001212 if (nullptr == streamInfo) {
1213 return BAD_VALUE;
1214 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001217
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 switch (mStatus) {
1219 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001220 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 return INVALID_OPERATION;
1222 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001223 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 case STATUS_UNCONFIGURED:
1226 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 case STATUS_ACTIVE:
1228 // OK
1229 break;
1230 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
1233 }
1234
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001235 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1236 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001237 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001238 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 }
1240
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001241 streamInfo->width = stream->getWidth();
1242 streamInfo->height = stream->getHeight();
1243 streamInfo->format = stream->getFormat();
1244 streamInfo->dataSpace = stream->getDataSpace();
1245 streamInfo->formatOverridden = stream->isFormatOverridden();
1246 streamInfo->originalFormat = stream->getOriginalFormat();
1247 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1248 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001249 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001250 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252}
1253
1254status_t Camera3Device::setStreamTransform(int id,
1255 int transform) {
1256 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001257 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 switch (mStatus) {
1261 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
1264 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001265 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 case STATUS_UNCONFIGURED:
1268 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 case STATUS_ACTIVE:
1270 // OK
1271 break;
1272 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001273 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return INVALID_OPERATION;
1275 }
1276
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001277 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1278 if (stream == nullptr) {
1279 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 return BAD_VALUE;
1281 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001282 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001283}
1284
1285status_t Camera3Device::deleteStream(int id) {
1286 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 Mutex::Autolock l(mLock);
1289 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001290
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001291 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001292
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 // CameraDevice semantics require device to already be idle before
1294 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001295 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001296 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001297 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 }
1299
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001300 if (mStatus == STATUS_ERROR) {
1301 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1302 __FUNCTION__, mId.string());
1303 return -EBUSY;
1304 }
1305
Igor Murashkin2fba5842013-04-22 14:03:54 -07001306 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001307 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 if (mInputStream != NULL && id == mInputStream->getId()) {
1309 deletedStream = mInputStream;
1310 mInputStream.clear();
1311 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001312 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001313 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001314 return BAD_VALUE;
1315 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001316 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001317 }
1318
1319 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001320 if (stream != nullptr) {
1321 deletedStream = stream;
1322 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001323 }
1324
1325 // Free up the stream endpoint so that it can be used by some other stream
1326 res = deletedStream->disconnect();
1327 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001328 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329 // fall through since we want to still list the stream as deleted.
1330 }
1331 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001332 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001333
1334 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001335}
1336
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001337status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001338 ATRACE_CALL();
1339 ALOGV("%s: E", __FUNCTION__);
1340
1341 Mutex::Autolock il(mInterfaceLock);
1342 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001343
Emilian Peev811d2952018-05-25 11:08:40 +01001344 // In case the client doesn't include any session parameter, try a
1345 // speculative configuration using the values from the last cached
1346 // default request.
1347 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001348 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001349 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1350 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1351 mLastTemplateId);
1352 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1353 operatingMode);
1354 }
1355
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001356 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1357}
1358
1359status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1360 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001361 //Filter out any incoming session parameters
1362 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001363 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1364 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001365 CameraMetadata filteredParams(availableSessionKeys.count);
1366 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1367 filteredParams.getAndLock());
1368 set_camera_metadata_vendor_id(meta, mVendorTagId);
1369 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001370 if (availableSessionKeys.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001371 bool rotateAndCropSessionKey = false;
1372 bool autoframingSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001373 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1374 camera_metadata_ro_entry entry = params.find(
1375 availableSessionKeys.data.i32[i]);
1376 if (entry.count > 0) {
1377 filteredParams.update(entry);
1378 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07001379 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1380 rotateAndCropSessionKey = true;
1381 }
1382 if (ANDROID_CONTROL_AUTOFRAMING == availableSessionKeys.data.i32[i]) {
1383 autoframingSessionKey = true;
1384 }
1385 }
1386
1387 if (rotateAndCropSessionKey || autoframingSessionKey) {
1388 sp<CaptureRequest> request = new CaptureRequest();
1389 PhysicalCameraSettings settingsList;
1390 settingsList.metadata = filteredParams;
1391 request->mSettingsList.push_back(settingsList);
1392
1393 if (rotateAndCropSessionKey) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001394 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1395 if (rotateAndCropEntry.count > 0 &&
1396 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1397 request->mRotateAndCropAuto = true;
1398 } else {
1399 request->mRotateAndCropAuto = false;
1400 }
1401
1402 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1403 }
1404
1405 if (autoframingSessionKey) {
1406 auto autoframingEntry = filteredParams.find(ANDROID_CONTROL_AUTOFRAMING);
1407 if (autoframingEntry.count > 0 &&
1408 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
1409 overrideAutoframing(request, mAutoframingOverride);
1410 }
1411 }
1412
1413 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001414 }
1415 }
1416
1417 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001418}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001419
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001420status_t Camera3Device::getInputBufferProducer(
1421 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001422 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001423 Mutex::Autolock il(mInterfaceLock);
1424 Mutex::Autolock l(mLock);
1425
1426 if (producer == NULL) {
1427 return BAD_VALUE;
1428 } else if (mInputStream == NULL) {
1429 return INVALID_OPERATION;
1430 }
1431
1432 return mInputStream->getInputBufferProducer(producer);
1433}
1434
Emilian Peevf4816702020-04-03 15:44:51 -07001435status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001436 CameraMetadata *request) {
1437 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001438 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001439
Emilian Peevf4816702020-04-03 15:44:51 -07001440 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001441 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001442 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001443 return BAD_VALUE;
1444 }
1445
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001446 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001448 {
1449 Mutex::Autolock l(mLock);
1450 switch (mStatus) {
1451 case STATUS_ERROR:
1452 CLOGE("Device has encountered a serious error");
1453 return INVALID_OPERATION;
1454 case STATUS_UNINITIALIZED:
1455 CLOGE("Device is not initialized!");
1456 return INVALID_OPERATION;
1457 case STATUS_UNCONFIGURED:
1458 case STATUS_CONFIGURED:
1459 case STATUS_ACTIVE:
1460 // OK
1461 break;
1462 default:
1463 SET_ERR_L("Unexpected status: %d", mStatus);
1464 return INVALID_OPERATION;
1465 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001466
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001467 if (!mRequestTemplateCache[templateId].isEmpty()) {
1468 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001469 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001470 return OK;
1471 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001472 }
1473
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001474 camera_metadata_t *rawRequest;
1475 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001476 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001477
1478 {
1479 Mutex::Autolock l(mLock);
1480 if (res == BAD_VALUE) {
1481 ALOGI("%s: template %d is not supported on this camera device",
1482 __FUNCTION__, templateId);
1483 return res;
1484 } else if (res != OK) {
1485 CLOGE("Unable to construct request template %d: %s (%d)",
1486 templateId, strerror(-res), res);
1487 return res;
1488 }
1489
1490 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1491 mRequestTemplateCache[templateId].acquire(rawRequest);
1492
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001493 // Override the template request with zoomRatioMapper
1494 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1495 &mRequestTemplateCache[templateId]);
1496 if (res != OK) {
1497 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1498 templateId, strerror(-res), res);
1499 return res;
1500 }
1501
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001502 // Fill in JPEG_QUALITY if not available
1503 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1504 static const uint8_t kDefaultJpegQuality = 95;
1505 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1506 &kDefaultJpegQuality, 1);
1507 }
1508
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001509 // Fill in AUTOFRAMING if not available
1510 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1511 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1512 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1513 &kDefaultAutoframingMode, 1);
1514 }
1515
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001516 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001517 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001518 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519 return OK;
1520}
1521
1522status_t Camera3Device::waitUntilDrained() {
1523 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001525 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001528 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001529}
1530
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001531status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 switch (mStatus) {
1533 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001534 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 ALOGV("%s: Already idle", __FUNCTION__);
1536 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 case STATUS_CONFIGURED:
1538 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 case STATUS_ERROR:
1540 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 break;
1543 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001544 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return INVALID_OPERATION;
1546 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001547 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1548 maxExpectedDuration);
1549 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001550 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001551 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001552 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1553 res);
1554 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 return res;
1556}
1557
Ruben Brunk183f0562015-08-12 12:55:02 -07001558void Camera3Device::internalUpdateStatusLocked(Status status) {
1559 mStatus = status;
1560 mRecentStatusUpdates.add(mStatus);
1561 mStatusChanged.broadcast();
1562}
1563
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001565status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001566 if (mRequestThread.get() != nullptr) {
1567 mRequestThread->setPaused(true);
1568 } else {
1569 return NO_INIT;
1570 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001572 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1573 maxExpectedDuration);
1574 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001576 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001577 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001578 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 }
1580
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001581 return res;
1582}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584// Resume after internalPauseAndWaitLocked
1585status_t Camera3Device::internalResumeLocked() {
1586 status_t res;
1587
1588 mRequestThread->setPaused(false);
1589
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001590 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1591 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1593 if (res != OK) {
1594 SET_ERR_L("Can't transition to active in %f seconds!",
1595 kActiveTimeout/1e9);
1596 }
1597 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599}
1600
Ruben Brunk183f0562015-08-12 12:55:02 -07001601status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001603
1604 size_t startIndex = 0;
1605 if (mStatusWaiters == 0) {
1606 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1607 // this status list
1608 mRecentStatusUpdates.clear();
1609 } else {
1610 // If other threads are waiting on updates to this status list, set the position of the
1611 // first element that this list will check rather than clearing the list.
1612 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 }
1614
Ruben Brunk183f0562015-08-12 12:55:02 -07001615 mStatusWaiters++;
1616
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001617 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001618 if (!active && mUseHalBufManager) {
1619 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001620 if (mStatus == STATUS_ACTIVE) {
1621 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001622 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001623 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001624 mRequestBufferSM.onWaitUntilIdle();
1625 }
1626
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001628 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001629 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001630 if (active == (mStatus == STATUS_ACTIVE)) {
1631 // Desired state is current
1632 break;
1633 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001634
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001635 nsecs_t timeElapsed = systemTime() - startTime;
1636 nsecs_t timeToWait = timeout - timeElapsed;
1637 if (timeToWait <= 0) {
1638 // Thread woke up spuriously but has timed out since.
1639 // Force out of loop with TIMED_OUT result.
1640 res = TIMED_OUT;
1641 break;
1642 }
1643 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001644 if (res != OK) break;
1645
Ruben Brunk183f0562015-08-12 12:55:02 -07001646 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1647 // transitions.
1648 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1649 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1650 __FUNCTION__);
1651
1652 // Encountered desired state since we began waiting
1653 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001654 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1655 stateSeen = true;
1656 break;
1657 }
1658 }
1659 } while (!stateSeen);
1660
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001661 if (signalPipelineDrain) {
1662 mRequestThread->resetPipelineDrain();
1663 }
1664
Ruben Brunk183f0562015-08-12 12:55:02 -07001665 mStatusWaiters--;
1666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667 return res;
1668}
1669
1670
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001671status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001673 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001675 if (listener != NULL && mListener != NULL) {
1676 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1677 }
1678 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001679 mRequestThread->setNotificationListener(listener);
1680 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001681
1682 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001683}
1684
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001685bool Camera3Device::willNotify3A() {
1686 return false;
1687}
1688
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001690 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001691 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001693 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001694 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1695 if (st == std::cv_status::timeout) {
1696 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001697 }
1698 }
1699 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700}
1701
Jianing Weicb0652e2014-03-12 18:29:36 -07001702status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001703 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001704 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001705
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001706 if (mResultQueue.empty()) {
1707 return NOT_ENOUGH_DATA;
1708 }
1709
Jianing Weicb0652e2014-03-12 18:29:36 -07001710 if (frame == NULL) {
1711 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1712 return BAD_VALUE;
1713 }
1714
1715 CaptureResult &result = *(mResultQueue.begin());
1716 frame->mResultExtras = result.mResultExtras;
1717 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001718 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001719 mResultQueue.erase(mResultQueue.begin());
1720
1721 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001722}
1723
1724status_t Camera3Device::triggerAutofocus(uint32_t id) {
1725 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001728 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1729 // Mix-in this trigger into the next request and only the next request.
1730 RequestTrigger trigger[] = {
1731 {
1732 ANDROID_CONTROL_AF_TRIGGER,
1733 ANDROID_CONTROL_AF_TRIGGER_START
1734 },
1735 {
1736 ANDROID_CONTROL_AF_TRIGGER_ID,
1737 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001738 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001739 };
1740
1741 return mRequestThread->queueTrigger(trigger,
1742 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
1745status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1746 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001747 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001749 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1750 // Mix-in this trigger into the next request and only the next request.
1751 RequestTrigger trigger[] = {
1752 {
1753 ANDROID_CONTROL_AF_TRIGGER,
1754 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1755 },
1756 {
1757 ANDROID_CONTROL_AF_TRIGGER_ID,
1758 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001759 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001760 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001762 return mRequestThread->queueTrigger(trigger,
1763 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001764}
1765
1766status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1767 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001769
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001770 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1771 // Mix-in this trigger into the next request and only the next request.
1772 RequestTrigger trigger[] = {
1773 {
1774 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1775 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1776 },
1777 {
1778 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1779 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001780 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001781 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001782
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001783 return mRequestThread->queueTrigger(trigger,
1784 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001785}
1786
Jianing Weicb0652e2014-03-12 18:29:36 -07001787status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001788 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001789 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001790 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001791
Zhijun He7ef20392014-04-21 16:04:17 -07001792 {
1793 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001794
1795 // b/116514106 "disconnect()" can get called twice for the same device. The
1796 // camera device will not be initialized during the second run.
1797 if (mStatus == STATUS_UNINITIALIZED) {
1798 return OK;
1799 }
1800
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001801 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001802
1803 // Stop session and stream counter
1804 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001805 }
1806
Ravneetdbd5b242022-03-02 07:22:46 +00001807 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001808 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001809 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1810 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1811
1812 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001813}
1814
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001815status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001816 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1817}
1818
1819status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001820 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001821 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001822 Mutex::Autolock il(mInterfaceLock);
1823 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001824
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001825 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1826 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001827 CLOGE("Stream %d does not exist", streamId);
1828 return BAD_VALUE;
1829 }
1830
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001831 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001832 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001833 return BAD_VALUE;
1834 }
1835
1836 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001837 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001838 return BAD_VALUE;
1839 }
1840
Ruben Brunkc78ac262015-08-13 17:58:46 -07001841 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001842}
1843
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001844status_t Camera3Device::tearDown(int streamId) {
1845 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001846 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001847 Mutex::Autolock il(mInterfaceLock);
1848 Mutex::Autolock l(mLock);
1849
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001850 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1851 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001852 CLOGE("Stream %d does not exist", streamId);
1853 return BAD_VALUE;
1854 }
1855
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001856 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1857 CLOGE("Stream %d is a target of a in-progress request", streamId);
1858 return BAD_VALUE;
1859 }
1860
1861 return stream->tearDown();
1862}
1863
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001864status_t Camera3Device::addBufferListenerForStream(int streamId,
1865 wp<Camera3StreamBufferListener> listener) {
1866 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001867 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001868 Mutex::Autolock il(mInterfaceLock);
1869 Mutex::Autolock l(mLock);
1870
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001871 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1872 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001873 CLOGE("Stream %d does not exist", streamId);
1874 return BAD_VALUE;
1875 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001876 stream->addBufferListener(listener);
1877
1878 return OK;
1879}
1880
Austin Borger4a870a32022-02-25 01:48:41 +00001881float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1882 camera_metadata_entry minDurations =
1883 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1884 for (size_t i = 0; i < minDurations.count; i += 4) {
1885 if (minDurations.data.i64[i] == stream->getFormat()
1886 && minDurations.data.i64[i+1] == stream->getWidth()
1887 && minDurations.data.i64[i+2] == stream->getHeight()) {
1888 int64_t minFrameDuration = minDurations.data.i64[i+3];
1889 return 1e9f / minFrameDuration;
1890 }
1891 }
1892 return 0.0f;
1893}
1894
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001896 * Methods called by subclasses
1897 */
1898
1899void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001900 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001901 std::vector<int> streamIds;
1902 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001903 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001904
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001905 {
1906 // Need mLock to safely update state and synchronize to current
1907 // state of methods in flight.
1908 Mutex::Autolock l(mLock);
1909 // We can get various system-idle notices from the status tracker
1910 // while starting up. Only care about them if we've actually sent
1911 // in some requests recently.
1912 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1913 return;
1914 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001915 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1916 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001917 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918
1919 // Skip notifying listener if we're doing some user-transparent
1920 // state changes
1921 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001922
Austin Borger4a870a32022-02-25 01:48:41 +00001923 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1924 auto stream = mOutputStreams[i];
1925 if (stream.get() == nullptr) continue;
1926
1927 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1928 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1929
1930 // Populate stream statistics in case of Idle
1931 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001932 streamIds.push_back(stream->getId());
1933 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1934 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001935 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001936 if (camera3Stream != nullptr) {
1937 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001938 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001939 }
1940 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001941 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001942 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001943 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001944 stream->getDynamicRangeProfile(), streamUseCase,
1945 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001946 }
1947 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001949
1950 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001952 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001953 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001954 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001955 status_t res = OK;
1956 if (listener != nullptr) {
1957 if (idle) {
1958 // Get session stats from the builder, and notify the listener.
1959 int64_t requestCount, resultErrorCount;
1960 bool deviceError;
1961 std::map<int, StreamStats> streamStatsMap;
1962 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1963 &deviceError, &streamStatsMap);
1964 for (size_t i = 0; i < streamIds.size(); i++) {
1965 int streamId = streamIds[i];
1966 auto stats = streamStatsMap.find(streamId);
1967 if (stats != streamStatsMap.end()) {
1968 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1969 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1970 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1971 streamStats[i].mHistogramType =
1972 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1973 streamStats[i].mHistogramBins.assign(
1974 stats->second.mCaptureLatencyBins.begin(),
1975 stats->second.mCaptureLatencyBins.end());
1976 streamStats[i].mHistogramCounts.assign(
1977 stats->second.mCaptureLatencyHistogram.begin(),
1978 stats->second.mCaptureLatencyHistogram.end());
1979 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001980 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001981 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1982 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001983 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001984 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001985 }
1986 if (res != OK) {
1987 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1988 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001989 }
1990}
1991
Shuzhen Wang758c2152017-01-10 18:26:18 -08001992status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001993 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001994 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001995 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1996 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001997
1998 if (surfaceIds == nullptr) {
1999 return BAD_VALUE;
2000 }
2001
Zhijun He5d677d12016-05-29 16:52:39 -07002002 Mutex::Autolock il(mInterfaceLock);
2003 Mutex::Autolock l(mLock);
2004
Shuzhen Wang758c2152017-01-10 18:26:18 -08002005 if (consumers.size() == 0) {
2006 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002007 return BAD_VALUE;
2008 }
2009
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002010 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2011 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002012 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002013 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002014 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002015
2016 // isConsumerConfigurationDeferred will be off after setConsumers
2017 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002018 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002019 if (res != OK) {
2020 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2021 return res;
2022 }
2023
Emilian Peev40ead602017-09-26 15:46:36 +01002024 for (auto &consumer : consumers) {
2025 int id = stream->getSurfaceId(consumer);
2026 if (id < 0) {
2027 CLOGE("Invalid surface id!");
2028 return BAD_VALUE;
2029 }
2030 surfaceIds->push_back(id);
2031 }
2032
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002033 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002034 if (!stream->isConfiguring()) {
2035 CLOGE("Stream %d was already fully configured.", streamId);
2036 return INVALID_OPERATION;
2037 }
Zhijun He5d677d12016-05-29 16:52:39 -07002038
Shuzhen Wang0129d522016-10-30 22:43:41 -07002039 res = stream->finishConfiguration();
2040 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002041 // If finishConfiguration fails due to abandoned surface, do not set
2042 // device to error state.
2043 bool isSurfaceAbandoned =
2044 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2045 if (!isSurfaceAbandoned) {
2046 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2047 stream->getId(), strerror(-res), res);
2048 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002049 return res;
2050 }
Zhijun He5d677d12016-05-29 16:52:39 -07002051 }
2052
2053 return OK;
2054}
2055
Emilian Peev40ead602017-09-26 15:46:36 +01002056status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2057 const std::vector<OutputStreamInfo> &outputInfo,
2058 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2059 Mutex::Autolock il(mInterfaceLock);
2060 Mutex::Autolock l(mLock);
2061
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002062 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2063 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002064 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002065 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002066 }
2067
2068 for (const auto &it : removedSurfaceIds) {
2069 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2070 CLOGE("Shared surface still part of a pending request!");
2071 return -EBUSY;
2072 }
2073 }
2074
Emilian Peev40ead602017-09-26 15:46:36 +01002075 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2076 if (res != OK) {
2077 CLOGE("Stream %d failed to update stream (error %d %s) ",
2078 streamId, res, strerror(-res));
2079 if (res == UNKNOWN_ERROR) {
2080 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2081 __FUNCTION__);
2082 }
2083 return res;
2084 }
2085
2086 return res;
2087}
2088
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002089status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2090 Mutex::Autolock il(mInterfaceLock);
2091 Mutex::Autolock l(mLock);
2092
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002093 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2094 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002095 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2096 return BAD_VALUE;
2097 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002098
2099 if (dropping) {
2100 mSessionStatsBuilder.stopCounter(streamId);
2101 } else {
2102 mSessionStatsBuilder.startCounter(streamId);
2103 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002104 return stream->dropBuffers(dropping);
2105}
2106
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002107/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002108 * Camera3Device private methods
2109 */
2110
2111sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002112 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002115 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002116 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117
2118 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002119 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120 if (inputStreams.count > 0) {
2121 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002122 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002123 CLOGE("Request references unknown input stream %d",
2124 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 return NULL;
2126 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002127
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002129 SET_ERR_L("%s: input stream %d is not configured!",
2130 __FUNCTION__, mInputStream->getId());
2131 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002133 // Check if stream prepare is blocking requests.
2134 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002135 CLOGE("Request references an input stream that's being prepared!");
2136 return NULL;
2137 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
2139 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002140 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002141 }
2142
2143 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002144 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002146 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002147 return NULL;
2148 }
2149
2150 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002151 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2152 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002153 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002154 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155 return NULL;
2156 }
Zhijun He5d677d12016-05-29 16:52:39 -07002157 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002158 auto iter = surfaceMap.find(streams.data.i32[i]);
2159 if (iter != surfaceMap.end()) {
2160 const std::vector<size_t>& surfaces = iter->second;
2161 for (const auto& surface : surfaces) {
2162 if (stream->isConsumerConfigurationDeferred(surface)) {
2163 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2164 "due to deferred consumer", stream->getId(), surface);
2165 return NULL;
2166 }
2167 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002168 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002169 }
2170
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002171 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002172 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2173 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002174 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002175 // Check if stream prepare is blocking requests.
2176 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002177 CLOGE("Request references an output stream that's being prepared!");
2178 return NULL;
2179 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002180
2181 newRequest->mOutputStreams.push(stream);
2182 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002183 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002184 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002186 auto rotateAndCropEntry =
2187 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2188 if (rotateAndCropEntry.count > 0 &&
2189 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2190 newRequest->mRotateAndCropAuto = true;
2191 } else {
2192 newRequest->mRotateAndCropAuto = false;
2193 }
2194
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002195 auto autoframingEntry =
2196 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2197 if (autoframingEntry.count > 0 &&
2198 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2199 newRequest->mAutoframingAuto = true;
2200 } else {
2201 newRequest->mAutoframingAuto = false;
2202 }
2203
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002204 auto zoomRatioEntry =
2205 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2206 if (zoomRatioEntry.count > 0 &&
2207 zoomRatioEntry.data.f[0] == 1.0f) {
2208 newRequest->mZoomRatioIs1x = true;
2209 } else {
2210 newRequest->mZoomRatioIs1x = false;
2211 }
2212
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002213 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002214 for (auto& settings : newRequest->mSettingsList) {
2215 auto testPatternModeEntry =
2216 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2217 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2218 testPatternModeEntry.data.i32[0] :
2219 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002220
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002221 auto testPatternDataEntry =
2222 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2223 if (testPatternDataEntry.count >= 4) {
2224 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2225 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2226 } else {
2227 settings.mOriginalTestPatternData[0] = 0;
2228 settings.mOriginalTestPatternData[1] = 0;
2229 settings.mOriginalTestPatternData[2] = 0;
2230 settings.mOriginalTestPatternData[3] = 0;
2231 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002232 }
2233 }
2234
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002236}
2237
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002238void Camera3Device::cancelStreamsConfigurationLocked() {
2239 int res = OK;
2240 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2241 res = mInputStream->cancelConfiguration();
2242 if (res != OK) {
2243 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2244 mInputStream->getId(), strerror(-res), res);
2245 }
2246 }
2247
2248 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002249 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002250 if (outputStream->isConfiguring()) {
2251 res = outputStream->cancelConfiguration();
2252 if (res != OK) {
2253 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2254 outputStream->getId(), strerror(-res), res);
2255 }
2256 }
2257 }
2258
2259 // Return state to that at start of call, so that future configures
2260 // properly clean things up
2261 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2262 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002263
2264 res = mPreparerThread->resume();
2265 if (res != OK) {
2266 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2267 }
2268}
2269
Emilian Peev0d0191e2020-04-21 17:01:18 -07002270bool Camera3Device::checkAbandonedStreamsLocked() {
2271 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2272 return true;
2273 }
2274
2275 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2276 auto stream = mOutputStreams[i];
2277 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2278 return true;
2279 }
2280 }
2281
2282 return false;
2283}
2284
Emilian Peev3bead5f2020-05-28 17:29:08 -07002285bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002286 ATRACE_CALL();
2287 bool ret = false;
2288
Shuzhen Wang316781a2020-08-18 18:11:01 -07002289 nsecs_t startTime = systemTime();
2290
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002291 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002292 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2293
2294 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002295 if (checkAbandonedStreamsLocked()) {
2296 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2297 __FUNCTION__);
2298 return true;
2299 }
2300
Emilian Peev3bead5f2020-05-28 17:29:08 -07002301 status_t rc = NO_ERROR;
2302 bool markClientActive = false;
2303 if (mStatus == STATUS_ACTIVE) {
2304 markClientActive = true;
2305 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002306
2307 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2308 }
2309
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002310 if (rc == NO_ERROR) {
2311 mNeedConfig = true;
2312 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2313 if (rc == NO_ERROR) {
2314 ret = true;
2315 mPauseStateNotify = false;
2316 //Moving to active state while holding 'mLock' is important.
2317 //There could be pending calls to 'create-/deleteStream' which
2318 //will trigger another stream configuration while the already
2319 //present streams end up with outstanding buffers that will
2320 //not get drained.
2321 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002322 } else if (rc == DEAD_OBJECT) {
2323 // DEAD_OBJECT can be returned if either the consumer surface is
2324 // abandoned, or the HAL has died.
2325 // - If the HAL has died, configureStreamsLocked call will set
2326 // device to error state,
2327 // - If surface is abandoned, we should not set device to error
2328 // state.
2329 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002330 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002331 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002332 }
2333 } else {
2334 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2335 }
2336
Austin Borger74fca042022-05-23 12:41:21 -07002337 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002338 ns2ms(systemTime() - startTime));
2339
Emilian Peev3bead5f2020-05-28 17:29:08 -07002340 if (markClientActive) {
2341 mStatusTracker->markComponentActive(clientStatusId);
2342 }
2343
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002344 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002345}
2346
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002347status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002348 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002349 ATRACE_CALL();
2350 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002351
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002352 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002353 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 return INVALID_OPERATION;
2355 }
2356
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002357 if (operatingMode < 0) {
2358 CLOGE("Invalid operating mode: %d", operatingMode);
2359 return BAD_VALUE;
2360 }
2361
2362 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002363 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002364
2365 if (mOperatingMode != operatingMode) {
2366 mNeedConfig = true;
2367 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2368 mOperatingMode = operatingMode;
2369 }
2370
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002371 // Reset min expected duration when session is reconfigured.
2372 mMinExpectedDuration = 0;
2373
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002374 // In case called from configureStreams, abort queued input buffers not belonging to
2375 // any pending requests.
2376 if (mInputStream != NULL && notifyRequestThread) {
2377 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002378 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002379 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002380 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002381 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002382 if (res != OK) {
2383 // Exhausted acquiring all input buffers.
2384 break;
2385 }
2386
Emilian Peevf4816702020-04-03 15:44:51 -07002387 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002388 res = mInputStream->returnInputBuffer(inputBuffer);
2389 if (res != OK) {
2390 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2391 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2392 }
2393 }
2394 }
2395
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002396 if (!mNeedConfig) {
2397 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2398 return OK;
2399 }
2400
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002401 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002402 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002403 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2404 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002405 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002406 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002407 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002408 }
2409
Shuzhen Wang16610a62022-12-15 22:38:07 -08002410 // Override stream use case based on "adb shell command"
2411 overrideStreamUseCaseLocked();
2412
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002414 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002415
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002416 mPreparerThread->pause();
2417
Emilian Peevf4816702020-04-03 15:44:51 -07002418 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002419 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002421 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422
Emilian Peevf4816702020-04-03 15:44:51 -07002423 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002425 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002426
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002427
2428 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002429 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002430 inputStream = mInputStream->startConfiguration();
2431 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002432 CLOGE("Can't start input stream configuration");
2433 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434 return INVALID_OPERATION;
2435 }
2436 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002437
2438 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002439 }
2440
Shuzhen Wang99080502021-03-07 21:08:20 -08002441 mGroupIdPhysicalCameraMap.clear();
Emilian Peevd865f0d2023-03-17 17:13:07 -07002442 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002443 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002444
2445 // Don't configure bidi streams twice, nor add them twice to the list
2446 if (mOutputStreams[i].get() ==
2447 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2448
2449 config.num_streams--;
2450 continue;
2451 }
2452
Emilian Peevf4816702020-04-03 15:44:51 -07002453 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002454 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002456 CLOGE("Can't start output stream configuration");
2457 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002458 return INVALID_OPERATION;
2459 }
2460 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002461
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002462 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002463 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2464 // always occupy the initial entry.
Emilian Peeve579d8b2023-02-28 14:16:08 -08002465 if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2466 (outputStream->data_space ==
2467 static_cast<android_dataspace_t>(
2468 aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002469 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002470 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2471 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002472 } else if (outputStream->data_space ==
2473 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2474 bufferSizes[k] = outputStream->width * outputStream->height;
2475 } else {
2476 ALOGW("%s: Blob dataSpace %d not supported",
2477 __FUNCTION__, outputStream->data_space);
2478 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002479 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002480
2481 if (mOutputStreams[i]->isMultiResolution()) {
2482 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2483 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2484 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2485 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002486
2487 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07002488 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002489 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002490 }
2491
2492 config.streams = streams.editArray();
2493
2494 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002495 // max_buffers, usage, and priv fields, as well as data_space and format
2496 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002497
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002498 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002499 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002500 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002501 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002502
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002503 if (res == BAD_VALUE) {
2504 // HAL rejected this set of streams as unsupported, clean up config
2505 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002506 CLOGE("Set of requested inputs/outputs not supported by HAL");
2507 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002508 return BAD_VALUE;
2509 } else if (res != OK) {
2510 // Some other kind of error from configure_streams - this is not
2511 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002512 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2513 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002514 return res;
2515 }
2516
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002517 // Finish all stream configuration immediately.
2518 // TODO: Try to relax this later back to lazy completion, which should be
2519 // faster
2520
Igor Murashkin073f8572013-05-02 14:59:28 -07002521 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002522 bool streamReConfigured = false;
2523 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002524 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002525 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002526 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002527 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002528 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2529 return DEAD_OBJECT;
2530 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002531 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002532 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002533 if (streamReConfigured) {
2534 mInterface->onStreamReConfigured(mInputStream->getId());
2535 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002536 }
2537
2538 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002539 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002540 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002541 bool streamReConfigured = false;
2542 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002543 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002544 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002545 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002546 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002547 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2548 return DEAD_OBJECT;
2549 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002550 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002551 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002552 if (streamReConfigured) {
2553 mInterface->onStreamReConfigured(outputStream->getId());
2554 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002555 }
2556 }
2557
Emilian Peevd865f0d2023-03-17 17:13:07 -07002558 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002559
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 // Request thread needs to know to avoid using repeat-last-settings protocol
2561 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002562 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002563 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2564 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002565 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566
Zhijun He90f7c372016-08-16 16:19:43 -07002567 char value[PROPERTY_VALUE_MAX];
2568 property_get("camera.fifo.disable", value, "0");
2569 int32_t disableFifo = atoi(value);
2570 if (disableFifo != 1) {
2571 // Boost priority of request thread to SCHED_FIFO.
2572 pid_t requestThreadTid = mRequestThread->getTid();
2573 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002574 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002575 if (res != OK) {
2576 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2577 strerror(-res), res);
2578 } else {
2579 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2580 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002581 }
2582
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002583 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002584 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2585 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2586 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2587 sessionParams.unlock(newSessionParams);
2588 mSessionParams.unlock(currentSessionParams);
2589 if (updateSessionParams) {
2590 mSessionParams = sessionParams;
2591 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002593 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002594
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002595 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002596 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002598 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002599
Zhijun He0a210512014-07-24 13:45:15 -07002600 // tear down the deleted streams after configure streams.
2601 mDeletedStreams.clear();
2602
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002603 auto rc = mPreparerThread->resume();
2604 if (rc != OK) {
2605 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2606 return rc;
2607 }
2608
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002609 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002610 mRequestBufferSM.onStreamsConfigured();
2611 }
2612
Cliff Wu3b268182021-07-06 15:44:43 +08002613 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002614 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002615 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002616 // configure the injection streams.
2617 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002618 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002619 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2620 res = mInjectionMethods->injectCamera(config, bufferSizes);
2621 if (res != OK) {
2622 ALOGE("Can't finish inject camera process!");
2623 return res;
2624 }
Cliff Wu3b268182021-07-06 15:44:43 +08002625 } else {
2626 // First run configureStreamsLocked() and then call injectCamera() case:
2627 // If the stream configuration has been completed and camera deive is active, but the
2628 // injection camera has not been injected yet, we need to store the stream configuration of
2629 // the internal camera (because the stream configuration of the injection camera is based
2630 // on the internal camera). When injecting occurs later, this configuration can be used by
2631 // the injection camera.
2632 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2633 " injection camera has not been injected yet.", __FUNCTION__);
2634 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002635 }
2636
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002638}
2639
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002640status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002641 ATRACE_CALL();
2642 status_t res;
2643
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002644 if (mFakeStreamId != NO_STREAM) {
2645 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002646 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002647 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002648 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002649 return INVALID_OPERATION;
2650 }
2651
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002652 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002653
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002654 sp<Camera3OutputStreamInterface> fakeStream =
2655 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002656
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002657 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002658 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002659 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002660 return res;
2661 }
2662
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002663 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002664 mNextStreamId++;
2665
2666 return OK;
2667}
2668
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002669status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002670 ATRACE_CALL();
2671 status_t res;
2672
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002673 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002674 if (mOutputStreams.size() == 1) return OK;
2675
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002676 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002677
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002678 // Ok, have a fake stream and there's at least one other output stream,
2679 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002680
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002681 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002682 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002683 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002684 return INVALID_OPERATION;
2685 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002686 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002687
2688 // Free up the stream endpoint so that it can be used by some other stream
2689 res = deletedStream->disconnect();
2690 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002691 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002692 // fall through since we want to still list the stream as deleted.
2693 }
2694 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002695 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002696
2697 return res;
2698}
2699
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002700void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002701 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002702 Mutex::Autolock l(mLock);
2703 va_list args;
2704 va_start(args, fmt);
2705
2706 setErrorStateLockedV(fmt, args);
2707
2708 va_end(args);
2709}
2710
2711void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002712 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002713 Mutex::Autolock l(mLock);
2714 setErrorStateLockedV(fmt, args);
2715}
2716
2717void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2718 va_list args;
2719 va_start(args, fmt);
2720
2721 setErrorStateLockedV(fmt, args);
2722
2723 va_end(args);
2724}
2725
2726void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002727 // Print out all error messages to log
2728 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002729 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002730
2731 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002732 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002733
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002734 mErrorCause = errorCause;
2735
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002736 if (mRequestThread != nullptr) {
2737 mRequestThread->setPaused(true);
2738 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002739 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002740
2741 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002742 sp<NotificationListener> listener = mListener.promote();
2743 if (listener != NULL) {
2744 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002745 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002746 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002747 }
2748
2749 // Save stack trace. View by dumping it later.
2750 CameraTraces::saveTrace();
2751 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002752}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002753
2754/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002755 * In-flight request management
2756 */
2757
Jianing Weicb0652e2014-03-12 18:29:36 -07002758status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002759 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002760 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002761 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002762 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002763 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002764 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002765 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002766 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002767
2768 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002769 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002770 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002771 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2772 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002773 if (res < 0) return res;
2774
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002775 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002776 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2777 // avoid a deadlock during reprocess requests.
2778 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002779 if (mStatusTracker != nullptr) {
2780 mStatusTracker->markComponentActive(mInFlightStatusId);
2781 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002782 }
2783
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002784 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002785 return OK;
2786}
2787
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002788void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002789 // Indicate idle inFlightMap to the status tracker
2790 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002791 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002792 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2793 // avoid a deadlock during reprocess requests.
2794 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002795 if (mStatusTracker != nullptr) {
2796 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2797 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002798 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002799 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002800}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002801
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002802void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002803 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002804 // something has likely gone wrong. This might still be legit only if application send in
2805 // a long burst of long exposure requests.
2806 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2807 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2808 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2809 mInFlightMap.size(), mExpectedInflightDuration);
2810 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2811 kInFlightWarnLimitHighSpeed) {
2812 CLOGW("In-flight list too large for high speed configuration: %zu,"
2813 "total inflight duration %" PRIu64,
2814 mInFlightMap.size(), mExpectedInflightDuration);
2815 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002816 }
2817}
2818
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002819void Camera3Device::onInflightMapFlushedLocked() {
2820 mExpectedInflightDuration = 0;
2821}
2822
2823void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002824 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002825 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2826 mInFlightMap.removeItemsAt(idx, 1);
2827
2828 onInflightEntryRemovedLocked(duration);
2829}
2830
2831
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002832void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002833 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002834 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002835 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002836 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002837 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002838 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002839
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002840 FlushInflightReqStates states {
2841 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002842 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002843
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002844 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002845}
2846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002847CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002848 ALOGV("%s", __FUNCTION__);
2849
Igor Murashkin1e479c02013-09-06 16:55:14 -07002850 CameraMetadata retVal;
2851
2852 if (mRequestThread != NULL) {
2853 retVal = mRequestThread->getLatestRequest();
2854 }
2855
Igor Murashkin1e479c02013-09-06 16:55:14 -07002856 return retVal;
2857}
2858
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002859void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002860 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002861 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002862 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2863 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002864
2865 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002866 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002867}
2868
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002869void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002870 std::vector<native_handle_t*> *handles, bool closeFd) {
2871 if (handles == nullptr) {
2872 return;
2873 }
2874 if (closeFd) {
2875 for (auto& handle : *handles) {
2876 native_handle_close(handle);
2877 }
2878 }
2879 for (auto& handle : *handles) {
2880 native_handle_delete(handle);
2881 }
2882 handles->clear();
2883 return;
2884}
2885
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002886/**
2887 * HalInterface inner class methods
2888 */
2889
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002890void Camera3Device::HalInterface::getInflightBufferKeys(
2891 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002892 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002893 return;
2894}
2895
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002896void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2897 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002898 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002899 return;
2900}
2901
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002902bool Camera3Device::HalInterface::verifyBufferIds(
2903 int32_t streamId, std::vector<uint64_t>& bufIds) {
2904 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002905}
2906
2907status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002908 int32_t frameNumber, int32_t streamId,
2909 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002910 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002911}
2912
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002913status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002914 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002915 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002916}
2917
2918// Find and pop a buffer_handle_t based on bufferId
2919status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002920 uint64_t bufferId,
2921 /*out*/ buffer_handle_t** buffer,
2922 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002923 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002924}
2925
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002926std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2927 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002928 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002929}
2930
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002931uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2932 const native_handle_t* handle) {
2933 return mBufferRecords.removeOneBufferCache(streamId, handle);
2934}
2935
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002936void Camera3Device::HalInterface::onBufferFreed(
2937 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002938 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2939 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2940 if (bufferId != BUFFER_ID_NO_BUFFER) {
2941 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002942 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002943}
2944
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002945void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002946 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2947 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2948 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002949 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2950 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002951}
2952
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002954 * RequestThread inner class methods
2955 */
2956
2957Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002958 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002959 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002960 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002961 bool supportCameraMute,
2962 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002963 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002964 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002965 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002966 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002967 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002968 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002969 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002970 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971 mReconfigured(false),
2972 mDoPause(false),
2973 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002974 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002975 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002976 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002977 mCurrentAfTriggerId(0),
2978 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002979 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00002980 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002981 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002982 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002983 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002984 mRepeatingLastFrameNumber(
2985 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002986 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002987 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002988 mRequestLatency(kRequestLatencyBinSize),
2989 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002990 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002991 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07002992 mSupportCameraMute(supportCameraMute),
2993 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002994 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08002995 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002996}
2997
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002998Camera3Device::RequestThread::~RequestThread() {}
2999
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003000void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003001 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003002 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003003 Mutex::Autolock l(mRequestLock);
3004 mListener = listener;
3005}
3006
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003007void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08003008 const CameraMetadata& sessionParams,
3009 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003010 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003011 Mutex::Autolock l(mRequestLock);
3012 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003013 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08003014 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003015 // Prepare video stream for high speed recording.
3016 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003017 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003018}
3019
Jianing Wei90e59c92014-03-12 18:29:36 -07003020status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003021 List<sp<CaptureRequest> > &requests,
3022 /*out*/
3023 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003024 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003025 Mutex::Autolock l(mRequestLock);
3026 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3027 ++it) {
3028 mRequestQueue.push_back(*it);
3029 }
3030
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003031 if (lastFrameNumber != NULL) {
3032 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3033 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3034 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3035 *lastFrameNumber);
3036 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003037
Jianing Wei90e59c92014-03-12 18:29:36 -07003038 unpauseForNewRequests();
3039
3040 return OK;
3041}
3042
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003043
3044status_t Camera3Device::RequestThread::queueTrigger(
3045 RequestTrigger trigger[],
3046 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003047 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003048 Mutex::Autolock l(mTriggerMutex);
3049 status_t ret;
3050
3051 for (size_t i = 0; i < count; ++i) {
3052 ret = queueTriggerLocked(trigger[i]);
3053
3054 if (ret != OK) {
3055 return ret;
3056 }
3057 }
3058
3059 return OK;
3060}
3061
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003062const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3063 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003064 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003065 if (d != nullptr) return d->mId;
3066 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003067}
3068
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003069status_t Camera3Device::RequestThread::queueTriggerLocked(
3070 RequestTrigger trigger) {
3071
3072 uint32_t tag = trigger.metadataTag;
3073 ssize_t index = mTriggerMap.indexOfKey(tag);
3074
3075 switch (trigger.getTagType()) {
3076 case TYPE_BYTE:
3077 // fall-through
3078 case TYPE_INT32:
3079 break;
3080 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003081 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3082 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003083 return INVALID_OPERATION;
3084 }
3085
3086 /**
3087 * Collect only the latest trigger, since we only have 1 field
3088 * in the request settings per trigger tag, and can't send more than 1
3089 * trigger per request.
3090 */
3091 if (index != NAME_NOT_FOUND) {
3092 mTriggerMap.editValueAt(index) = trigger;
3093 } else {
3094 mTriggerMap.add(tag, trigger);
3095 }
3096
3097 return OK;
3098}
3099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003100status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003101 const RequestList &requests,
3102 /*out*/
3103 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003104 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003105 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003106 if (lastFrameNumber != NULL) {
3107 *lastFrameNumber = mRepeatingLastFrameNumber;
3108 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003109 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003110 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003111 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3112 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003113
3114 unpauseForNewRequests();
3115
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003117 return OK;
3118}
3119
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003120bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003121 if (mRepeatingRequests.empty()) {
3122 return false;
3123 }
3124 int32_t requestId = requestIn->mResultExtras.requestId;
3125 const RequestList &repeatRequests = mRepeatingRequests;
3126 // All repeating requests are guaranteed to have same id so only check first quest
3127 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3128 return (firstRequest->mResultExtras.requestId == requestId);
3129}
3130
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003131status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003132 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003133 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003134 return clearRepeatingRequestsLocked(lastFrameNumber);
3135
3136}
3137
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003138status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3139 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003140 std::vector<int32_t> streamIds;
3141 for (const auto& request : mRepeatingRequests) {
3142 for (const auto& stream : request->mOutputStreams) {
3143 streamIds.push_back(stream->getId());
3144 }
3145 }
3146
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003147 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003148 if (lastFrameNumber != NULL) {
3149 *lastFrameNumber = mRepeatingLastFrameNumber;
3150 }
Emilian Peev2295df72021-11-12 18:14:10 -08003151
3152 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3153
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003154 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003155 return OK;
3156}
3157
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003158status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003159 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003160 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003161 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003162 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003163
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003164 // Send errors for all requests pending in the request queue, including
3165 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003166 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003167 if (listener != NULL) {
3168 for (RequestList::iterator it = mRequestQueue.begin();
3169 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003170 // Abort the input buffers for reprocess requests.
3171 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003172 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003173 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003174 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003175 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003176 if (res != OK) {
3177 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3178 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3179 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003180 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003181 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3182 if (res != OK) {
3183 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3184 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3185 }
3186 }
3187 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003188 // Set the frame number this request would have had, if it
3189 // had been submitted; this frame number will not be reused.
3190 // The requestId and burstId fields were set when the request was
3191 // submitted originally (in convertMetadataListToRequestListLocked)
3192 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003193 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003194 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003195 }
3196 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003197 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003198
3199 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003200 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003201 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003202 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003203 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003204 return OK;
3205}
3206
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003207status_t Camera3Device::RequestThread::flush() {
3208 ATRACE_CALL();
3209 Mutex::Autolock l(mFlushLock);
3210
Emilian Peev08dd2452017-04-06 16:55:14 +01003211 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003212}
3213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003214void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003215 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003216 Mutex::Autolock l(mPauseLock);
3217 mDoPause = paused;
3218 mDoPauseSignal.signal();
3219}
3220
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003221status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3222 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003223 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003224 Mutex::Autolock l(mLatestRequestMutex);
3225 status_t res;
3226 while (mLatestRequestId != requestId) {
3227 nsecs_t startTime = systemTime();
3228
3229 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3230 if (res != OK) return res;
3231
3232 timeout -= (systemTime() - startTime);
3233 }
3234
3235 return OK;
3236}
3237
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003238void Camera3Device::RequestThread::requestExit() {
3239 // Call parent to set up shutdown
3240 Thread::requestExit();
3241 // The exit from any possible waits
3242 mDoPauseSignal.signal();
3243 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003244
3245 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3246 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003247}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003248
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003249void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003250 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003251 bool surfaceAbandoned = false;
3252 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003253 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003254 {
3255 Mutex::Autolock l(mRequestLock);
3256 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3257 // repeating requests.
3258 for (const auto& request : mRepeatingRequests) {
3259 for (const auto& s : request->mOutputStreams) {
3260 if (s->isAbandoned()) {
3261 surfaceAbandoned = true;
3262 clearRepeatingRequestsLocked(&lastFrameNumber);
3263 break;
3264 }
3265 }
3266 if (surfaceAbandoned) {
3267 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003268 }
3269 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003270 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003271 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003272
3273 if (listener != NULL && surfaceAbandoned) {
3274 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003275 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003276}
3277
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003278bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003279 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003280 status_t res;
3281 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003282 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003283 uint32_t numRequestProcessed = 0;
3284 for (size_t i = 0; i < batchSize; i++) {
3285 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003286 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003287 }
3288
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003289 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3290
3291 bool triggerRemoveFailed = false;
3292 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3293 for (size_t i = 0; i < numRequestProcessed; i++) {
3294 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3295 nextRequest.submitted = true;
3296
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003297 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003298
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003299 if (!triggerRemoveFailed) {
3300 // Remove any previously queued triggers (after unlock)
3301 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3302 if (removeTriggerRes != OK) {
3303 triggerRemoveFailed = true;
3304 triggerFailedRequest = nextRequest;
3305 }
3306 }
3307 }
3308
3309 if (triggerRemoveFailed) {
3310 SET_ERR("RequestThread: Unable to remove triggers "
3311 "(capture request %d, HAL device: %s (%d)",
3312 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3313 cleanUpFailedRequests(/*sendRequestError*/ false);
3314 return false;
3315 }
3316
3317 if (res != OK) {
3318 // Should only get a failure here for malformed requests or device-level
3319 // errors, so consider all errors fatal. Bad metadata failures should
3320 // come through notify.
3321 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3322 mNextRequests[numRequestProcessed].halRequest.frame_number,
3323 strerror(-res), res);
3324 cleanUpFailedRequests(/*sendRequestError*/ false);
3325 return false;
3326 }
3327 return true;
3328}
3329
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003330Camera3Device::RequestThread::ExpectedDurationInfo
3331 Camera3Device::RequestThread::calculateExpectedDurationRange(
3332 const camera_metadata_t *request) {
3333 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003334 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003335 InFlightRequest::kDefaultMaxExpectedDuration,
3336 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003337 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3338 find_camera_metadata_ro_entry(request,
3339 ANDROID_CONTROL_AE_MODE,
3340 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003341 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003342
3343 switch (e.data.u8[0]) {
3344 case ANDROID_CONTROL_AE_MODE_OFF:
3345 find_camera_metadata_ro_entry(request,
3346 ANDROID_SENSOR_EXPOSURE_TIME,
3347 &e);
3348 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003349 expectedDurationInfo.minDuration = e.data.i64[0];
3350 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003351 }
3352 find_camera_metadata_ro_entry(request,
3353 ANDROID_SENSOR_FRAME_DURATION,
3354 &e);
3355 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003356 expectedDurationInfo.minDuration =
3357 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3358 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003359 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003360 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003361 break;
3362 default:
3363 find_camera_metadata_ro_entry(request,
3364 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3365 &e);
3366 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003367 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3368 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003369 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003370 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003371 break;
3372 }
3373
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003374 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003375}
3376
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003377bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3378 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3379 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3380 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3381 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3382 return true;
3383 }
3384
3385 return false;
3386}
3387
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003388void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3389 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003390 camera_capture_request_t& halRequest = nextRequest.halRequest;
3391 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003392 Mutex::Autolock al(mLatestRequestMutex);
3393
Shuzhen Wang83bff122020-11-20 15:51:39 -08003394 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003395 mLatestRequest.acquire(cloned);
3396
3397 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003398 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3399 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3400 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003401 CameraMetadata(cloned));
3402 }
3403
3404 sp<Camera3Device> parent = mParent.promote();
3405 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003406 int32_t inputStreamId = -1;
3407 if (halRequest.input_buffer != nullptr) {
3408 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3409 }
3410
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003411 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003412 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003413 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3414 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003415 }
3416 }
3417
Shuzhen Wang83bff122020-11-20 15:51:39 -08003418 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003419 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003420 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003421 }
3422
Shuzhen Wang83bff122020-11-20 15:51:39 -08003423 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003424}
3425
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003426bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3427 ATRACE_CALL();
3428 bool updatesDetected = false;
3429
Emilian Peev4ec17882019-01-24 17:16:58 -08003430 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003431 for (auto tag : mSessionParamKeys) {
3432 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003433 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003434
3435 if (entry.count > 0) {
3436 bool isDifferent = false;
3437 if (lastEntry.count > 0) {
3438 // Have a last value, compare to see if changed
3439 if (lastEntry.type == entry.type &&
3440 lastEntry.count == entry.count) {
3441 // Same type and count, compare values
3442 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3443 size_t entryBytes = bytesPerValue * lastEntry.count;
3444 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3445 if (cmp != 0) {
3446 isDifferent = true;
3447 }
3448 } else {
3449 // Count or type has changed
3450 isDifferent = true;
3451 }
3452 } else {
3453 // No last entry, so always consider to be different
3454 isDifferent = true;
3455 }
3456
3457 if (isDifferent) {
3458 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003459 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3460 updatesDetected = true;
3461 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003462 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003463 }
3464 } else if (lastEntry.count > 0) {
3465 // Value has been removed
3466 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003467 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003468 updatesDetected = true;
3469 }
3470 }
3471
Emilian Peev4ec17882019-01-24 17:16:58 -08003472 bool reconfigureRequired;
3473 if (updatesDetected) {
3474 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3475 updatedParams);
3476 mLatestSessionParams = updatedParams;
3477 } else {
3478 reconfigureRequired = false;
3479 }
3480
3481 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003482}
3483
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003484bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003485 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003486 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003487 // Any function called from threadLoop() must not hold mInterfaceLock since
3488 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3489 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003490
3491 // Handle paused state.
3492 if (waitIfPaused()) {
3493 return true;
3494 }
3495
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003496 // Wait for the next batch of requests.
3497 waitForNextRequestBatch();
3498 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003499 return true;
3500 }
3501
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003502 // Get the latest request ID, if any
3503 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003504 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003505 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003506 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003507 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003508 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003509 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3510 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003511 }
3512
Emilian Peevd865f0d2023-03-17 17:13:07 -07003513 for (size_t i = 0; i < mNextRequests.size(); i++) {
3514 auto& nextRequest = mNextRequests.editItemAt(i);
3515 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3516 // Do not override rotate&crop for stream configurations that include
3517 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3518 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3519 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3520 overrideAutoRotateAndCrop(captureRequest);
3521 captureRequest->mAutoframingChanged = overrideAutoframing(captureRequest);
3522 }
3523
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003524 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3525 // or a single request from streaming or burst. In either case the first element
3526 // should contain the latest camera settings that we need to check for any session
3527 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003528 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003529 res = OK;
3530
3531 //Input stream buffers are already acquired at this point so an input stream
3532 //will not be able to move to idle state unless we force it.
3533 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3534 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3535 if (res != OK) {
3536 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3537 cleanUpFailedRequests(/*sendRequestError*/ false);
3538 return false;
3539 }
3540 }
3541
3542 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003543 sp<Camera3Device> parent = mParent.promote();
3544 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003545 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3546 if (statusTracker != nullptr) {
3547 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3548 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003549 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003550 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003551 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003552
3553 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3554 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3555 if (res != OK) {
3556 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3557 cleanUpFailedRequests(/*sendRequestError*/ false);
3558 return false;
3559 }
3560 }
3561 }
3562 }
3563
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003564 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003565 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003566 if (res == TIMED_OUT) {
3567 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003568 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003569 // Check if any stream is abandoned.
3570 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003571 return true;
3572 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003573 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003574 return false;
3575 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003576
Zhijun Hecc27e112013-10-03 16:12:43 -07003577 // Inform waitUntilRequestProcessed thread of a new request ID
3578 {
3579 Mutex::Autolock al(mLatestRequestMutex);
3580
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003581 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003582 mLatestRequestSignal.signal();
3583 }
3584
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003585 // Submit a batch of requests to HAL.
3586 // Use flush lock only when submitting multilple requests in a batch.
3587 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3588 // which may take a long time to finish so synchronizing flush() and
3589 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3590 // For now, only synchronize for high speed recording and we should figure something out for
3591 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003592 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003593
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003594 if (useFlushLock) {
3595 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003596 }
3597
Zhijun Hef0645c12016-08-02 00:58:11 -07003598 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003599 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003600
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003601 sp<Camera3Device> parent = mParent.promote();
3602 if (parent != nullptr) {
3603 parent->mRequestBufferSM.onSubmittingRequest();
3604 }
3605
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003606 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003607 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003608 submitRequestSuccess = sendRequestsBatch();
3609
Shuzhen Wang686f6442017-06-20 16:16:04 -07003610 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3611 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003612
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003613 if (useFlushLock) {
3614 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003615 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003616
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003617 // Unset as current request
3618 {
3619 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003620 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003621 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003622 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003623
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003624 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003625}
3626
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003627status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3628 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3629 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3630 ANDROID_SCALER_CROP_REGION_SET};
3631 if (request == nullptr) {
3632 ALOGE("%s request metadata nullptr", __FUNCTION__);
3633 return BAD_VALUE;
3634 }
3635 status_t res = OK;
3636 for (const auto &key : kFwkOnlyRegionKeys) {
3637 if (request->exists(key)) {
3638 res = request->erase(key);
3639 if (res != OK) {
3640 return res;
3641 }
3642 }
3643 }
3644 return OK;
3645}
3646
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003647status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003648 ATRACE_CALL();
3649
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003650 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003651 for (size_t i = 0; i < mNextRequests.size(); i++) {
3652 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003653 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003654 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3655 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003656
3657 // Prepare a request to HAL
3658 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3659
3660 // Insert any queued triggers (before metadata is locked)
3661 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003662 if (res < 0) {
3663 SET_ERR("RequestThread: Unable to insert triggers "
3664 "(capture request %d, HAL device: %s (%d)",
3665 halRequest->frame_number, strerror(-res), res);
3666 return INVALID_OPERATION;
3667 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003668
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003669 int triggerCount = res;
3670 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3671 mPrevTriggers = triggerCount;
3672
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003673 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003674
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003675 // If the request is the same as last, or we had triggers now or last time or
3676 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003677 bool newRequest =
Emilian Peevd865f0d2023-03-17 17:13:07 -07003678 (mPrevRequest != captureRequest || triggersMixedIn ||
3679 captureRequest->mRotateAndCropChanged ||
3680 captureRequest->mAutoframingChanged ||
3681 testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003682 // Request settings are all the same within one batch, so only treat the first
3683 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003684 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003685 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003686 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003687 /**
3688 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003689 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003690 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003691 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003692 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003693 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003694 "(capture request %d, HAL device: %s (%d)",
3695 halRequest->frame_number, strerror(-res), res);
3696 return INVALID_OPERATION;
3697 }
3698
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003699 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003700 sp<Camera3Device> parent = mParent.promote();
3701 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003702 List<PhysicalCameraSettings>::iterator it;
3703 for (it = captureRequest->mSettingsList.begin();
3704 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003705 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3706 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003707 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3708 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3709 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3710 res);
3711 return INVALID_OPERATION;
3712 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003713 continue;
3714 }
3715
3716 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3717 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3718 updateCaptureRequest(&(it->metadata));
3719 if (res != OK) {
3720 SET_ERR("RequestThread: Unable to correct capture requests "
3721 "for scaler crop region and metering regions for request "
3722 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3723 res);
3724 return INVALID_OPERATION;
3725 }
3726 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003727 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3728 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3729 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3730 res);
3731 return INVALID_OPERATION;
3732 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003733 }
3734 }
3735
3736 // Correct metadata regions for distortion correction if enabled
3737 for (it = captureRequest->mSettingsList.begin();
3738 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003739 if (parent->mDistortionMappers.find(it->cameraId) ==
3740 parent->mDistortionMappers.end()) {
3741 continue;
3742 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003743
3744 if (!captureRequest->mDistortionCorrectionUpdated) {
3745 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3746 &(it->metadata));
3747 if (res != OK) {
3748 SET_ERR("RequestThread: Unable to correct capture requests "
3749 "for lens distortion for request %d: %s (%d)",
3750 halRequest->frame_number, strerror(-res), res);
3751 return INVALID_OPERATION;
3752 }
3753 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003754 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003755 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003756
3757 for (it = captureRequest->mSettingsList.begin();
3758 it != captureRequest->mSettingsList.end(); it++) {
3759 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3760 parent->mZoomRatioMappers.end()) {
3761 continue;
3762 }
3763
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003764 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003765 cameraIdsWithZoom.insert(it->cameraId);
3766 }
3767
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003768 if (!captureRequest->mZoomRatioUpdated) {
3769 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3770 &(it->metadata));
3771 if (res != OK) {
3772 SET_ERR("RequestThread: Unable to correct capture requests "
3773 "for zoom ratio for request %d: %s (%d)",
3774 halRequest->frame_number, strerror(-res), res);
3775 return INVALID_OPERATION;
3776 }
3777 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003778 }
3779 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003780 if (captureRequest->mRotateAndCropAuto &&
3781 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003782 for (it = captureRequest->mSettingsList.begin();
3783 it != captureRequest->mSettingsList.end(); it++) {
3784 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3785 if (mapper != parent->mRotateAndCropMappers.end()) {
3786 res = mapper->second.updateCaptureRequest(&(it->metadata));
3787 if (res != OK) {
3788 SET_ERR("RequestThread: Unable to correct capture requests "
3789 "for rotate-and-crop for request %d: %s (%d)",
3790 halRequest->frame_number, strerror(-res), res);
3791 return INVALID_OPERATION;
3792 }
3793 }
3794 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003795 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003796 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003797
3798 for (it = captureRequest->mSettingsList.begin();
3799 it != captureRequest->mSettingsList.end(); it++) {
3800 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3801 mVndkVersion, it->metadata, false /*isStatic*/);
3802 if (res != OK) {
3803 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3804 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3805 return INVALID_OPERATION;
3806 }
3807 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003808 }
3809 }
3810
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003811 /**
3812 * The request should be presorted so accesses in HAL
3813 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3814 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003815 captureRequest->mSettingsList.begin()->metadata.sort();
3816 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003817 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003818 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003819 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3820
3821 IF_ALOGV() {
3822 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3823 find_camera_metadata_ro_entry(
3824 halRequest->settings,
3825 ANDROID_CONTROL_AF_TRIGGER,
3826 &e
3827 );
3828 if (e.count > 0) {
3829 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3830 __FUNCTION__,
3831 halRequest->frame_number,
3832 e.data.u8[0]);
3833 }
3834 }
3835 } else {
3836 // leave request.settings NULL to indicate 'reuse latest given'
3837 ALOGVV("%s: Request settings are REUSED",
3838 __FUNCTION__);
3839 }
3840
Emilian Peevaebbe412018-01-15 13:53:24 +00003841 if (captureRequest->mSettingsList.size() > 1) {
3842 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3843 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003844 if (newRequest) {
3845 halRequest->physcam_settings =
3846 new const camera_metadata* [halRequest->num_physcam_settings];
3847 } else {
3848 halRequest->physcam_settings = nullptr;
3849 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003850 auto it = ++captureRequest->mSettingsList.begin();
3851 size_t i = 0;
3852 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3853 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003854 if (newRequest) {
3855 it->metadata.sort();
3856 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3857 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003858 }
3859 }
3860
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003861 uint32_t totalNumBuffers = 0;
3862
3863 // Fill in buffers
3864 if (captureRequest->mInputStream != NULL) {
3865 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003866
3867 halRequest->input_width = captureRequest->mInputBufferSize.width;
3868 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003869 totalNumBuffers += 1;
3870 } else {
3871 halRequest->input_buffer = NULL;
3872 }
3873
Emilian Peevf4816702020-04-03 15:44:51 -07003874 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003875 captureRequest->mOutputStreams.size());
3876 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003877 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003878
3879 sp<Camera3Device> parent = mParent.promote();
3880 if (parent == NULL) {
3881 // Should not happen, and nowhere to send errors to, so just log it
3882 CLOGE("RequestThread: Parent is gone");
3883 return INVALID_OPERATION;
3884 }
3885 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3886
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003887 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003888 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003889 sp<Camera3OutputStreamInterface> outputStream =
3890 captureRequest->mOutputStreams.editItemAt(j);
3891 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003892
3893 // Prepare video buffers for high speed recording on the first video request.
3894 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3895 // Only try to prepare video stream on the first video request.
3896 mPrepareVideoStream = false;
3897
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003898 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3899 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003900 while (res == NOT_ENOUGH_DATA) {
3901 res = outputStream->prepareNextBuffer();
3902 }
3903 if (res != OK) {
3904 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3905 __FUNCTION__, strerror(-res), res);
3906 outputStream->cancelPrepare();
3907 }
3908 }
3909
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003910 std::vector<size_t> uniqueSurfaceIds;
3911 res = outputStream->getUniqueSurfaceIds(
3912 captureRequest->mOutputSurfaces[streamId],
3913 &uniqueSurfaceIds);
3914 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3915 if (res != OK && res != INVALID_OPERATION) {
3916 ALOGE("%s: failed to query stream %d unique surface IDs",
3917 __FUNCTION__, streamId);
3918 return res;
3919 }
3920 if (res == OK) {
3921 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3922 }
3923
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003924 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003925 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003926 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003927 return TIMED_OUT;
3928 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003929 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003930 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003931 buffer.stream = outputStream->asHalStream();
3932 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003933 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003934 buffer.acquire_fence = -1;
3935 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003936 // Mark the output stream as unpreparable to block clients from calling
3937 // 'prepare' after this request reaches CameraHal and before the respective
3938 // buffers are requested.
3939 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003940 } else {
3941 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3942 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003943 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003944 if (res != OK) {
3945 // Can't get output buffer from gralloc queue - this could be due to
3946 // abandoned queue or other consumer misbehavior, so not a fatal
3947 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003948 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003949 " %s (%d)", strerror(-res), res);
3950
3951 return TIMED_OUT;
3952 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003953 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003954
3955 {
3956 sp<Camera3Device> parent = mParent.promote();
3957 if (parent != nullptr) {
3958 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3959 for (const auto& settings : captureRequest->mSettingsList) {
3960 if ((streamCameraId.isEmpty() &&
3961 parent->getId() == settings.cameraId.c_str()) ||
3962 streamCameraId == settings.cameraId.c_str()) {
3963 outputStream->fireBufferRequestForFrameNumber(
3964 captureRequest->mResultExtras.frameNumber,
3965 settings.metadata);
3966 }
3967 }
3968 }
3969 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003970
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003971 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003972 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3973 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3974 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3975 } else if (!physicalCameraId.isEmpty()) {
3976 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003977 }
3978 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003979 }
3980 totalNumBuffers += halRequest->num_output_buffers;
3981
3982 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003983 // If this request list is for constrained high speed recording (not
3984 // preview), and the current request is not the last one in the batch,
3985 // do not send callback to the app.
3986 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003987 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003988 hasCallback = false;
3989 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003990 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003991 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003992 const camera_metadata_t* settings = halRequest->settings;
3993 bool shouldUnlockSettings = false;
3994 if (settings == nullptr) {
3995 shouldUnlockSettings = true;
3996 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3997 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003998 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3999 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004000 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004001 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4002 isStillCapture = true;
4003 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4004 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004005
Emilian Peevaf8416e2021-02-04 17:52:43 -08004006 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004007 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004008 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4009 isZslCapture = true;
4010 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004011 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004012 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004013 res = parent->registerInFlight(halRequest->frame_number,
4014 totalNumBuffers, captureRequest->mResultExtras,
4015 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004016 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004017 expectedDurationInfo.minDuration,
4018 expectedDurationInfo.maxDuration,
4019 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004020 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004021 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
4022 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004023 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004024 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004025 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4026 ", burstId = %" PRId32 ".",
4027 __FUNCTION__,
4028 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4029 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004030
4031 if (shouldUnlockSettings) {
4032 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4033 }
4034
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004035 if (res != OK) {
4036 SET_ERR("RequestThread: Unable to register new in-flight request:"
4037 " %s (%d)", strerror(-res), res);
4038 return INVALID_OPERATION;
4039 }
4040 }
4041
4042 return OK;
4043}
4044
Igor Murashkin1e479c02013-09-06 16:55:14 -07004045CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004046 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004047 Mutex::Autolock al(mLatestRequestMutex);
4048
4049 ALOGV("RequestThread::%s", __FUNCTION__);
4050
4051 return mLatestRequest;
4052}
4053
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004054bool Camera3Device::RequestThread::isStreamPending(
4055 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004056 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004057 Mutex::Autolock l(mRequestLock);
4058
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004060 if (!nextRequest.submitted) {
4061 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4062 if (stream == s) return true;
4063 }
4064 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004065 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004066 }
4067
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004068 for (const auto& request : mRequestQueue) {
4069 for (const auto& s : request->mOutputStreams) {
4070 if (stream == s) return true;
4071 }
4072 if (stream == request->mInputStream) return true;
4073 }
4074
4075 for (const auto& request : mRepeatingRequests) {
4076 for (const auto& s : request->mOutputStreams) {
4077 if (stream == s) return true;
4078 }
4079 if (stream == request->mInputStream) return true;
4080 }
4081
4082 return false;
4083}
Jianing Weicb0652e2014-03-12 18:29:36 -07004084
Emilian Peev40ead602017-09-26 15:46:36 +01004085bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4086 ATRACE_CALL();
4087 Mutex::Autolock l(mRequestLock);
4088
4089 for (const auto& nextRequest : mNextRequests) {
4090 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4091 if (s.first == streamId) {
4092 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4093 if (it != s.second.end()) {
4094 return true;
4095 }
4096 }
4097 }
4098 }
4099
4100 for (const auto& request : mRequestQueue) {
4101 for (const auto& s : request->mOutputSurfaces) {
4102 if (s.first == streamId) {
4103 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4104 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004105 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004106 }
4107 }
4108 }
4109 }
4110
4111 for (const auto& request : mRepeatingRequests) {
4112 for (const auto& s : request->mOutputSurfaces) {
4113 if (s.first == streamId) {
4114 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4115 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004116 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004117 }
4118 }
4119 }
4120 }
4121
4122 return false;
4123}
4124
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004125void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4126 if (!mUseHalBufManager) {
4127 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4128 return;
4129 }
4130
4131 Mutex::Autolock pl(mPauseLock);
4132 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004133 mInterface->signalPipelineDrain(streamIds);
4134 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004135 }
4136 // If request thread is still busy, wait until paused then notify HAL
4137 mNotifyPipelineDrain = true;
4138 mStreamIdsToBeDrained = streamIds;
4139}
4140
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004141void Camera3Device::RequestThread::resetPipelineDrain() {
4142 Mutex::Autolock pl(mPauseLock);
4143 mNotifyPipelineDrain = false;
4144 mStreamIdsToBeDrained.clear();
4145}
4146
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004147void Camera3Device::RequestThread::clearPreviousRequest() {
4148 Mutex::Autolock l(mRequestLock);
4149 mPrevRequest.clear();
4150}
4151
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004152status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4153 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4154 ATRACE_CALL();
4155 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004156 mRotateAndCropOverride = rotateAndCropValue;
4157 return OK;
4158}
4159
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004160status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4161 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4162 ATRACE_CALL();
4163 Mutex::Autolock l(mTriggerMutex);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004164 mAutoframingOverride = autoframingValue;
4165 return OK;
4166}
4167
Emilian Peeve23f1d92021-09-20 14:56:01 -07004168status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4169 ATRACE_CALL();
4170 Mutex::Autolock l(mTriggerMutex);
4171 mComposerOutput = composerSurfacePresent;
4172 return OK;
4173}
4174
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004175status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004176 ATRACE_CALL();
4177 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004178 if (muteMode != mCameraMute) {
4179 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004180 mCameraMuteChanged = true;
4181 }
4182 return OK;
4183}
4184
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004185nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004186 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004187 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004188 return mExpectedInflightDuration > kMinInflightDuration ?
4189 mExpectedInflightDuration : kMinInflightDuration;
4190}
4191
Emilian Peevaebbe412018-01-15 13:53:24 +00004192void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004193 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004194 if ((request == nullptr) || (halRequest == nullptr)) {
4195 ALOGE("%s: Invalid request!", __FUNCTION__);
4196 return;
4197 }
4198
4199 if (halRequest->num_physcam_settings > 0) {
4200 if (halRequest->physcam_id != nullptr) {
4201 delete [] halRequest->physcam_id;
4202 halRequest->physcam_id = nullptr;
4203 }
4204 if (halRequest->physcam_settings != nullptr) {
4205 auto it = ++(request->mSettingsList.begin());
4206 size_t i = 0;
4207 for (; it != request->mSettingsList.end(); it++, i++) {
4208 it->metadata.unlock(halRequest->physcam_settings[i]);
4209 }
4210 delete [] halRequest->physcam_settings;
4211 halRequest->physcam_settings = nullptr;
4212 }
4213 }
4214}
4215
Ravneetaeb20dc2022-03-30 05:33:03 +00004216status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4217 Mutex::Autolock il(mInterfaceLock);
4218 Mutex::Autolock l(mLock);
4219
4220 if (mCameraServiceWatchdog != NULL) {
4221 mCameraServiceWatchdog->setEnabled(enabled);
4222 }
4223
4224 return OK;
4225}
4226
Shuzhen Wang16610a62022-12-15 22:38:07 -08004227void Camera3Device::setStreamUseCaseOverrides(
4228 const std::vector<int64_t>& useCaseOverrides) {
4229 Mutex::Autolock il(mInterfaceLock);
4230 Mutex::Autolock l(mLock);
4231 mStreamUseCaseOverrides = useCaseOverrides;
4232}
4233
4234void Camera3Device::clearStreamUseCaseOverrides() {
4235 Mutex::Autolock il(mInterfaceLock);
4236 Mutex::Autolock l(mLock);
4237 mStreamUseCaseOverrides.clear();
4238}
4239
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004240bool Camera3Device::hasDeviceError() {
4241 Mutex::Autolock il(mInterfaceLock);
4242 Mutex::Autolock l(mLock);
4243 return mStatus == STATUS_ERROR;
4244}
4245
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004246void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4247 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004248 return;
4249 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004250
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004251 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004252 // Skip the ones that have been submitted successfully.
4253 if (nextRequest.submitted) {
4254 continue;
4255 }
4256
4257 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004258 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4259 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004260
4261 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004262 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004263 }
4264
Emilian Peevaebbe412018-01-15 13:53:24 +00004265 cleanupPhysicalSettings(captureRequest, halRequest);
4266
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004267 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004268 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004269 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4270 }
4271
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004272 // No output buffer can be returned when using HAL buffer manager
4273 if (!mUseHalBufManager) {
4274 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4275 //Buffers that failed processing could still have
4276 //valid acquire fence.
4277 int acquireFence = (*outputBuffers)[i].acquire_fence;
4278 if (0 <= acquireFence) {
4279 close(acquireFence);
4280 outputBuffers->editItemAt(i).acquire_fence = -1;
4281 }
Emilian Peevf4816702020-04-03 15:44:51 -07004282 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004283 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4284 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004285 /*timestampIncreasing*/true, std::vector<size_t> (),
4286 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004287 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004288 }
4289
4290 if (sendRequestError) {
4291 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004292 sp<NotificationListener> listener = mListener.promote();
4293 if (listener != NULL) {
4294 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004295 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004296 captureRequest->mResultExtras);
4297 }
4298 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004299
4300 // Remove yet-to-be submitted inflight request from inflightMap
4301 {
4302 sp<Camera3Device> parent = mParent.promote();
4303 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004304 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004305 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4306 if (idx >= 0) {
4307 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4308 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4309 parent->removeInFlightMapEntryLocked(idx);
4310 }
4311 }
4312 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004313 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004314
4315 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004316 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004317}
4318
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004319void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004320 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321 // Optimized a bit for the simple steady-state case (single repeating
4322 // request), to avoid putting that request in the queue temporarily.
4323 Mutex::Autolock l(mRequestLock);
4324
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004325 assert(mNextRequests.empty());
4326
4327 NextRequest nextRequest;
4328 nextRequest.captureRequest = waitForNextRequestLocked();
4329 if (nextRequest.captureRequest == nullptr) {
4330 return;
4331 }
4332
Emilian Peevf4816702020-04-03 15:44:51 -07004333 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004334 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004335 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004336
4337 // Wait for additional requests
4338 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4339
4340 for (size_t i = 1; i < batchSize; i++) {
4341 NextRequest additionalRequest;
4342 additionalRequest.captureRequest = waitForNextRequestLocked();
4343 if (additionalRequest.captureRequest == nullptr) {
4344 break;
4345 }
4346
Emilian Peevf4816702020-04-03 15:44:51 -07004347 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004348 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004349 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004350 }
4351
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004352 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004353 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004354 mNextRequests.size(), batchSize);
4355 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356 }
4357
4358 return;
4359}
4360
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004361void Camera3Device::RequestThread::setRequestClearing() {
4362 Mutex::Autolock l(mRequestLock);
4363 mRequestClearing = true;
4364}
4365
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004366sp<Camera3Device::CaptureRequest>
4367 Camera3Device::RequestThread::waitForNextRequestLocked() {
4368 status_t res;
4369 sp<CaptureRequest> nextRequest;
4370
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004371 while (mRequestQueue.empty()) {
4372 if (!mRepeatingRequests.empty()) {
4373 // Always atomically enqueue all requests in a repeating request
4374 // list. Guarantees a complete in-sequence set of captures to
4375 // application.
4376 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004377 if (mFirstRepeating) {
4378 mFirstRepeating = false;
4379 } else {
4380 for (auto& request : requests) {
4381 // For repeating requests, override timestamp request using
4382 // the time a request is inserted into the request queue,
4383 // because the original repeating request will have an old
4384 // fixed timestamp.
4385 request->mRequestTimeNs = systemTime();
4386 }
4387 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004388 RequestList::const_iterator firstRequest =
4389 requests.begin();
4390 nextRequest = *firstRequest;
4391 mRequestQueue.insert(mRequestQueue.end(),
4392 ++firstRequest,
4393 requests.end());
4394 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004395
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004396 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004398 break;
4399 }
4400
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004401 if (!mRequestClearing) {
4402 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4403 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004404
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004405 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4406 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004407 Mutex::Autolock pl(mPauseLock);
4408 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004409 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004410 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004411 if (mNotifyPipelineDrain) {
4412 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4413 mNotifyPipelineDrain = false;
4414 mStreamIdsToBeDrained.clear();
4415 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004416 // Let the tracker know
4417 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4418 if (statusTracker != 0) {
4419 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4420 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004421 sp<Camera3Device> parent = mParent.promote();
4422 if (parent != nullptr) {
4423 parent->mRequestBufferSM.onRequestThreadPaused();
4424 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004425 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004426 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004427 // Stop waiting for now and let thread management happen
4428 return NULL;
4429 }
4430 }
4431
4432 if (nextRequest == NULL) {
4433 // Don't have a repeating request already in hand, so queue
4434 // must have an entry now.
4435 RequestList::iterator firstRequest =
4436 mRequestQueue.begin();
4437 nextRequest = *firstRequest;
4438 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004439 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4440 sp<NotificationListener> listener = mListener.promote();
4441 if (listener != NULL) {
4442 listener->notifyRequestQueueEmpty();
4443 }
4444 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004445 }
4446
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004447 // In case we've been unpaused by setPaused clearing mDoPause, need to
4448 // update internal pause state (capture/setRepeatingRequest unpause
4449 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004451 if (mPaused) {
4452 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4453 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4454 if (statusTracker != 0) {
4455 statusTracker->markComponentActive(mStatusId);
4456 }
4457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004458 mPaused = false;
4459
4460 // Check if we've reconfigured since last time, and reset the preview
4461 // request if so. Can't use 'NULL request == repeat' across configure calls.
4462 if (mReconfigured) {
4463 mPrevRequest.clear();
4464 mReconfigured = false;
4465 }
4466
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004467 if (nextRequest != NULL) {
4468 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004469 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4470 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004471
4472 // Since RequestThread::clear() removes buffers from the input stream,
4473 // get the right buffer here before unlocking mRequestLock
4474 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004475 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4476 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004477 if (res != OK) {
4478 // Can't get input buffer from gralloc queue - this could be due to
4479 // disconnected queue or other producer misbehavior, so not a fatal
4480 // error
4481 ALOGE("%s: Can't get input buffer, skipping request:"
4482 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004483
4484 sp<NotificationListener> listener = mListener.promote();
4485 if (listener != NULL) {
4486 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004487 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004488 nextRequest->mResultExtras);
4489 }
4490 return NULL;
4491 }
4492 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004493 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004494
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004495 return nextRequest;
4496}
4497
4498bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004499 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004500 status_t res;
4501 Mutex::Autolock l(mPauseLock);
4502 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004503 if (mPaused == false) {
4504 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004505 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004506 if (mNotifyPipelineDrain) {
4507 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4508 mNotifyPipelineDrain = false;
4509 mStreamIdsToBeDrained.clear();
4510 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004511 // Let the tracker know
4512 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4513 if (statusTracker != 0) {
4514 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4515 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004516 sp<Camera3Device> parent = mParent.promote();
4517 if (parent != nullptr) {
4518 parent->mRequestBufferSM.onRequestThreadPaused();
4519 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004520 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004521
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004522 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004523 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004524 return true;
4525 }
4526 }
4527 // We don't set mPaused to false here, because waitForNextRequest needs
4528 // to further manage the paused state in case of starvation.
4529 return false;
4530}
4531
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004532void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004533 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004534 // With work to do, mark thread as unpaused.
4535 // If paused by request (setPaused), don't resume, to avoid
4536 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004537 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004538 Mutex::Autolock p(mPauseLock);
4539 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004540 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4541 if (mPaused) {
4542 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4543 if (statusTracker != 0) {
4544 statusTracker->markComponentActive(mStatusId);
4545 }
4546 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004547 mPaused = false;
4548 }
4549}
4550
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004551void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4552 sp<Camera3Device> parent = mParent.promote();
4553 if (parent != NULL) {
4554 va_list args;
4555 va_start(args, fmt);
4556
4557 parent->setErrorStateV(fmt, args);
4558
4559 va_end(args);
4560 }
4561}
4562
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004563status_t Camera3Device::RequestThread::insertTriggers(
4564 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004565 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004566 Mutex::Autolock al(mTriggerMutex);
4567
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004568 sp<Camera3Device> parent = mParent.promote();
4569 if (parent == NULL) {
4570 CLOGE("RequestThread: Parent is gone");
4571 return DEAD_OBJECT;
4572 }
4573
Emilian Peevaebbe412018-01-15 13:53:24 +00004574 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004575 size_t count = mTriggerMap.size();
4576
4577 for (size_t i = 0; i < count; ++i) {
4578 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004579 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004580
4581 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4582 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4583 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004584 if (isAeTrigger) {
4585 request->mResultExtras.precaptureTriggerId = triggerId;
4586 mCurrentPreCaptureTriggerId = triggerId;
4587 } else {
4588 request->mResultExtras.afTriggerId = triggerId;
4589 mCurrentAfTriggerId = triggerId;
4590 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004591 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004592 }
4593
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004594 camera_metadata_entry entry = metadata.find(tag);
4595
4596 if (entry.count > 0) {
4597 /**
4598 * Already has an entry for this trigger in the request.
4599 * Rewrite it with our requested trigger value.
4600 */
4601 RequestTrigger oldTrigger = trigger;
4602
4603 oldTrigger.entryValue = entry.data.u8[0];
4604
4605 mTriggerReplacedMap.add(tag, oldTrigger);
4606 } else {
4607 /**
4608 * More typical, no trigger entry, so we just add it
4609 */
4610 mTriggerRemovedMap.add(tag, trigger);
4611 }
4612
4613 status_t res;
4614
4615 switch (trigger.getTagType()) {
4616 case TYPE_BYTE: {
4617 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4618 res = metadata.update(tag,
4619 &entryValue,
4620 /*count*/1);
4621 break;
4622 }
4623 case TYPE_INT32:
4624 res = metadata.update(tag,
4625 &trigger.entryValue,
4626 /*count*/1);
4627 break;
4628 default:
4629 ALOGE("%s: Type not supported: 0x%x",
4630 __FUNCTION__,
4631 trigger.getTagType());
4632 return INVALID_OPERATION;
4633 }
4634
4635 if (res != OK) {
4636 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4637 ", value %d", __FUNCTION__, trigger.getTagName(),
4638 trigger.entryValue);
4639 return res;
4640 }
4641
4642 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4643 trigger.getTagName(),
4644 trigger.entryValue);
4645 }
4646
4647 mTriggerMap.clear();
4648
4649 return count;
4650}
4651
4652status_t Camera3Device::RequestThread::removeTriggers(
4653 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004654 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004655 Mutex::Autolock al(mTriggerMutex);
4656
Emilian Peevaebbe412018-01-15 13:53:24 +00004657 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004658
4659 /**
4660 * Replace all old entries with their old values.
4661 */
4662 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4663 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4664
4665 status_t res;
4666
4667 uint32_t tag = trigger.metadataTag;
4668 switch (trigger.getTagType()) {
4669 case TYPE_BYTE: {
4670 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4671 res = metadata.update(tag,
4672 &entryValue,
4673 /*count*/1);
4674 break;
4675 }
4676 case TYPE_INT32:
4677 res = metadata.update(tag,
4678 &trigger.entryValue,
4679 /*count*/1);
4680 break;
4681 default:
4682 ALOGE("%s: Type not supported: 0x%x",
4683 __FUNCTION__,
4684 trigger.getTagType());
4685 return INVALID_OPERATION;
4686 }
4687
4688 if (res != OK) {
4689 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4690 ", trigger value %d", __FUNCTION__,
4691 trigger.getTagName(), trigger.entryValue);
4692 return res;
4693 }
4694 }
4695 mTriggerReplacedMap.clear();
4696
4697 /**
4698 * Remove all new entries.
4699 */
4700 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4701 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4702 status_t res = metadata.erase(trigger.metadataTag);
4703
4704 if (res != OK) {
4705 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4706 ", trigger value %d", __FUNCTION__,
4707 trigger.getTagName(), trigger.entryValue);
4708 return res;
4709 }
4710 }
4711 mTriggerRemovedMap.clear();
4712
4713 return OK;
4714}
4715
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004716status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004717 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004718 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004719 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004720 status_t res;
4721
Emilian Peevaebbe412018-01-15 13:53:24 +00004722 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004723
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004724 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004725 // exists
4726 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4727 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4728 if (afTrigger.count > 0 &&
4729 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4730 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004731 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004732 if (res != OK) return res;
4733 }
4734
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004735 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004736 // if none already exists
4737 camera_metadata_entry pcTrigger =
4738 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4739 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4740 if (pcTrigger.count > 0 &&
4741 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4742 pcId.count == 0) {
4743 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004744 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004745 if (res != OK) return res;
4746 }
4747
4748 return OK;
4749}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004750
Emilian Peevd865f0d2023-03-17 17:13:07 -07004751bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4752 ATRACE_CALL();
4753 Mutex::Autolock l(mTriggerMutex);
4754 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4755 this->mRotateAndCropOverride);
4756}
4757
4758bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4759 bool overrideToPortrait,
4760 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004761 ATRACE_CALL();
4762
Emilian Peevd865f0d2023-03-17 17:13:07 -07004763 if (overrideToPortrait) {
4764 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger18b30a72022-10-27 12:20:29 -07004765 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4766 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4767 &rotateAndCrop_u8, 1);
4768 return true;
4769 }
4770
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004771 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004772 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4773
4774 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4775 if (rotateAndCropEntry.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004776 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004777 return false;
4778 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004779 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004780 return true;
4781 }
4782 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004783 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4784 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004785 return true;
4786 }
4787 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004788
4789 return false;
4790}
4791
4792bool Camera3Device::overrideAutoframing(const sp<CaptureRequest> &request /*out*/,
4793 camera_metadata_enum_android_control_autoframing_t autoframingOverride) {
4794 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4795 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4796 if (autoframingEntry.count > 0) {
4797 if (autoframingEntry.data.u8[0] == autoframingOverride) {
4798 return false;
4799 } else {
4800 autoframingEntry.data.u8[0] = autoframingOverride;
4801 return true;
4802 }
4803 } else {
4804 uint8_t autoframing_u8 = autoframingOverride;
4805 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4806 &autoframing_u8, 1);
4807 return true;
4808 }
4809
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004810 return false;
4811}
4812
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004813bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4814 ATRACE_CALL();
4815
4816 if (request->mAutoframingAuto) {
4817 Mutex::Autolock l(mTriggerMutex);
Emilian Peevd865f0d2023-03-17 17:13:07 -07004818 return Camera3Device::overrideAutoframing(request, mAutoframingOverride);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004819 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004820
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004821 return false;
4822}
4823
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004824bool Camera3Device::RequestThread::overrideTestPattern(
4825 const sp<CaptureRequest> &request) {
4826 ATRACE_CALL();
4827
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004828 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004829
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004830 Mutex::Autolock l(mTriggerMutex);
4831
4832 bool changed = false;
4833
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004834 // For a multi-camera, the physical cameras support the same set of
4835 // test pattern modes as the logical camera.
4836 for (auto& settings : request->mSettingsList) {
4837 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004838
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004839 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4840 int32_t testPatternData[4] = {
4841 settings.mOriginalTestPatternData[0],
4842 settings.mOriginalTestPatternData[1],
4843 settings.mOriginalTestPatternData[2],
4844 settings.mOriginalTestPatternData[3]
4845 };
4846 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4847 testPatternMode = mCameraMute;
4848 testPatternData[0] = 0;
4849 testPatternData[1] = 0;
4850 testPatternData[2] = 0;
4851 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004852 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004853
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004854 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4855 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4856 if (testPatternEntry.count > 0) {
4857 if (testPatternEntry.data.i32[0] != testPatternMode) {
4858 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004859 changed = true;
4860 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004861 } else if (supportTestPatternModeKey) {
4862 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4863 &testPatternMode, 1);
4864 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004865 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004866
4867 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4868 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4869 if (testPatternColor.count >= 4) {
4870 for (size_t i = 0; i < 4; i++) {
4871 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4872 testPatternColor.data.i32[i] = testPatternData[i];
4873 changed = true;
4874 }
4875 }
4876 } else if (supportTestPatternDataKey) {
4877 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4878 testPatternData, 4);
4879 changed = true;
4880 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004881 }
4882
4883 return changed;
4884}
4885
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004886status_t Camera3Device::RequestThread::setHalInterface(
4887 sp<HalInterface> newHalInterface) {
4888 if (newHalInterface.get() == nullptr) {
4889 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4890 return DEAD_OBJECT;
4891 }
4892
4893 mInterface = newHalInterface;
4894
4895 return OK;
4896}
4897
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004898/**
4899 * PreparerThread inner class methods
4900 */
4901
4902Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004903 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004904 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004905}
4906
4907Camera3Device::PreparerThread::~PreparerThread() {
4908 Thread::requestExitAndWait();
4909 if (mCurrentStream != nullptr) {
4910 mCurrentStream->cancelPrepare();
4911 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4912 mCurrentStream.clear();
4913 }
4914 clear();
4915}
4916
Ruben Brunkc78ac262015-08-13 17:58:46 -07004917status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004918 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004919 status_t res;
4920
4921 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004922 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004923
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004924 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004925 if (res == OK) {
4926 // No preparation needed, fire listener right off
4927 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004928 if (listener != NULL) {
4929 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004930 }
4931 return OK;
4932 } else if (res != NOT_ENOUGH_DATA) {
4933 return res;
4934 }
4935
4936 // Need to prepare, start up thread if necessary
4937 if (!mActive) {
4938 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4939 // isn't running
4940 Thread::requestExitAndWait();
4941 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4942 if (res != OK) {
4943 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004944 if (listener != NULL) {
4945 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004946 }
4947 return res;
4948 }
4949 mCancelNow = false;
4950 mActive = true;
4951 ALOGV("%s: Preparer stream started", __FUNCTION__);
4952 }
4953
4954 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004955 mPendingStreams.push_back(
4956 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004957 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4958
4959 return OK;
4960}
4961
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004962void Camera3Device::PreparerThread::pause() {
4963 ATRACE_CALL();
4964
4965 Mutex::Autolock l(mLock);
4966
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004967 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
4968 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004969 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4970 int currentMaxCount = mCurrentMaxCount;
4971 mPendingStreams.clear();
4972 mCancelNow = true;
4973 while (mActive) {
4974 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4975 if (res == TIMED_OUT) {
4976 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4977 return;
4978 } else if (res != OK) {
4979 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4980 return;
4981 }
4982 }
4983
4984 //Check whether the prepare thread was able to complete the current
4985 //stream. In case work is still pending emplace it along with the rest
4986 //of the streams in the pending list.
4987 if (currentStream != nullptr) {
4988 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004989 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004990 }
4991 }
4992
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004993 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004994 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004995 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004996 }
4997}
4998
4999status_t Camera3Device::PreparerThread::resume() {
5000 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005001 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005002 status_t res;
5003
5004 Mutex::Autolock l(mLock);
5005 sp<NotificationListener> listener = mListener.promote();
5006
5007 if (mActive) {
5008 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5009 return NO_INIT;
5010 }
5011
5012 auto it = mPendingStreams.begin();
5013 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005014 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005015 if (res == OK) {
5016 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005017 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005018 }
5019 it = mPendingStreams.erase(it);
5020 } else if (res != NOT_ENOUGH_DATA) {
5021 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5022 res, strerror(-res));
5023 it = mPendingStreams.erase(it);
5024 } else {
5025 it++;
5026 }
5027 }
5028
5029 if (mPendingStreams.empty()) {
5030 return OK;
5031 }
5032
5033 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5034 if (res != OK) {
5035 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5036 __FUNCTION__, res, strerror(-res));
5037 return res;
5038 }
5039 mCancelNow = false;
5040 mActive = true;
5041 ALOGV("%s: Preparer stream started", __FUNCTION__);
5042
5043 return OK;
5044}
5045
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005046status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005047 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005048 Mutex::Autolock l(mLock);
5049
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005050 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005051 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005052 }
5053 mPendingStreams.clear();
5054 mCancelNow = true;
5055
5056 return OK;
5057}
5058
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005059void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005060 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005061 Mutex::Autolock l(mLock);
5062 mListener = listener;
5063}
5064
5065bool Camera3Device::PreparerThread::threadLoop() {
5066 status_t res;
5067 {
5068 Mutex::Autolock l(mLock);
5069 if (mCurrentStream == nullptr) {
5070 // End thread if done with work
5071 if (mPendingStreams.empty()) {
5072 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5073 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5074 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5075 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005076 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005077 return false;
5078 }
5079
5080 // Get next stream to prepare
5081 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005082 mCurrentMaxCount = std::get<0>(*it);
5083 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005084 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005085 mPendingStreams.erase(it);
5086 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5087 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5088 } else if (mCancelNow) {
5089 mCurrentStream->cancelPrepare();
5090 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5091 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5092 mCurrentStream.clear();
5093 mCancelNow = false;
5094 return true;
5095 }
5096 }
5097
5098 res = mCurrentStream->prepareNextBuffer();
5099 if (res == NOT_ENOUGH_DATA) return true;
5100 if (res != OK) {
5101 // Something bad happened; try to recover by cancelling prepare and
5102 // signalling listener anyway
5103 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5104 mCurrentStream->getId(), res, strerror(-res));
5105 mCurrentStream->cancelPrepare();
5106 }
5107
5108 // This stream has finished, notify listener
5109 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005110 sp<NotificationListener> listener = mListener.promote();
5111 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005112 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5113 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005114 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005115 }
5116
5117 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5118 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005119 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005120
5121 return true;
5122}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005123
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005124status_t Camera3Device::RequestBufferStateMachine::initialize(
5125 sp<camera3::StatusTracker> statusTracker) {
5126 if (statusTracker == nullptr) {
5127 ALOGE("%s: statusTracker is null", __FUNCTION__);
5128 return BAD_VALUE;
5129 }
5130
5131 std::lock_guard<std::mutex> lock(mLock);
5132 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005133 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005134 return OK;
5135}
5136
5137bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5138 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005139 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005140 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005141 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005142 return true;
5143 }
5144 return false;
5145}
5146
5147void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5148 std::lock_guard<std::mutex> lock(mLock);
5149 if (!mRequestBufferOngoing) {
5150 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5151 return;
5152 }
5153 mRequestBufferOngoing = false;
5154 if (mStatus == RB_STATUS_PENDING_STOP) {
5155 checkSwitchToStopLocked();
5156 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005157 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005158}
5159
5160void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5161 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005162 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005163 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005164 return;
5165}
5166
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005167void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005168 std::lock_guard<std::mutex> lock(mLock);
5169 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005170 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5171 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005172 mInflightMapEmpty = false;
5173 if (mStatus == RB_STATUS_STOPPED) {
5174 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005175 }
5176 return;
5177}
5178
5179void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5180 std::lock_guard<std::mutex> lock(mLock);
5181 mRequestThreadPaused = true;
5182 if (mStatus == RB_STATUS_PENDING_STOP) {
5183 checkSwitchToStopLocked();
5184 }
5185 return;
5186}
5187
5188void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5189 std::lock_guard<std::mutex> lock(mLock);
5190 mInflightMapEmpty = true;
5191 if (mStatus == RB_STATUS_PENDING_STOP) {
5192 checkSwitchToStopLocked();
5193 }
5194 return;
5195}
5196
5197void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5198 std::lock_guard<std::mutex> lock(mLock);
5199 if (!checkSwitchToStopLocked()) {
5200 mStatus = RB_STATUS_PENDING_STOP;
5201 }
5202 return;
5203}
5204
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005205bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5206 std::lock_guard<std::mutex> lock(mLock);
5207 if (mRequestBufferOngoing) {
5208 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5209 __FUNCTION__);
5210 return false;
5211 }
5212 mSwitchedToOffline = true;
5213 mInflightMapEmpty = true;
5214 mRequestThreadPaused = true;
5215 mStatus = RB_STATUS_STOPPED;
5216 return true;
5217}
5218
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005219void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5220 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5221 if (statusTracker != nullptr) {
5222 if (active) {
5223 statusTracker->markComponentActive(mRequestBufferStatusId);
5224 } else {
5225 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5226 }
5227 }
5228}
5229
5230bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5231 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5232 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005233 return true;
5234 }
5235 return false;
5236}
5237
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005238bool Camera3Device::startRequestBuffer() {
5239 return mRequestBufferSM.startRequestBuffer();
5240}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005241
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005242void Camera3Device::endRequestBuffer() {
5243 mRequestBufferSM.endRequestBuffer();
5244}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005245
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005246nsecs_t Camera3Device::getWaitDuration() {
5247 return kBaseGetBufferWait + getExpectedInFlightDuration();
5248}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005249
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005250void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5251 mInterface->getInflightBufferKeys(out);
5252}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005253
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005254void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5255 mInterface->getInflightRequestBufferKeys(out);
5256}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005257
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005258std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5259 std::vector<sp<Camera3StreamInterface>> ret;
5260 bool hasInputStream = mInputStream != nullptr;
5261 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5262 if (hasInputStream) {
5263 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005264 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005265 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5266 ret.push_back(mOutputStreams[i]);
5267 }
5268 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5269 ret.push_back(mDeletedStreams[i]);
5270 }
5271 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005272}
5273
Emilian Peevcc0b7952020-01-07 13:54:47 -08005274void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5275 ATRACE_CALL();
5276
5277 if (offlineStreamIds == nullptr) {
5278 return;
5279 }
5280
5281 Mutex::Autolock il(mInterfaceLock);
5282
5283 auto streamIds = mOutputStreams.getStreamIds();
5284 bool hasInputStream = mInputStream != nullptr;
5285 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5286 offlineStreamIds->push_back(mInputStream->getId());
5287 }
5288
5289 for (const auto & streamId : streamIds) {
5290 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5291 // Streams that use the camera buffer manager are currently not supported in
5292 // offline mode
5293 if (stream->getOfflineProcessingSupport() &&
5294 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5295 offlineStreamIds->push_back(streamId);
5296 }
5297 }
5298}
5299
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005300status_t Camera3Device::setRotateAndCropAutoBehavior(
5301 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5302 ATRACE_CALL();
5303 Mutex::Autolock il(mInterfaceLock);
5304 Mutex::Autolock l(mLock);
5305 if (mRequestThread == nullptr) {
5306 return INVALID_OPERATION;
5307 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005308 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5309 return BAD_VALUE;
5310 }
5311 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005312 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5313}
5314
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005315status_t Camera3Device::setAutoframingAutoBehavior(
5316 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5317 ATRACE_CALL();
5318 Mutex::Autolock il(mInterfaceLock);
5319 Mutex::Autolock l(mLock);
5320 if (mRequestThread == nullptr) {
5321 return INVALID_OPERATION;
5322 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005323 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
5324 return BAD_VALUE;
5325 }
5326 mAutoframingOverride = autoframingValue;
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005327 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5328}
5329
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005330bool Camera3Device::supportsCameraMute() {
5331 Mutex::Autolock il(mInterfaceLock);
5332 Mutex::Autolock l(mLock);
5333
5334 return mSupportCameraMute;
5335}
5336
5337status_t Camera3Device::setCameraMute(bool enabled) {
5338 ATRACE_CALL();
5339 Mutex::Autolock il(mInterfaceLock);
5340 Mutex::Autolock l(mLock);
5341
5342 if (mRequestThread == nullptr || !mSupportCameraMute) {
5343 return INVALID_OPERATION;
5344 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005345 int32_t muteMode =
5346 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5347 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5348 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5349 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005350}
5351
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005352status_t Camera3Device::injectCamera(const String8& injectedCamId,
5353 sp<CameraProviderManager> manager) {
5354 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5355 ATRACE_CALL();
5356 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005357 // When the camera device is active, injectCamera() and stopInjection() will call
5358 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5359 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5360 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5361 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5362 // waitUntilStateThenRelock().
5363 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005364
5365 status_t res = NO_ERROR;
5366 if (mInjectionMethods->isInjecting()) {
5367 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5368 return OK;
5369 } else {
5370 res = mInjectionMethods->stopInjection();
5371 if (res != OK) {
5372 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5373 __FUNCTION__, res);
5374 return res;
5375 }
5376 }
5377 }
5378
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005379 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005380 if (res != OK) {
5381 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5382 __FUNCTION__, res);
5383 return res;
5384 }
5385
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005386 // When the second display of android is cast to the remote device, and the opened camera is
5387 // also cast to the second display, in this case, because the camera has configured the streams
5388 // at this time, we can directly call injectCamera() to replace the internal camera with
5389 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005390 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5391 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5392
5393 camera3::camera_stream_configuration injectionConfig;
5394 std::vector<uint32_t> injectionBufferSizes;
5395 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5396 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5397 || injectionBufferSizes.size() <= 0) {
5398 ALOGE("Failed to inject camera due to abandoned configuration! "
5399 "mOperatingMode: %d injectionConfig.num_streams: %d "
5400 "injectionBufferSizes.size(): %zu", mOperatingMode,
5401 injectionConfig.num_streams, injectionBufferSizes.size());
5402 return DEAD_OBJECT;
5403 }
5404
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005405 res = mInjectionMethods->injectCamera(
5406 injectionConfig, injectionBufferSizes);
5407 if (res != OK) {
5408 ALOGE("Can't finish inject camera process!");
5409 return res;
5410 }
5411 }
5412
5413 return OK;
5414}
5415
5416status_t Camera3Device::stopInjection() {
5417 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5418 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005419 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005420 return mInjectionMethods->stopInjection();
5421}
5422
Shuzhen Wang16610a62022-12-15 22:38:07 -08005423void Camera3Device::overrideStreamUseCaseLocked() {
5424 if (mStreamUseCaseOverrides.size() == 0) {
5425 return;
5426 }
5427
5428 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5429 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5430 // Refer to CameraService::printHelp for details.
5431 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5432 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5433 outputStreamsIndices[i] = i;
5434 }
5435
5436 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5437 [&](int a, int b) -> bool {
5438
5439 auto formatScore = [](int format) {
5440 switch (format) {
5441 case HAL_PIXEL_FORMAT_BLOB:
5442 return 4;
5443 case HAL_PIXEL_FORMAT_RAW16:
5444 case HAL_PIXEL_FORMAT_RAW10:
5445 case HAL_PIXEL_FORMAT_RAW12:
5446 return 3;
5447 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5448 return 2;
5449 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5450 return 1;
5451 default:
5452 return 0;
5453 }
5454 };
5455
5456 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5457 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5458 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5459 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5460 if (sizeA > sizeB ||
5461 (sizeA == sizeB && formatAScore >= formatBScore)) {
5462 return true;
5463 } else {
5464 return false;
5465 }
5466 });
5467
5468 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5469 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5470 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5471 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5472 }
5473}
5474
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005475}; // namespace android