blob: 312f5bad9de0755871d098b88adc1d17706a39c9 [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>
Jayant Chowdhary44d5f622023-09-20 03:11:41 +000070#include <optional>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080071#include <tuple>
72
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080073using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Austin Borger74fca042022-05-23 12:41:21 -070078Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070079 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070080 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070082 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080083 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070084 mIsConstrainedHighSpeedConfiguration(false),
Emilian Peev15230142023-04-27 20:22:54 +000085 mIsCompositeJpegRDisabled(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070086 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070087 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070088 mUsePartialResult(false),
89 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080090 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080091 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070093 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070095 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070096 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070097 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000098 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010099 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -0700100 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700101 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -0700102 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800103 mOverrideToPortrait(overrideToPortrait),
Emilian Peevd865f0d2023-03-17 17:13:07 -0700104 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
105 mComposerOutput(false),
106 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700107 mSettingsOverride(-1),
Austin Borgerc8099762023-01-12 17:08:46 -0800108 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109{
110 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800112}
113
114Camera3Device::~Camera3Device()
115{
116 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700118 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800119}
120
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800121const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800122 return mId;
123}
124
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125status_t Camera3Device::initializeCommonLocked() {
126
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700127 /** Start up status tracker thread */
128 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700130 if (res != OK) {
131 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
132 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700134 mStatusTracker.clear();
135 return res;
136 }
137
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700138 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700139 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700140
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700141 if (mUseHalBufManager) {
142 res = mRequestBufferSM.initialize(mStatusTracker);
143 if (res != OK) {
144 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
145 strerror(-res), res);
146 mInterface->close();
147 mStatusTracker.clear();
148 return res;
149 }
150 }
151
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800152 /** Create buffer manager */
153 mBufferManager = new Camera3BufferManager();
154
155 Vector<int32_t> sessionParamKeys;
156 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
157 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
158 if (sessionKeysEntry.count > 0) {
159 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
160 }
161
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700162 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
163 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
164 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
165 if (availableTestPatternModes.data.i32[i] ==
166 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
167 mSupportCameraMute = true;
168 mSupportTestPatternSolidColor = true;
169 break;
170 } else if (availableTestPatternModes.data.i32[i] ==
171 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
172 mSupportCameraMute = true;
173 mSupportTestPatternSolidColor = false;
174 }
175 }
176
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700177 camera_metadata_entry_t availableSettingsOverrides = mDeviceInfo.find(
178 ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES);
179 for (size_t i = 0; i < availableSettingsOverrides.count; i++) {
180 if (availableSettingsOverrides.data.i32[i] ==
181 ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM) {
182 mSupportZoomOverride = true;
183 break;
184 }
185 }
186
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700187 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800188 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700189 this, mStatusTracker, mInterface, sessionParamKeys,
Shuzhen Wangaf22e912023-04-11 16:03:17 -0700190 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait,
191 mSupportZoomOverride);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800192 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800193 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700194 SET_ERR_L("Unable to start request queue thread: %s (%d)",
195 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800196 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800197 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800198 return res;
199 }
200
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700201 mPreparerThread = new PreparerThread();
202
Ruben Brunk183f0562015-08-12 12:55:02 -0700203 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800204 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400205 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700206 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700207 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800208 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800209
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800210 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800211 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800212 camera_metadata_entry timestampSource =
213 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
214 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
215 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800216 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800217 }
218
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700219 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100220 camera_metadata_entry partialResultsCount =
221 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
222 if (partialResultsCount.count > 0) {
223 mNumPartialResults = partialResultsCount.data.i32[0];
224 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700225 }
226
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800227 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
228 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700229 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700230 if (res != OK) {
231 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
232 return res;
233 }
234 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800235
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800236 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800237 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800238
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800239 if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700240 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
241 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
242 }
243
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800244 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
245 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
246 }
247
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800248 // Hidl/AidlCamera3DeviceInjectionMethods
249 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800250
Ravneetaeb20dc2022-03-30 05:33:03 +0000251 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800252 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700253 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
254 if (res != OK) {
255 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
256 strerror(-res), res);
257 return res;
258 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000259
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800260 return OK;
261}
262
263status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700264 return disconnectImpl();
265}
266
267status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800268 ATRACE_CALL();
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000269 Mutex::Autolock il(mInterfaceLock);
270
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700271 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800272
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700273 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700274 std::vector<wp<Camera3StreamInterface>> streams;
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000275 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000277 Mutex::Autolock l(mLock);
278 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000280 if (mRequestThread != NULL) {
281 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
282 res = mRequestThread->clear();
283 if (res != OK) {
284 SET_ERR_L("Can't stop streaming");
285 // Continue to close device even in case of error
286 } else {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000287 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
288 /*requestThreadInvocation*/ false);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800289 if (res != OK) {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000290 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
291 maxExpectedDuration);
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800292 // Continue to close device even in case of error
293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700295 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000296 // Signal to request thread that we're not expecting any
297 // more requests. This will be true since once we're in
298 // disconnect and we've cleared off the request queue, the
299 // request thread can't receive any new requests through
300 // binder calls - since disconnect holds
301 // mBinderSerialization lock.
302 mRequestThread->setRequestClearing();
303 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000305 if (mStatus == STATUS_ERROR) {
306 CLOGE("Shutting down in an error state");
307 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000309 if (mStatusTracker != NULL) {
310 mStatusTracker->requestExit();
311 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000313 if (mRequestThread != NULL) {
314 mRequestThread->requestExit();
315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000317 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
318 for (size_t i = 0; i < mOutputStreams.size(); i++) {
319 streams.push_back(mOutputStreams[i]);
320 }
321 if (mInputStream != nullptr) {
322 streams.push_back(mInputStream);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700323 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000325
326 // Joining done without holding mLock, otherwise deadlocks may ensue
327 // as the threads try to access parent state
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
329 // HAL may be in a bad state, so waiting for request thread
330 // (which may be stuck in the HAL processCaptureRequest call)
331 // could be dangerous.
332 mRequestThread->join();
333 }
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000334
335 if (mStatusTracker != NULL) {
336 mStatusTracker->join();
337 }
338
339 if (mInjectionMethods->isInjecting()) {
340 mInjectionMethods->stopInjection();
341 }
342
343 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 {
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000345 Mutex::Autolock l(mLock);
346 mRequestThread.clear();
347 Mutex::Autolock stLock(mTrackerLock);
348 mStatusTracker.clear();
349 interface = mInterface.get();
350 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800351
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000352 // Call close without internal mutex held, as the HAL close may need to
353 // wait on assorted callbacks,etc, to complete before it can return.
354 mCameraServiceWatchdog->WATCH(interface->close());
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800355
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000356 flushInflightRequests();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700357
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000358 {
359 Mutex::Autolock l(mLock);
360 mInterface->clear();
361 mOutputStreams.clear();
362 mInputStream.clear();
363 mDeletedStreams.clear();
364 mBufferManager.clear();
365 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
366 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700367
Bharatt Kukreja5681f782023-01-18 21:56:28 +0000368 for (auto& weakStream : streams) {
369 sp<Camera3StreamInterface> stream = weakStream.promote();
370 if (stream != nullptr) {
371 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
372 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700373 }
374 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700375 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000376
377 if (mCameraServiceWatchdog != NULL) {
378 mCameraServiceWatchdog->requestExit();
379 mCameraServiceWatchdog.clear();
380 }
381
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700382 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800383}
384
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385// For dumping/debugging only -
386// try to acquire a lock a few times, eventually give up to proceed with
387// debug/dump operations
388bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
389 bool gotLock = false;
390 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
391 if (lock.tryLock() == NO_ERROR) {
392 gotLock = true;
393 break;
394 } else {
395 usleep(kDumpSleepDuration);
396 }
397 }
398 return gotLock;
399}
400
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800401nsecs_t Camera3Device::getMonoToBoottimeOffset() {
402 // try three times to get the clock offset, choose the one
403 // with the minimum gap in measurements.
404 const int tries = 3;
405 nsecs_t bestGap, measured;
406 for (int i = 0; i < tries; ++i) {
407 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
408 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
409 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
410 const nsecs_t gap = tmono2 - tmono;
411 if (i == 0 || gap < bestGap) {
412 bestGap = gap;
413 measured = tbase - ((tmono + tmono2) >> 1);
414 }
415 }
416 return measured;
417}
418
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800419ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
420 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700421 // Get max jpeg size (area-wise) for default sensor pixel mode
422 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800423 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800424 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700425 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
426 // not ultra high res sensor
427 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800428 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700429 /*isUltraHighResolution*/true);
430 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800431 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
432 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700433 return BAD_VALUE;
434 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700435 bool useMaxSensorPixelModeThreshold = false;
436 if (uhrMaxJpegResolution.width != 0 &&
437 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
438 // Use the ultra high res max jpeg size and max jpeg buffer size
439 useMaxSensorPixelModeThreshold = true;
440 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700441
Zhijun Hef7da0962014-04-24 13:27:56 -0700442 // Get max jpeg buffer size
443 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800444 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700445 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800446 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
447 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700448 return BAD_VALUE;
449 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700450 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700451
452 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
453 if (useMaxSensorPixelModeThreshold) {
454 maxJpegBufferSize =
455 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
456 maxDefaultJpegResolution, maxJpegBufferSize);
457 chosenMaxJpegResolution = uhrMaxJpegResolution;
458 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800459 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700460
461 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700462 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700463 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800464 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
465 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700466 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800467 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
468 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700469 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700470 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700471 return jpegBufferSize;
472}
473
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800474ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700475 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800476 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700477 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800478 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
479 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700480 return BAD_VALUE;
481 }
482 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
483 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
484 return maxBytesForPointCloud;
485}
486
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800487ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
488 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800489 const int PER_CONFIGURATION_SIZE = 3;
490 const int WIDTH_OFFSET = 0;
491 const int HEIGHT_OFFSET = 1;
492 const int SIZE_OFFSET = 2;
493 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800494 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800495 camera3::SessionConfigurationUtils::getAppropriateModeTag(
496 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
497 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800498 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800499 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
501 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800502 return BAD_VALUE;
503 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700504
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800505 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
506 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
507 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
508 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
509 }
510 }
511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
513 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800514 return BAD_VALUE;
515}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700516
Jing Mikec7f9b132023-03-12 11:12:04 +0800517status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800518 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700519
520 // Try to lock, but continue in case of failure (to avoid blocking in
521 // deadlocks)
522 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
523 bool gotLock = tryLockSpinRightRound(mLock);
524
525 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800526 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
527 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700528 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800529 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
530 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700531
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800532 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700533
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800534 String16 templatesOption("-t");
535 int n = args.size();
536 for (int i = 0; i < n; i++) {
537 if (args[i] == templatesOption) {
538 dumpTemplates = true;
539 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000540 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700541 if (i + 1 < n) {
542 String8 monitorTags = String8(args[i + 1]);
543 if (monitorTags == "off") {
544 mTagMonitor.disableMonitoring();
545 } else {
546 mTagMonitor.parseTagsToMonitor(monitorTags);
547 }
548 } else {
549 mTagMonitor.disableMonitoring();
550 }
551 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800552 }
553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800555
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800556 const char *status =
557 mStatus == STATUS_ERROR ? "ERROR" :
558 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700559 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
560 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800561 mStatus == STATUS_ACTIVE ? "ACTIVE" :
562 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800564 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700565 if (mStatus == STATUS_ERROR) {
566 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
567 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800568 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800569 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000570 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
571 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
572 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800573 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800574
575 if (mInputStream != NULL) {
576 write(fd, lines.string(), lines.size());
577 mInputStream->dump(fd, args);
578 } else {
579 lines.appendFormat(" No input stream.\n");
580 write(fd, lines.string(), lines.size());
581 }
582 for (size_t i = 0; i < mOutputStreams.size(); i++) {
583 mOutputStreams[i]->dump(fd,args);
584 }
585
Zhijun He431503c2016-03-07 17:30:16 -0800586 if (mBufferManager != NULL) {
587 lines = String8(" Camera3 Buffer Manager:\n");
588 write(fd, lines.string(), lines.size());
589 mBufferManager->dump(fd, args);
590 }
Zhijun He125684a2015-12-26 15:07:30 -0800591
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700592 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700593 if (mInFlightLock.try_lock()) {
594 if (mInFlightMap.size() == 0) {
595 lines.append(" None\n");
596 } else {
597 for (size_t i = 0; i < mInFlightMap.size(); i++) {
598 InFlightRequest r = mInFlightMap.valueAt(i);
599 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
600 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
601 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
602 r.numBuffersLeft);
603 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700604 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700605 mInFlightLock.unlock();
606 } else {
607 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700608 }
609 write(fd, lines.string(), lines.size());
610
Shuzhen Wang686f6442017-06-20 16:16:04 -0700611 if (mRequestThread != NULL) {
612 mRequestThread->dumpCaptureRequestLatency(fd,
613 " ProcessCaptureRequest latency histogram:");
614 }
615
Igor Murashkin1e479c02013-09-06 16:55:14 -0700616 {
617 lines = String8(" Last request sent:\n");
618 write(fd, lines.string(), lines.size());
619
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700620 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700621 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
622 }
623
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700625 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 "TEMPLATE_PREVIEW",
627 "TEMPLATE_STILL_CAPTURE",
628 "TEMPLATE_VIDEO_RECORD",
629 "TEMPLATE_VIDEO_SNAPSHOT",
630 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800631 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800632 };
633
Emilian Peevf4816702020-04-03 15:44:51 -0700634 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 camera_metadata_t *templateRequest = nullptr;
636 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700637 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800638 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800640 lines.append(" Not supported\n");
641 write(fd, lines.string(), lines.size());
642 } else {
643 write(fd, lines.string(), lines.size());
644 dump_indented_camera_metadata(templateRequest,
645 fd, /*verbosity*/2, /*indentation*/8);
646 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800648 }
649 }
650
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700651 mTagMonitor.dumpMonitoredMetadata(fd);
652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800653 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800654 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800656 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800658
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700659 if (gotLock) mLock.unlock();
660 if (gotInterfaceLock) mInterfaceLock.unlock();
661
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800662 return OK;
663}
664
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700665status_t Camera3Device::startWatchingTags(const String8 &tags) {
666 mTagMonitor.parseTagsToMonitor(tags);
667 return OK;
668}
669
670status_t Camera3Device::stopWatchingTags() {
671 mTagMonitor.disableMonitoring();
672 return OK;
673}
674
675status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
676 mTagMonitor.getLatestMonitoredTagEvents(out);
677 return OK;
678}
679
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800680const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800681 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
683 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700684 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800685 mStatus == STATUS_ERROR ?
686 "when in error state" : "before init");
687 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700688 if (physicalId.isEmpty()) {
689 return mDeviceInfo;
690 } else {
691 std::string id(physicalId.c_str());
692 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
693 return mPhysicalDeviceInfoMap.at(id);
694 } else {
695 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
696 return mDeviceInfo;
697 }
698 }
699}
700
701const CameraMetadata& Camera3Device::info() const {
702 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800703 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800704}
705
Jianing Wei90e59c92014-03-12 18:29:36 -0700706status_t Camera3Device::checkStatusOkToCaptureLocked() {
707 switch (mStatus) {
708 case STATUS_ERROR:
709 CLOGE("Device has encountered a serious error");
710 return INVALID_OPERATION;
711 case STATUS_UNINITIALIZED:
712 CLOGE("Device not initialized");
713 return INVALID_OPERATION;
714 case STATUS_UNCONFIGURED:
715 case STATUS_CONFIGURED:
716 case STATUS_ACTIVE:
717 // OK
718 break;
719 default:
720 SET_ERR_L("Unexpected status: %d", mStatus);
721 return INVALID_OPERATION;
722 }
723 return OK;
724}
725
726status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000727 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700728 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700729 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700730 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700731 if (requestList == NULL) {
732 CLOGE("requestList cannot be NULL.");
733 return BAD_VALUE;
734 }
735
Jianing Weicb0652e2014-03-12 18:29:36 -0700736 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000737 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700738 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
739 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
740 ++metadataIt, ++surfaceMapIt) {
741 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 if (newRequest == 0) {
743 CLOGE("Can't create capture request");
744 return BAD_VALUE;
745 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700746
Shuzhen Wang9d066012016-09-30 11:30:20 -0700747 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700748 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700749
Jianing Weicb0652e2014-03-12 18:29:36 -0700750 // Setup burst Id and request Id
751 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800752 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
753 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700754 CLOGE("RequestID does not exist in metadata");
755 return BAD_VALUE;
756 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800757 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700758
Jianing Wei90e59c92014-03-12 18:29:36 -0700759 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700760
761 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700762 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700763 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
764 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
765 return BAD_VALUE;
766 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700767
768 // Setup batch size if this is a high speed video recording request.
769 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
770 auto firstRequest = requestList->begin();
771 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
772 if (outputStream->isVideoStream()) {
773 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800774 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700775 break;
776 }
777 }
778 }
779
Jianing Wei90e59c92014-03-12 18:29:36 -0700780 return OK;
781}
782
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800783status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800784 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800785
Emilian Peevaebbe412018-01-15 13:53:24 +0000786 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700787 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000788 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700789
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800790 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700791}
792
Emilian Peevaebbe412018-01-15 13:53:24 +0000793void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794 std::list<const SurfaceMap>& surfaceMaps,
795 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000796 PhysicalCameraSettingsList requestList;
797 requestList.push_back({std::string(getId().string()), request});
798 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700799
800 SurfaceMap surfaceMap;
801 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
802 // With no surface list passed in, stream and surface will have 1-to-1
803 // mapping. So the surface index is 0 for each stream in the surfaceMap.
804 for (size_t i = 0; i < streams.count; i++) {
805 surfaceMap[streams.data.i32[i]].push_back(0);
806 }
807 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800808}
809
Jianing Wei90e59c92014-03-12 18:29:36 -0700810status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000811 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700812 const std::list<const SurfaceMap> &surfaceMaps,
813 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700814 /*out*/
815 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700816 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700817 nsecs_t requestTimeNs = systemTime();
818
Jianing Wei90e59c92014-03-12 18:29:36 -0700819 Mutex::Autolock il(mInterfaceLock);
820 Mutex::Autolock l(mLock);
821
822 status_t res = checkStatusOkToCaptureLocked();
823 if (res != OK) {
824 // error logged by previous call
825 return res;
826 }
827
828 RequestList requestList;
829
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700831 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700832 if (res != OK) {
833 // error logged by previous call
834 return res;
835 }
836
837 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700838 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700839 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700840 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700841 }
842
843 if (res == OK) {
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000844 waitUntilStateThenRelock(/*active*/true, kActiveTimeout, /*requestThreadInvocation*/false);
Jianing Wei90e59c92014-03-12 18:29:36 -0700845 if (res != OK) {
846 SET_ERR_L("Can't transition to active in %f seconds!",
847 kActiveTimeout/1e9);
848 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800849 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700850 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 } else {
852 CLOGE("Cannot queue request. Impossible.");
853 return BAD_VALUE;
854 }
855
856 return res;
857}
858
Emilian Peevaebbe412018-01-15 13:53:24 +0000859status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700861 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700862 ATRACE_CALL();
863
Emilian Peevaebbe412018-01-15 13:53:24 +0000864 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700865}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800866
Jianing Weicb0652e2014-03-12 18:29:36 -0700867status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
868 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800869 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800870
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700872 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000873 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700874
Emilian Peevaebbe412018-01-15 13:53:24 +0000875 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700876 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800877}
878
Emilian Peevaebbe412018-01-15 13:53:24 +0000879status_t Camera3Device::setStreamingRequestList(
880 const List<const PhysicalCameraSettingsList> &requestsList,
881 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 ATRACE_CALL();
883
Emilian Peevaebbe412018-01-15 13:53:24 +0000884 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700885}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800886
887sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000888 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800889 status_t res;
890
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700891 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800892 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
893 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000894 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700895 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700896 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800897 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700898 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800899 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700900 } else if (mStatus == STATUS_UNCONFIGURED) {
901 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700902 CLOGE("No streams configured");
903 return NULL;
904 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800905 }
906
Shuzhen Wang0129d522016-10-30 22:43:41 -0700907 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800908 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800909}
910
Jianing Weicb0652e2014-03-12 18:29:36 -0700911status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800912 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700913 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800914 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800915
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800916 switch (mStatus) {
917 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700918 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800919 return INVALID_OPERATION;
920 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700921 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800922 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700923 case STATUS_UNCONFIGURED:
924 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800925 case STATUS_ACTIVE:
926 // OK
927 break;
928 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700929 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800930 return INVALID_OPERATION;
931 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800932 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700933
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700934 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800935}
936
937status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
938 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800940
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700941 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800942}
943
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700944status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800945 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700946 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700947 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700948 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700949 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800950 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
951 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952
953 status_t res;
954 bool wasActive = false;
955
956 switch (mStatus) {
957 case STATUS_ERROR:
958 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
959 return INVALID_OPERATION;
960 case STATUS_UNINITIALIZED:
961 ALOGE("%s: Device not initialized", __FUNCTION__);
962 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700963 case STATUS_UNCONFIGURED:
964 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700965 // OK
966 break;
967 case STATUS_ACTIVE:
968 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +0000969 res = internalPauseAndWaitLocked(maxExpectedDuration,
970 /*requestThreadInvocation*/ false);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700971 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700972 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700973 return res;
974 }
975 wasActive = true;
976 break;
977 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700978 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979 return INVALID_OPERATION;
980 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700981 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700982
983 if (mInputStream != 0) {
984 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
985 return INVALID_OPERATION;
986 }
987
988 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
989 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700990 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700991
992 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800993 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700994
995 *id = mNextStreamId++;
996
997 // Continue captures if active at start
998 if (wasActive) {
999 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001000 // Reuse current operating mode and session parameters for new stream config
1001 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001002 if (res != OK) {
1003 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1004 __FUNCTION__, mNextStreamId, strerror(-res), res);
1005 return res;
1006 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001007 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001008 }
1009
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001010 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001011 return OK;
1012}
1013
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001014status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001015 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001016 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001017 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001018 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1019 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001020 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001021 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001022 ATRACE_CALL();
1023
1024 if (consumer == nullptr) {
1025 ALOGE("%s: consumer must not be null", __FUNCTION__);
1026 return BAD_VALUE;
1027 }
1028
1029 std::vector<sp<Surface>> consumers;
1030 consumers.push_back(consumer);
1031
1032 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001033 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001034 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001035 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001036}
1037
1038static bool isRawFormat(int format) {
1039 switch (format) {
1040 case HAL_PIXEL_FORMAT_RAW16:
1041 case HAL_PIXEL_FORMAT_RAW12:
1042 case HAL_PIXEL_FORMAT_RAW10:
1043 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1044 return true;
1045 default:
1046 return false;
1047 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001048}
1049
1050status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1051 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001052 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001053 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001054 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001055 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001056 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001057 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001058
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001060 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001061 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001062 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001063 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001064 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001065 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001066 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001067 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001068 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1069 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 status_t res;
1072 bool wasActive = false;
1073
1074 switch (mStatus) {
1075 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001076 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 return INVALID_OPERATION;
1078 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001079 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001081 case STATUS_UNCONFIGURED:
1082 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083 // OK
1084 break;
1085 case STATUS_ACTIVE:
1086 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001087 res = internalPauseAndWaitLocked(maxExpectedDuration,
1088 /*requestThreadInvocation*/ false);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001089 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001090 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001091 return res;
1092 }
1093 wasActive = true;
1094 break;
1095 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001096 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001097 return INVALID_OPERATION;
1098 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001099 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100
1101 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001102
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 if (consumers.size() == 0 && !hasDeferredConsumer) {
1104 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1105 return BAD_VALUE;
1106 }
Zhijun He5d677d12016-05-29 16:52:39 -07001107
Shuzhen Wang0129d522016-10-30 22:43:41 -07001108 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001109 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1110 return BAD_VALUE;
1111 }
1112
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001113 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1114 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1115 // be found in only one sensor pixel mode.
1116 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1117 return BAD_VALUE;
1118 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001119 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001120 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001121 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001122 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001123 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001124 if (blobBufferSize <= 0) {
1125 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1126 return BAD_VALUE;
1127 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001128 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1129 blobBufferSize = width * height;
1130 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001131 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001132 if (blobBufferSize <= 0) {
1133 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1134 return BAD_VALUE;
1135 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001136 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001137 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001138 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001139 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001140 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001141 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001142 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001143 bool maxResolution =
1144 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1145 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001146 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1147 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001148 if (rawOpaqueBufferSize <= 0) {
1149 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1150 return BAD_VALUE;
1151 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001152 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001153 width, height, rawOpaqueBufferSize, format, 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);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001157 } else if (isShared) {
1158 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1159 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001160 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001161 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001162 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001163 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001164 newStream = new Camera3OutputStream(mNextStreamId,
1165 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001166 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001167 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001168 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001169 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001170 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001171 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001172 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001173 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001174 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 }
Emilian Peev40ead602017-09-26 15:46:36 +01001176
1177 size_t consumerCount = consumers.size();
1178 for (size_t i = 0; i < consumerCount; i++) {
1179 int id = newStream->getSurfaceId(consumers[i]);
1180 if (id < 0) {
1181 SET_ERR_L("Invalid surface id");
1182 return BAD_VALUE;
1183 }
1184 if (surfaceIds != nullptr) {
1185 surfaceIds->push_back(id);
1186 }
1187 }
1188
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190
Emilian Peev08dd2452017-04-06 16:55:14 +01001191 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001192
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001193 newStream->setImageDumpMask(mImageDumpMask);
1194
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 res = mOutputStreams.add(mNextStreamId, newStream);
1196 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001197 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 return res;
1199 }
1200
Shuzhen Wang316781a2020-08-18 18:11:01 -07001201 mSessionStatsBuilder.addStream(mNextStreamId);
1202
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001204 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205
1206 // Continue captures if active at start
1207 if (wasActive) {
1208 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001209 // Reuse current operating mode and session parameters for new stream config
1210 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001212 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1213 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 return res;
1215 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001216 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001218 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
Emilian Peev710c1422017-08-30 11:19:38 +01001222status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001224 if (nullptr == streamInfo) {
1225 return BAD_VALUE;
1226 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001229
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 switch (mStatus) {
1231 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
1234 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001235 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 case STATUS_UNCONFIGURED:
1238 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 case STATUS_ACTIVE:
1240 // OK
1241 break;
1242 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001243 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 return INVALID_OPERATION;
1245 }
1246
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001247 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1248 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001249 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001250 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 }
1252
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001253 streamInfo->width = stream->getWidth();
1254 streamInfo->height = stream->getHeight();
1255 streamInfo->format = stream->getFormat();
1256 streamInfo->dataSpace = stream->getDataSpace();
1257 streamInfo->formatOverridden = stream->isFormatOverridden();
1258 streamInfo->originalFormat = stream->getOriginalFormat();
1259 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1260 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001261 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001262 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001264}
1265
1266status_t Camera3Device::setStreamTransform(int id,
1267 int transform) {
1268 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001269 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001271
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 switch (mStatus) {
1273 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001274 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return INVALID_OPERATION;
1276 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001277 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 case STATUS_UNCONFIGURED:
1280 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 case STATUS_ACTIVE:
1282 // OK
1283 break;
1284 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001285 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001286 return INVALID_OPERATION;
1287 }
1288
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001289 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1290 if (stream == nullptr) {
1291 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 return BAD_VALUE;
1293 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001294 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001295}
1296
1297status_t Camera3Device::deleteStream(int id) {
1298 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001300 Mutex::Autolock l(mLock);
1301 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001302
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001303 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001305 // CameraDevice semantics require device to already be idle before
1306 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001307 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001308 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001309 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310 }
1311
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001312 if (mStatus == STATUS_ERROR) {
1313 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1314 __FUNCTION__, mId.string());
1315 return -EBUSY;
1316 }
1317
Igor Murashkin2fba5842013-04-22 14:03:54 -07001318 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001319 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001320 if (mInputStream != NULL && id == mInputStream->getId()) {
1321 deletedStream = mInputStream;
1322 mInputStream.clear();
1323 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001324 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001325 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001326 return BAD_VALUE;
1327 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001328 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001329 }
1330
1331 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001332 if (stream != nullptr) {
1333 deletedStream = stream;
1334 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001335 }
1336
1337 // Free up the stream endpoint so that it can be used by some other stream
1338 res = deletedStream->disconnect();
1339 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001340 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 // fall through since we want to still list the stream as deleted.
1342 }
1343 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001344 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345
1346 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001347}
1348
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001349status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001350 ATRACE_CALL();
1351 ALOGV("%s: E", __FUNCTION__);
1352
1353 Mutex::Autolock il(mInterfaceLock);
1354 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001355
Emilian Peev811d2952018-05-25 11:08:40 +01001356 // In case the client doesn't include any session parameter, try a
1357 // speculative configuration using the values from the last cached
1358 // default request.
1359 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001360 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001361 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1362 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1363 mLastTemplateId);
1364 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1365 operatingMode);
1366 }
1367
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001368 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1369}
1370
1371status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1372 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001373 //Filter out any incoming session parameters
1374 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001375 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1376 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001377 CameraMetadata filteredParams(availableSessionKeys.count);
1378 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1379 filteredParams.getAndLock());
1380 set_camera_metadata_vendor_id(meta, mVendorTagId);
1381 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001382 if (availableSessionKeys.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001383 bool rotateAndCropSessionKey = false;
1384 bool autoframingSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001385 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1386 camera_metadata_ro_entry entry = params.find(
1387 availableSessionKeys.data.i32[i]);
1388 if (entry.count > 0) {
1389 filteredParams.update(entry);
1390 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07001391 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1392 rotateAndCropSessionKey = true;
1393 }
1394 if (ANDROID_CONTROL_AUTOFRAMING == availableSessionKeys.data.i32[i]) {
1395 autoframingSessionKey = true;
1396 }
1397 }
1398
1399 if (rotateAndCropSessionKey || autoframingSessionKey) {
1400 sp<CaptureRequest> request = new CaptureRequest();
1401 PhysicalCameraSettings settingsList;
1402 settingsList.metadata = filteredParams;
1403 request->mSettingsList.push_back(settingsList);
1404
1405 if (rotateAndCropSessionKey) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07001406 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1407 if (rotateAndCropEntry.count > 0 &&
1408 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1409 request->mRotateAndCropAuto = true;
1410 } else {
1411 request->mRotateAndCropAuto = false;
1412 }
1413
1414 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1415 }
1416
1417 if (autoframingSessionKey) {
1418 auto autoframingEntry = filteredParams.find(ANDROID_CONTROL_AUTOFRAMING);
1419 if (autoframingEntry.count > 0 &&
1420 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
1421 overrideAutoframing(request, mAutoframingOverride);
1422 }
1423 }
1424
1425 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001426 }
1427 }
1428
1429 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001430}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001431
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001432status_t Camera3Device::getInputBufferProducer(
1433 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001434 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001435 Mutex::Autolock il(mInterfaceLock);
1436 Mutex::Autolock l(mLock);
1437
1438 if (producer == NULL) {
1439 return BAD_VALUE;
1440 } else if (mInputStream == NULL) {
1441 return INVALID_OPERATION;
1442 }
1443
1444 return mInputStream->getInputBufferProducer(producer);
1445}
1446
Emilian Peevf4816702020-04-03 15:44:51 -07001447status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001448 CameraMetadata *request) {
1449 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001450 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001451
Emilian Peevf4816702020-04-03 15:44:51 -07001452 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001453 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001454 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001455 return BAD_VALUE;
1456 }
1457
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001458 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001460 {
1461 Mutex::Autolock l(mLock);
1462 switch (mStatus) {
1463 case STATUS_ERROR:
1464 CLOGE("Device has encountered a serious error");
1465 return INVALID_OPERATION;
1466 case STATUS_UNINITIALIZED:
1467 CLOGE("Device is not initialized!");
1468 return INVALID_OPERATION;
1469 case STATUS_UNCONFIGURED:
1470 case STATUS_CONFIGURED:
1471 case STATUS_ACTIVE:
1472 // OK
1473 break;
1474 default:
1475 SET_ERR_L("Unexpected status: %d", mStatus);
1476 return INVALID_OPERATION;
1477 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001479 if (!mRequestTemplateCache[templateId].isEmpty()) {
1480 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001481 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001482 return OK;
1483 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001484 }
1485
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001486 camera_metadata_t *rawRequest;
1487 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001488 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489
1490 {
1491 Mutex::Autolock l(mLock);
1492 if (res == BAD_VALUE) {
1493 ALOGI("%s: template %d is not supported on this camera device",
1494 __FUNCTION__, templateId);
1495 return res;
1496 } else if (res != OK) {
1497 CLOGE("Unable to construct request template %d: %s (%d)",
1498 templateId, strerror(-res), res);
1499 return res;
1500 }
1501
1502 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1503 mRequestTemplateCache[templateId].acquire(rawRequest);
1504
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001505 // Override the template request with zoomRatioMapper
1506 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1507 &mRequestTemplateCache[templateId]);
1508 if (res != OK) {
1509 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1510 templateId, strerror(-res), res);
1511 return res;
1512 }
1513
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001514 // Fill in JPEG_QUALITY if not available
1515 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1516 static const uint8_t kDefaultJpegQuality = 95;
1517 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1518 &kDefaultJpegQuality, 1);
1519 }
1520
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001521 // Fill in AUTOFRAMING if not available
1522 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1523 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1524 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1525 &kDefaultAutoframingMode, 1);
1526 }
1527
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001528 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001529 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001530 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001531 return OK;
1532}
1533
1534status_t Camera3Device::waitUntilDrained() {
1535 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001537 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001539
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001540 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001541}
1542
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001543status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 switch (mStatus) {
1545 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 ALOGV("%s: Already idle", __FUNCTION__);
1548 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 case STATUS_CONFIGURED:
1550 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 case STATUS_ERROR:
1552 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 break;
1555 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return INVALID_OPERATION;
1558 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001559 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1560 maxExpectedDuration);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001561 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1562 /*requestThreadInvocation*/ false);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001563 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001564 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001565 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1566 res);
1567 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 return res;
1569}
1570
Ruben Brunk183f0562015-08-12 12:55:02 -07001571void Camera3Device::internalUpdateStatusLocked(Status status) {
1572 mStatus = status;
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001573 mStatusIsInternal = mPauseStateNotify ? true : false;
1574 mRecentStatusUpdates.add({mStatus, mStatusIsInternal});
Ruben Brunk183f0562015-08-12 12:55:02 -07001575 mStatusChanged.broadcast();
1576}
1577
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578// Pause to reconfigure
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001579status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration,
1580 bool requestThreadInvocation) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001581 if (mRequestThread.get() != nullptr) {
1582 mRequestThread->setPaused(true);
1583 } else {
1584 return NO_INIT;
1585 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001587 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1588 maxExpectedDuration);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001589 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
1590 requestThreadInvocation);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001592 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001593 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001594 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001595 }
1596
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 return res;
1598}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600// Resume after internalPauseAndWaitLocked
1601status_t Camera3Device::internalResumeLocked() {
1602 status_t res;
1603
1604 mRequestThread->setPaused(false);
1605
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001606 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1607 kActiveTimeout);
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001608 // internalResumeLocked is always called from a binder thread.
1609 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout,
1610 /*requestThreadInvocation*/ false);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001611 if (res != OK) {
1612 SET_ERR_L("Can't transition to active in %f seconds!",
1613 kActiveTimeout/1e9);
1614 }
1615 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617}
1618
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001619status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout,
1620 bool requestThreadInvocation) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001622
1623 size_t startIndex = 0;
1624 if (mStatusWaiters == 0) {
1625 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1626 // this status list
1627 mRecentStatusUpdates.clear();
1628 } else {
1629 // If other threads are waiting on updates to this status list, set the position of the
1630 // first element that this list will check rather than clearing the list.
1631 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001632 }
1633
Ruben Brunk183f0562015-08-12 12:55:02 -07001634 mStatusWaiters++;
1635
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001636 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001637 if (!active && mUseHalBufManager) {
1638 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001639 if (mStatus == STATUS_ACTIVE) {
1640 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001641 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001642 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001643 mRequestBufferSM.onWaitUntilIdle();
1644 }
1645
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001646 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001647 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001648 do {
Shuzhen Wang376f04c2023-06-06 04:50:01 +00001649 if (mStatus == STATUS_ERROR) {
1650 // Device in error state. Return right away.
1651 break;
1652 }
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001653 if (active == (mStatus == STATUS_ACTIVE) &&
1654 (requestThreadInvocation || !mStatusIsInternal)) {
Ruben Brunk183f0562015-08-12 12:55:02 -07001655 // Desired state is current
1656 break;
1657 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001659 nsecs_t timeElapsed = systemTime() - startTime;
1660 nsecs_t timeToWait = timeout - timeElapsed;
1661 if (timeToWait <= 0) {
1662 // Thread woke up spuriously but has timed out since.
1663 // Force out of loop with TIMED_OUT result.
1664 res = TIMED_OUT;
1665 break;
1666 }
1667 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001668 if (res != OK) break;
1669
Ruben Brunk183f0562015-08-12 12:55:02 -07001670 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1671 // transitions.
1672 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1673 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1674 __FUNCTION__);
1675
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001676 // Encountered desired state since we began waiting. Internal invocations coming from
1677 // request threads (such as reconfigureCamera) should be woken up immediately, whereas
1678 // invocations from binder threads (such as createInputStream) should only be woken up if
1679 // they are not paused. This avoids intermediate pause signals from reconfigureCamera as it
1680 // changes the status to active right after.
Ruben Brunk183f0562015-08-12 12:55:02 -07001681 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Shuzhen Wang376f04c2023-06-06 04:50:01 +00001682 if (mRecentStatusUpdates[i].status == STATUS_ERROR) {
1683 // Device in error state. Return right away.
1684 stateSeen = true;
1685 break;
1686 }
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00001687 if (active == (mRecentStatusUpdates[i].status == STATUS_ACTIVE) &&
1688 (requestThreadInvocation || !mRecentStatusUpdates[i].isInternal)) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001689 stateSeen = true;
1690 break;
1691 }
1692 }
1693 } while (!stateSeen);
1694
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001695 if (signalPipelineDrain) {
1696 mRequestThread->resetPipelineDrain();
1697 }
1698
Ruben Brunk183f0562015-08-12 12:55:02 -07001699 mStatusWaiters--;
1700
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001701 return res;
1702}
1703
1704
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001705status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001706 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001707 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001709 if (listener != NULL && mListener != NULL) {
1710 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1711 }
1712 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001713 mRequestThread->setNotificationListener(listener);
1714 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001715
1716 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001717}
1718
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001719bool Camera3Device::willNotify3A() {
1720 return false;
1721}
1722
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001724 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001725 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001726
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001727 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001728 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1729 if (st == std::cv_status::timeout) {
1730 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001731 }
1732 }
1733 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001734}
1735
Jianing Weicb0652e2014-03-12 18:29:36 -07001736status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001737 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001738 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001739
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001740 if (mResultQueue.empty()) {
1741 return NOT_ENOUGH_DATA;
1742 }
1743
Jianing Weicb0652e2014-03-12 18:29:36 -07001744 if (frame == NULL) {
1745 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1746 return BAD_VALUE;
1747 }
1748
1749 CaptureResult &result = *(mResultQueue.begin());
1750 frame->mResultExtras = result.mResultExtras;
1751 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001752 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001753 mResultQueue.erase(mResultQueue.begin());
1754
1755 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001756}
1757
1758status_t Camera3Device::triggerAutofocus(uint32_t id) {
1759 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001762 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1763 // Mix-in this trigger into the next request and only the next request.
1764 RequestTrigger trigger[] = {
1765 {
1766 ANDROID_CONTROL_AF_TRIGGER,
1767 ANDROID_CONTROL_AF_TRIGGER_START
1768 },
1769 {
1770 ANDROID_CONTROL_AF_TRIGGER_ID,
1771 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001772 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001773 };
1774
1775 return mRequestThread->queueTrigger(trigger,
1776 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001777}
1778
1779status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1780 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001781 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001782
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001783 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1784 // Mix-in this trigger into the next request and only the next request.
1785 RequestTrigger trigger[] = {
1786 {
1787 ANDROID_CONTROL_AF_TRIGGER,
1788 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1789 },
1790 {
1791 ANDROID_CONTROL_AF_TRIGGER_ID,
1792 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001793 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001794 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001795
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001796 return mRequestThread->queueTrigger(trigger,
1797 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001798}
1799
1800status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1801 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001803
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001804 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1805 // Mix-in this trigger into the next request and only the next request.
1806 RequestTrigger trigger[] = {
1807 {
1808 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1809 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1810 },
1811 {
1812 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1813 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001814 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001815 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001816
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001817 return mRequestThread->queueTrigger(trigger,
1818 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001819}
1820
Jianing Weicb0652e2014-03-12 18:29:36 -07001821status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001822 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001823 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001825
Zhijun He7ef20392014-04-21 16:04:17 -07001826 {
1827 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001828
1829 // b/116514106 "disconnect()" can get called twice for the same device. The
1830 // camera device will not be initialized during the second run.
1831 if (mStatus == STATUS_UNINITIALIZED) {
1832 return OK;
1833 }
1834
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001835 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001836
1837 // Stop session and stream counter
1838 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001839 }
1840
Ravneetdbd5b242022-03-02 07:22:46 +00001841 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001842 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001843 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1844 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1845
1846 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001847}
1848
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001849status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001850 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1851}
1852
1853status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001854 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001855 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001856 Mutex::Autolock il(mInterfaceLock);
1857 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001858
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001859 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1860 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001861 CLOGE("Stream %d does not exist", streamId);
1862 return BAD_VALUE;
1863 }
1864
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001865 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001866 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001867 return BAD_VALUE;
1868 }
1869
1870 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001871 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001872 return BAD_VALUE;
1873 }
1874
Ruben Brunkc78ac262015-08-13 17:58:46 -07001875 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001876}
1877
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001878status_t Camera3Device::tearDown(int streamId) {
1879 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001880 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001881 Mutex::Autolock il(mInterfaceLock);
1882 Mutex::Autolock l(mLock);
1883
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001884 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1885 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001886 CLOGE("Stream %d does not exist", streamId);
1887 return BAD_VALUE;
1888 }
1889
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001890 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1891 CLOGE("Stream %d is a target of a in-progress request", streamId);
1892 return BAD_VALUE;
1893 }
1894
1895 return stream->tearDown();
1896}
1897
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001898status_t Camera3Device::addBufferListenerForStream(int streamId,
1899 wp<Camera3StreamBufferListener> listener) {
1900 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001901 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001902 Mutex::Autolock il(mInterfaceLock);
1903 Mutex::Autolock l(mLock);
1904
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001905 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1906 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001907 CLOGE("Stream %d does not exist", streamId);
1908 return BAD_VALUE;
1909 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001910 stream->addBufferListener(listener);
1911
1912 return OK;
1913}
1914
Austin Borger4a870a32022-02-25 01:48:41 +00001915float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1916 camera_metadata_entry minDurations =
1917 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1918 for (size_t i = 0; i < minDurations.count; i += 4) {
Shuzhen Wangfa23af12023-05-31 19:14:03 +00001919 if (minDurations.data.i64[i] == stream->getOriginalFormat()
Austin Borger4a870a32022-02-25 01:48:41 +00001920 && minDurations.data.i64[i+1] == stream->getWidth()
1921 && minDurations.data.i64[i+2] == stream->getHeight()) {
1922 int64_t minFrameDuration = minDurations.data.i64[i+3];
1923 return 1e9f / minFrameDuration;
1924 }
1925 }
1926 return 0.0f;
1927}
1928
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001929/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001930 * Methods called by subclasses
1931 */
1932
1933void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001934 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001935 std::vector<int> streamIds;
1936 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001937 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001938
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001939 {
1940 // Need mLock to safely update state and synchronize to current
1941 // state of methods in flight.
1942 Mutex::Autolock l(mLock);
1943 // We can get various system-idle notices from the status tracker
1944 // while starting up. Only care about them if we've actually sent
1945 // in some requests recently.
1946 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1947 return;
1948 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001949 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1950 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001951 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001952
1953 // Skip notifying listener if we're doing some user-transparent
1954 // state changes
1955 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001956
Austin Borger4a870a32022-02-25 01:48:41 +00001957 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1958 auto stream = mOutputStreams[i];
1959 if (stream.get() == nullptr) continue;
1960
1961 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1962 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1963
1964 // Populate stream statistics in case of Idle
1965 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001966 streamIds.push_back(stream->getId());
1967 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1968 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001969 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001970 if (camera3Stream != nullptr) {
1971 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001972 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001973 }
1974 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001975 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001976 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001977 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001978 stream->getDynamicRangeProfile(), streamUseCase,
1979 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001980 }
1981 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001982 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001983
1984 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001985 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001986 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001987 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001988 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001989 status_t res = OK;
1990 if (listener != nullptr) {
1991 if (idle) {
1992 // Get session stats from the builder, and notify the listener.
1993 int64_t requestCount, resultErrorCount;
1994 bool deviceError;
1995 std::map<int, StreamStats> streamStatsMap;
1996 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1997 &deviceError, &streamStatsMap);
1998 for (size_t i = 0; i < streamIds.size(); i++) {
1999 int streamId = streamIds[i];
2000 auto stats = streamStatsMap.find(streamId);
2001 if (stats != streamStatsMap.end()) {
2002 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2003 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2004 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2005 streamStats[i].mHistogramType =
2006 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2007 streamStats[i].mHistogramBins.assign(
2008 stats->second.mCaptureLatencyBins.begin(),
2009 stats->second.mCaptureLatencyBins.end());
2010 streamStats[i].mHistogramCounts.assign(
2011 stats->second.mCaptureLatencyHistogram.begin(),
2012 stats->second.mCaptureLatencyHistogram.end());
2013 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002014 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002015 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
2016 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00002017 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002018 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07002019 }
2020 if (res != OK) {
2021 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
2022 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002023 }
2024}
2025
Shuzhen Wang758c2152017-01-10 18:26:18 -08002026status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002027 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002028 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002029 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2030 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002031
2032 if (surfaceIds == nullptr) {
2033 return BAD_VALUE;
2034 }
2035
Zhijun He5d677d12016-05-29 16:52:39 -07002036 Mutex::Autolock il(mInterfaceLock);
2037 Mutex::Autolock l(mLock);
2038
Shuzhen Wang758c2152017-01-10 18:26:18 -08002039 if (consumers.size() == 0) {
2040 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002041 return BAD_VALUE;
2042 }
2043
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002044 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2045 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002046 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002047 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002048 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002049
2050 // isConsumerConfigurationDeferred will be off after setConsumers
2051 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002052 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002053 if (res != OK) {
2054 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2055 return res;
2056 }
2057
Emilian Peev40ead602017-09-26 15:46:36 +01002058 for (auto &consumer : consumers) {
2059 int id = stream->getSurfaceId(consumer);
2060 if (id < 0) {
2061 CLOGE("Invalid surface id!");
2062 return BAD_VALUE;
2063 }
2064 surfaceIds->push_back(id);
2065 }
2066
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002067 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002068 if (!stream->isConfiguring()) {
2069 CLOGE("Stream %d was already fully configured.", streamId);
2070 return INVALID_OPERATION;
2071 }
Zhijun He5d677d12016-05-29 16:52:39 -07002072
Shuzhen Wang0129d522016-10-30 22:43:41 -07002073 res = stream->finishConfiguration();
2074 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002075 // If finishConfiguration fails due to abandoned surface, do not set
2076 // device to error state.
2077 bool isSurfaceAbandoned =
2078 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2079 if (!isSurfaceAbandoned) {
2080 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2081 stream->getId(), strerror(-res), res);
2082 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002083 return res;
2084 }
Zhijun He5d677d12016-05-29 16:52:39 -07002085 }
2086
2087 return OK;
2088}
2089
Emilian Peev40ead602017-09-26 15:46:36 +01002090status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2091 const std::vector<OutputStreamInfo> &outputInfo,
2092 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2093 Mutex::Autolock il(mInterfaceLock);
2094 Mutex::Autolock l(mLock);
2095
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002096 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2097 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002098 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002099 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002100 }
2101
2102 for (const auto &it : removedSurfaceIds) {
2103 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2104 CLOGE("Shared surface still part of a pending request!");
2105 return -EBUSY;
2106 }
2107 }
2108
Emilian Peev40ead602017-09-26 15:46:36 +01002109 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2110 if (res != OK) {
2111 CLOGE("Stream %d failed to update stream (error %d %s) ",
2112 streamId, res, strerror(-res));
2113 if (res == UNKNOWN_ERROR) {
2114 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2115 __FUNCTION__);
2116 }
2117 return res;
2118 }
2119
2120 return res;
2121}
2122
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002123status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2124 Mutex::Autolock il(mInterfaceLock);
2125 Mutex::Autolock l(mLock);
2126
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002127 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2128 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002129 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2130 return BAD_VALUE;
2131 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002132
2133 if (dropping) {
2134 mSessionStatsBuilder.stopCounter(streamId);
2135 } else {
2136 mSessionStatsBuilder.startCounter(streamId);
2137 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002138 return stream->dropBuffers(dropping);
2139}
2140
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 * Camera3Device private methods
2143 */
2144
2145sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002146 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002147 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002149 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002150 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151
2152 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002153 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002154 if (inputStreams.count > 0) {
2155 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002156 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002157 CLOGE("Request references unknown input stream %d",
2158 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002159 return NULL;
2160 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002161
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002163 SET_ERR_L("%s: input stream %d is not configured!",
2164 __FUNCTION__, mInputStream->getId());
2165 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002167 // Check if stream prepare is blocking requests.
2168 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002169 CLOGE("Request references an input stream that's being prepared!");
2170 return NULL;
2171 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002172
2173 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002174 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175 }
2176
2177 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002178 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002179 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002180 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181 return NULL;
2182 }
2183
2184 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002185 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2186 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002187 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002188 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002189 return NULL;
2190 }
Zhijun He5d677d12016-05-29 16:52:39 -07002191 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002192 auto iter = surfaceMap.find(streams.data.i32[i]);
2193 if (iter != surfaceMap.end()) {
2194 const std::vector<size_t>& surfaces = iter->second;
2195 for (const auto& surface : surfaces) {
2196 if (stream->isConsumerConfigurationDeferred(surface)) {
2197 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2198 "due to deferred consumer", stream->getId(), surface);
2199 return NULL;
2200 }
2201 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002202 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002203 }
2204
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002205 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002206 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2207 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002208 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002209 // Check if stream prepare is blocking requests.
2210 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002211 CLOGE("Request references an output stream that's being prepared!");
2212 return NULL;
2213 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002214
2215 newRequest->mOutputStreams.push(stream);
2216 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002217 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002218 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002219
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002220 auto rotateAndCropEntry =
2221 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2222 if (rotateAndCropEntry.count > 0 &&
2223 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2224 newRequest->mRotateAndCropAuto = true;
2225 } else {
2226 newRequest->mRotateAndCropAuto = false;
2227 }
2228
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002229 auto autoframingEntry =
2230 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2231 if (autoframingEntry.count > 0 &&
2232 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2233 newRequest->mAutoframingAuto = true;
2234 } else {
2235 newRequest->mAutoframingAuto = false;
2236 }
2237
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002238 auto zoomRatioEntry =
2239 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2240 if (zoomRatioEntry.count > 0 &&
2241 zoomRatioEntry.data.f[0] == 1.0f) {
2242 newRequest->mZoomRatioIs1x = true;
2243 } else {
2244 newRequest->mZoomRatioIs1x = false;
2245 }
2246
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002247 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002248 for (auto& settings : newRequest->mSettingsList) {
2249 auto testPatternModeEntry =
2250 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2251 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2252 testPatternModeEntry.data.i32[0] :
2253 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002254
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002255 auto testPatternDataEntry =
2256 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2257 if (testPatternDataEntry.count >= 4) {
2258 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2259 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2260 } else {
2261 settings.mOriginalTestPatternData[0] = 0;
2262 settings.mOriginalTestPatternData[1] = 0;
2263 settings.mOriginalTestPatternData[2] = 0;
2264 settings.mOriginalTestPatternData[3] = 0;
2265 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002266 }
2267 }
2268
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002269 if (mSupportZoomOverride) {
2270 for (auto& settings : newRequest->mSettingsList) {
2271 auto settingsOverrideEntry =
2272 settings.metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
2273 settings.mOriginalSettingsOverride = settingsOverrideEntry.count > 0 ?
2274 settingsOverrideEntry.data.i32[0] :
2275 ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
2276 }
2277 }
2278
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002280}
2281
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002282void Camera3Device::cancelStreamsConfigurationLocked() {
2283 int res = OK;
2284 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2285 res = mInputStream->cancelConfiguration();
2286 if (res != OK) {
2287 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2288 mInputStream->getId(), strerror(-res), res);
2289 }
2290 }
2291
2292 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002293 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002294 if (outputStream->isConfiguring()) {
2295 res = outputStream->cancelConfiguration();
2296 if (res != OK) {
2297 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2298 outputStream->getId(), strerror(-res), res);
2299 }
2300 }
2301 }
2302
2303 // Return state to that at start of call, so that future configures
2304 // properly clean things up
2305 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2306 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002307
2308 res = mPreparerThread->resume();
2309 if (res != OK) {
2310 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2311 }
2312}
2313
Emilian Peev0d0191e2020-04-21 17:01:18 -07002314bool Camera3Device::checkAbandonedStreamsLocked() {
2315 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2316 return true;
2317 }
2318
2319 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2320 auto stream = mOutputStreams[i];
2321 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2322 return true;
2323 }
2324 }
2325
2326 return false;
2327}
2328
Emilian Peev3bead5f2020-05-28 17:29:08 -07002329bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002330 ATRACE_CALL();
2331 bool ret = false;
2332
Shuzhen Wang316781a2020-08-18 18:11:01 -07002333 nsecs_t startTime = systemTime();
2334
Bharatt Kukreja5681f782023-01-18 21:56:28 +00002335 // We must not hold mInterfaceLock here since this function is called from
2336 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2337 // deadlocks (http://b/143513518)
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002338 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2339
2340 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002341 if (checkAbandonedStreamsLocked()) {
2342 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2343 __FUNCTION__);
2344 return true;
2345 }
2346
Emilian Peev3bead5f2020-05-28 17:29:08 -07002347 status_t rc = NO_ERROR;
2348 bool markClientActive = false;
2349 if (mStatus == STATUS_ACTIVE) {
2350 markClientActive = true;
2351 mPauseStateNotify = true;
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00002352 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
Emilian Peev3bead5f2020-05-28 17:29:08 -07002353
Bharatt Kukrejaf6f0ca12023-01-26 19:56:30 +00002354 // This is essentially the same as calling rc = internalPauseAndWaitLocked(..), except that
2355 // we don't want to call setPaused(true) to avoid it interfering with setPaused() called
2356 // from createInputStream/createStream.
2357 rc = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration,
2358 /*requestThreadInvocation*/ true);
2359 if (rc != OK) {
2360 mStatusTracker->dumpActiveComponents();
2361 SET_ERR_L("Can't idle device in %f seconds!",
2362 maxExpectedDuration/1e9);
2363 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07002364 }
2365
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002366 if (rc == NO_ERROR) {
2367 mNeedConfig = true;
2368 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2369 if (rc == NO_ERROR) {
2370 ret = true;
2371 mPauseStateNotify = false;
2372 //Moving to active state while holding 'mLock' is important.
2373 //There could be pending calls to 'create-/deleteStream' which
2374 //will trigger another stream configuration while the already
2375 //present streams end up with outstanding buffers that will
2376 //not get drained.
2377 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang25152e42023-06-13 22:18:58 +00002378
2379 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode,
2380 true /*internalReconfig*/, ns2ms(systemTime() - startTime));
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002381 } else if (rc == DEAD_OBJECT) {
2382 // DEAD_OBJECT can be returned if either the consumer surface is
2383 // abandoned, or the HAL has died.
2384 // - If the HAL has died, configureStreamsLocked call will set
2385 // device to error state,
2386 // - If surface is abandoned, we should not set device to error
2387 // state.
2388 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002389 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002390 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002391 }
2392 } else {
2393 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2394 }
2395
Emilian Peev3bead5f2020-05-28 17:29:08 -07002396 if (markClientActive) {
2397 mStatusTracker->markComponentActive(clientStatusId);
2398 }
2399
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002400 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002401}
2402
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002403status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002404 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002405 ATRACE_CALL();
2406 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002407
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002408 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002409 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002410 return INVALID_OPERATION;
2411 }
2412
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002413 if (operatingMode < 0) {
2414 CLOGE("Invalid operating mode: %d", operatingMode);
2415 return BAD_VALUE;
2416 }
2417
2418 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002419 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002420
2421 if (mOperatingMode != operatingMode) {
2422 mNeedConfig = true;
2423 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2424 mOperatingMode = operatingMode;
2425 }
2426
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002427 // Reset min expected duration when session is reconfigured.
2428 mMinExpectedDuration = 0;
2429
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002430 // In case called from configureStreams, abort queued input buffers not belonging to
2431 // any pending requests.
2432 if (mInputStream != NULL && notifyRequestThread) {
2433 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002434 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002435 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002436 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002437 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002438 if (res != OK) {
2439 // Exhausted acquiring all input buffers.
2440 break;
2441 }
2442
Emilian Peevf4816702020-04-03 15:44:51 -07002443 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002444 res = mInputStream->returnInputBuffer(inputBuffer);
2445 if (res != OK) {
2446 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2447 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2448 }
2449 }
2450 }
2451
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002452 if (!mNeedConfig) {
2453 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2454 return OK;
2455 }
2456
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002457 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002458 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002459 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2460 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002461 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002462 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002463 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002464 }
2465
Shuzhen Wang16610a62022-12-15 22:38:07 -08002466 // Override stream use case based on "adb shell command"
2467 overrideStreamUseCaseLocked();
2468
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002469 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002470 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002471
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002472 mPreparerThread->pause();
2473
Emilian Peevf4816702020-04-03 15:44:51 -07002474 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002475 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002477 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478
Emilian Peevf4816702020-04-03 15:44:51 -07002479 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002480 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002481 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002482
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002483
2484 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002485 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002486 inputStream = mInputStream->startConfiguration();
2487 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002488 CLOGE("Can't start input stream configuration");
2489 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002490 return INVALID_OPERATION;
2491 }
2492 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002493
2494 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495 }
2496
Shuzhen Wang99080502021-03-07 21:08:20 -08002497 mGroupIdPhysicalCameraMap.clear();
Emilian Peevd865f0d2023-03-17 17:13:07 -07002498 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002499 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002500
2501 // Don't configure bidi streams twice, nor add them twice to the list
2502 if (mOutputStreams[i].get() ==
2503 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2504
2505 config.num_streams--;
2506 continue;
2507 }
2508
Emilian Peevf4816702020-04-03 15:44:51 -07002509 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002510 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002512 CLOGE("Can't start output stream configuration");
2513 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002514 return INVALID_OPERATION;
2515 }
2516 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002517
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002518 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002519 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2520 // always occupy the initial entry.
Emilian Peeve579d8b2023-02-28 14:16:08 -08002521 if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2522 (outputStream->data_space ==
2523 static_cast<android_dataspace_t>(
2524 aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002525 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002526 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2527 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002528 } else if (outputStream->data_space ==
2529 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2530 bufferSizes[k] = outputStream->width * outputStream->height;
2531 } else {
2532 ALOGW("%s: Blob dataSpace %d not supported",
2533 __FUNCTION__, outputStream->data_space);
2534 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002535 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002536
2537 if (mOutputStreams[i]->isMultiResolution()) {
2538 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2539 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2540 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2541 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002542
2543 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07002544 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002545 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002546 }
2547
2548 config.streams = streams.editArray();
2549
2550 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002551 // max_buffers, usage, and priv fields, as well as data_space and format
2552 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002553
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002554 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002555 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002556 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002557 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002558
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002559 if (res == BAD_VALUE) {
2560 // HAL rejected this set of streams as unsupported, clean up config
2561 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002562 CLOGE("Set of requested inputs/outputs not supported by HAL");
2563 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002564 return BAD_VALUE;
2565 } else if (res != OK) {
2566 // Some other kind of error from configure_streams - this is not
2567 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002568 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2569 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002570 return res;
2571 }
2572
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002573 // Finish all stream configuration immediately.
2574 // TODO: Try to relax this later back to lazy completion, which should be
2575 // faster
2576
Igor Murashkin073f8572013-05-02 14:59:28 -07002577 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002578 bool streamReConfigured = false;
2579 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002580 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002581 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002582 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002583 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002584 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2585 return DEAD_OBJECT;
2586 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002587 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002588 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002589 if (streamReConfigured) {
2590 mInterface->onStreamReConfigured(mInputStream->getId());
2591 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002592 }
2593
2594 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002595 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002596 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002597 bool streamReConfigured = false;
2598 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002599 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002600 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002601 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002602 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002603 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2604 return DEAD_OBJECT;
2605 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002606 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002607 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002608 if (streamReConfigured) {
2609 mInterface->onStreamReConfigured(outputStream->getId());
2610 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002611 }
2612 }
2613
Emilian Peevd865f0d2023-03-17 17:13:07 -07002614 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002615
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 // Request thread needs to know to avoid using repeat-last-settings protocol
2617 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002618 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002619 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2620 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002621 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622
Zhijun He90f7c372016-08-16 16:19:43 -07002623 char value[PROPERTY_VALUE_MAX];
2624 property_get("camera.fifo.disable", value, "0");
2625 int32_t disableFifo = atoi(value);
2626 if (disableFifo != 1) {
2627 // Boost priority of request thread to SCHED_FIFO.
2628 pid_t requestThreadTid = mRequestThread->getTid();
2629 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002630 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002631 if (res != OK) {
2632 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2633 strerror(-res), res);
2634 } else {
2635 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2636 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002637 }
2638
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002639 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002640 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2641 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2642 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2643 sessionParams.unlock(newSessionParams);
2644 mSessionParams.unlock(currentSessionParams);
2645 if (updateSessionParams) {
2646 mSessionParams = sessionParams;
2647 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002648
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002649 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002652 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002653
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002654 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002655
Zhijun He0a210512014-07-24 13:45:15 -07002656 // tear down the deleted streams after configure streams.
2657 mDeletedStreams.clear();
2658
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002659 auto rc = mPreparerThread->resume();
2660 if (rc != OK) {
2661 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2662 return rc;
2663 }
2664
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002665 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002666 mRequestBufferSM.onStreamsConfigured();
2667 }
2668
Cliff Wu3b268182021-07-06 15:44:43 +08002669 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002670 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002671 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002672 // configure the injection streams.
2673 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002674 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002675 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2676 res = mInjectionMethods->injectCamera(config, bufferSizes);
2677 if (res != OK) {
2678 ALOGE("Can't finish inject camera process!");
2679 return res;
2680 }
Cliff Wu3b268182021-07-06 15:44:43 +08002681 } else {
2682 // First run configureStreamsLocked() and then call injectCamera() case:
2683 // If the stream configuration has been completed and camera deive is active, but the
2684 // injection camera has not been injected yet, we need to store the stream configuration of
2685 // the internal camera (because the stream configuration of the injection camera is based
2686 // on the internal camera). When injecting occurs later, this configuration can be used by
2687 // the injection camera.
2688 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2689 " injection camera has not been injected yet.", __FUNCTION__);
2690 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002691 }
2692
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002694}
2695
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002696status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002697 ATRACE_CALL();
2698 status_t res;
2699
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002700 if (mFakeStreamId != NO_STREAM) {
2701 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002702 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002703 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002704 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002705 return INVALID_OPERATION;
2706 }
2707
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002708 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002709
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002710 sp<Camera3OutputStreamInterface> fakeStream =
2711 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002712
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002713 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002714 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002715 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002716 return res;
2717 }
2718
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002719 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002720 mNextStreamId++;
2721
2722 return OK;
2723}
2724
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002725status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002726 ATRACE_CALL();
2727 status_t res;
2728
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002729 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002730 if (mOutputStreams.size() == 1) return OK;
2731
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002732 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002733
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002734 // Ok, have a fake stream and there's at least one other output stream,
2735 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002736
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002737 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002738 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002739 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002740 return INVALID_OPERATION;
2741 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002742 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002743
2744 // Free up the stream endpoint so that it can be used by some other stream
2745 res = deletedStream->disconnect();
2746 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002747 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002748 // fall through since we want to still list the stream as deleted.
2749 }
2750 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002751 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002752
2753 return res;
2754}
2755
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002756void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002757 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002758 Mutex::Autolock l(mLock);
2759 va_list args;
2760 va_start(args, fmt);
2761
2762 setErrorStateLockedV(fmt, args);
2763
2764 va_end(args);
2765}
2766
2767void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002768 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002769 Mutex::Autolock l(mLock);
2770 setErrorStateLockedV(fmt, args);
2771}
2772
2773void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2774 va_list args;
2775 va_start(args, fmt);
2776
2777 setErrorStateLockedV(fmt, args);
2778
2779 va_end(args);
2780}
2781
2782void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002783 // Print out all error messages to log
2784 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002785 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002786
2787 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002788 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002789
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002790 mErrorCause = errorCause;
2791
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002792 if (mRequestThread != nullptr) {
2793 mRequestThread->setPaused(true);
2794 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002795 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002796
2797 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002798 sp<NotificationListener> listener = mListener.promote();
2799 if (listener != NULL) {
2800 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002801 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002802 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002803 }
2804
2805 // Save stack trace. View by dumping it later.
2806 CameraTraces::saveTrace();
2807 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002808}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002809
2810/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002811 * In-flight request management
2812 */
2813
Jianing Weicb0652e2014-03-12 18:29:36 -07002814status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002815 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002816 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002817 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002818 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002819 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002820 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002821 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002822 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002823
2824 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002825 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002826 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002827 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2828 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002829 if (res < 0) return res;
2830
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002831 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002832 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2833 // avoid a deadlock during reprocess requests.
2834 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002835 if (mStatusTracker != nullptr) {
2836 mStatusTracker->markComponentActive(mInFlightStatusId);
2837 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002838 }
2839
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002840 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002841 return OK;
2842}
2843
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002844void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002845 // Indicate idle inFlightMap to the status tracker
2846 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002847 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002848 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2849 // avoid a deadlock during reprocess requests.
2850 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002851 if (mStatusTracker != nullptr) {
2852 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2853 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002854 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002855 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002856}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002857
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002858void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002859 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002860 // something has likely gone wrong. This might still be legit only if application send in
2861 // a long burst of long exposure requests.
2862 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2863 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2864 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2865 mInFlightMap.size(), mExpectedInflightDuration);
2866 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2867 kInFlightWarnLimitHighSpeed) {
2868 CLOGW("In-flight list too large for high speed configuration: %zu,"
2869 "total inflight duration %" PRIu64,
2870 mInFlightMap.size(), mExpectedInflightDuration);
2871 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002872 }
2873}
2874
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002875void Camera3Device::onInflightMapFlushedLocked() {
2876 mExpectedInflightDuration = 0;
2877}
2878
2879void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002880 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002881 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2882 mInFlightMap.removeItemsAt(idx, 1);
2883
2884 onInflightEntryRemovedLocked(duration);
2885}
2886
2887
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002888void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002889 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002890 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002891 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002892 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002893 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002894 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002895
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002896 FlushInflightReqStates states {
2897 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002898 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002899
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002900 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002901}
2902
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002903CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002904 ALOGV("%s", __FUNCTION__);
2905
Igor Murashkin1e479c02013-09-06 16:55:14 -07002906 CameraMetadata retVal;
2907
2908 if (mRequestThread != NULL) {
2909 retVal = mRequestThread->getLatestRequest();
2910 }
2911
Igor Murashkin1e479c02013-09-06 16:55:14 -07002912 return retVal;
2913}
2914
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002915void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002916 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002917 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002918 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2919 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002920
2921 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002922 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002923}
2924
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002925void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002926 std::vector<native_handle_t*> *handles, bool closeFd) {
2927 if (handles == nullptr) {
2928 return;
2929 }
2930 if (closeFd) {
2931 for (auto& handle : *handles) {
2932 native_handle_close(handle);
2933 }
2934 }
2935 for (auto& handle : *handles) {
2936 native_handle_delete(handle);
2937 }
2938 handles->clear();
2939 return;
2940}
2941
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002942/**
2943 * HalInterface inner class methods
2944 */
2945
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002946void Camera3Device::HalInterface::getInflightBufferKeys(
2947 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002948 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002949 return;
2950}
2951
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002952void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2953 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002954 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002955 return;
2956}
2957
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002958bool Camera3Device::HalInterface::verifyBufferIds(
2959 int32_t streamId, std::vector<uint64_t>& bufIds) {
2960 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002961}
2962
2963status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002964 int32_t frameNumber, int32_t streamId,
2965 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002966 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002967}
2968
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002969status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002970 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002971 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002972}
2973
2974// Find and pop a buffer_handle_t based on bufferId
2975status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002976 uint64_t bufferId,
2977 /*out*/ buffer_handle_t** buffer,
2978 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002979 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002980}
2981
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002982std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2983 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002984 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002985}
2986
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002987uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2988 const native_handle_t* handle) {
2989 return mBufferRecords.removeOneBufferCache(streamId, handle);
2990}
2991
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002992void Camera3Device::HalInterface::onBufferFreed(
2993 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002994 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2995 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2996 if (bufferId != BUFFER_ID_NO_BUFFER) {
2997 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002998 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002999}
3000
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003001void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003002 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3003 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3004 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003005 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3006 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003007}
3008
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003009/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003010 * RequestThread inner class methods
3011 */
3012
3013Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003014 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003015 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07003016 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07003017 bool supportCameraMute,
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003018 bool overrideToPortrait,
3019 bool supportSettingsOverride) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003020 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003021 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003022 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003023 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003024 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003025 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003026 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003027 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003028 mReconfigured(false),
3029 mDoPause(false),
3030 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003031 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003032 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003033 mLatestRequestId(NAME_NOT_FOUND),
Kwangkyu Park9dd5eda2023-06-20 21:12:06 +09003034 mLatestFailedRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003035 mCurrentAfTriggerId(0),
3036 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003037 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00003038 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07003039 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003040 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003041 mCameraMuteChanged(false),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003042 mSettingsOverride(ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003043 mRepeatingLastFrameNumber(
3044 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003045 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003046 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003047 mRequestLatency(kRequestLatencyBinSize),
3048 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003049 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07003050 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07003051 mSupportCameraMute(supportCameraMute),
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003052 mOverrideToPortrait(overrideToPortrait),
3053 mSupportSettingsOverride(supportSettingsOverride) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003054 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08003055 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003056}
3057
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003058Camera3Device::RequestThread::~RequestThread() {}
3059
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003060void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003061 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003062 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003063 Mutex::Autolock l(mRequestLock);
3064 mListener = listener;
3065}
3066
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003067void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08003068 const CameraMetadata& sessionParams,
3069 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003070 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003071 Mutex::Autolock l(mRequestLock);
3072 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003073 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08003074 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003075 // Prepare video stream for high speed recording.
3076 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003077 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003078}
3079
Jianing Wei90e59c92014-03-12 18:29:36 -07003080status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003081 List<sp<CaptureRequest> > &requests,
3082 /*out*/
3083 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003084 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003085 Mutex::Autolock l(mRequestLock);
3086 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3087 ++it) {
3088 mRequestQueue.push_back(*it);
3089 }
3090
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003091 if (lastFrameNumber != NULL) {
3092 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3093 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3094 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3095 *lastFrameNumber);
3096 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003097
Jianing Wei90e59c92014-03-12 18:29:36 -07003098 unpauseForNewRequests();
3099
3100 return OK;
3101}
3102
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003103
3104status_t Camera3Device::RequestThread::queueTrigger(
3105 RequestTrigger trigger[],
3106 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003107 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003108 Mutex::Autolock l(mTriggerMutex);
3109 status_t ret;
3110
3111 for (size_t i = 0; i < count; ++i) {
3112 ret = queueTriggerLocked(trigger[i]);
3113
3114 if (ret != OK) {
3115 return ret;
3116 }
3117 }
3118
3119 return OK;
3120}
3121
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003122const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3123 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003124 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003125 if (d != nullptr) return d->mId;
3126 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003127}
3128
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003129status_t Camera3Device::RequestThread::queueTriggerLocked(
3130 RequestTrigger trigger) {
3131
3132 uint32_t tag = trigger.metadataTag;
3133 ssize_t index = mTriggerMap.indexOfKey(tag);
3134
3135 switch (trigger.getTagType()) {
3136 case TYPE_BYTE:
3137 // fall-through
3138 case TYPE_INT32:
3139 break;
3140 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003141 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3142 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003143 return INVALID_OPERATION;
3144 }
3145
3146 /**
3147 * Collect only the latest trigger, since we only have 1 field
3148 * in the request settings per trigger tag, and can't send more than 1
3149 * trigger per request.
3150 */
3151 if (index != NAME_NOT_FOUND) {
3152 mTriggerMap.editValueAt(index) = trigger;
3153 } else {
3154 mTriggerMap.add(tag, trigger);
3155 }
3156
3157 return OK;
3158}
3159
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003160status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003161 const RequestList &requests,
3162 /*out*/
3163 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003164 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003165 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003166 if (lastFrameNumber != NULL) {
3167 *lastFrameNumber = mRepeatingLastFrameNumber;
3168 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003169 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003170 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003171 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3172 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003173
3174 unpauseForNewRequests();
3175
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003176 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003177 return OK;
3178}
3179
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003180bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003181 if (mRepeatingRequests.empty()) {
3182 return false;
3183 }
3184 int32_t requestId = requestIn->mResultExtras.requestId;
3185 const RequestList &repeatRequests = mRepeatingRequests;
3186 // All repeating requests are guaranteed to have same id so only check first quest
3187 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3188 return (firstRequest->mResultExtras.requestId == requestId);
3189}
3190
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003191status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003192 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003193 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003194 return clearRepeatingRequestsLocked(lastFrameNumber);
3195
3196}
3197
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003198status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3199 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003200 std::vector<int32_t> streamIds;
3201 for (const auto& request : mRepeatingRequests) {
3202 for (const auto& stream : request->mOutputStreams) {
3203 streamIds.push_back(stream->getId());
3204 }
3205 }
3206
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003207 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003208 if (lastFrameNumber != NULL) {
3209 *lastFrameNumber = mRepeatingLastFrameNumber;
3210 }
Emilian Peev2295df72021-11-12 18:14:10 -08003211
3212 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003214 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003215 return OK;
3216}
3217
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003218status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003219 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003220 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003221 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003222 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003223
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003224 // Send errors for all requests pending in the request queue, including
3225 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003226 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003227 if (listener != NULL) {
3228 for (RequestList::iterator it = mRequestQueue.begin();
3229 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003230 // Abort the input buffers for reprocess requests.
3231 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003232 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003233 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003234 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003235 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003236 if (res != OK) {
3237 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3238 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3239 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003240 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003241 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3242 if (res != OK) {
3243 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3244 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3245 }
3246 }
3247 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003248 // Set the frame number this request would have had, if it
3249 // had been submitted; this frame number will not be reused.
3250 // The requestId and burstId fields were set when the request was
3251 // submitted originally (in convertMetadataListToRequestListLocked)
3252 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003253 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003254 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003255 }
3256 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003257 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003258
3259 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003260 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003261 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003262 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003263 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003264 return OK;
3265}
3266
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003267status_t Camera3Device::RequestThread::flush() {
3268 ATRACE_CALL();
3269 Mutex::Autolock l(mFlushLock);
3270
Emilian Peev08dd2452017-04-06 16:55:14 +01003271 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003272}
3273
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003274void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003275 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003276 Mutex::Autolock l(mPauseLock);
3277 mDoPause = paused;
3278 mDoPauseSignal.signal();
3279}
3280
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003281status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3282 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003283 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003284 Mutex::Autolock l(mLatestRequestMutex);
3285 status_t res;
Kwangkyu Park9dd5eda2023-06-20 21:12:06 +09003286 while (mLatestRequestId != requestId && mLatestFailedRequestId != requestId) {
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003287 nsecs_t startTime = systemTime();
3288
3289 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3290 if (res != OK) return res;
3291
3292 timeout -= (systemTime() - startTime);
3293 }
3294
3295 return OK;
3296}
3297
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003298void Camera3Device::RequestThread::requestExit() {
3299 // Call parent to set up shutdown
3300 Thread::requestExit();
3301 // The exit from any possible waits
3302 mDoPauseSignal.signal();
3303 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003304
3305 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3306 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003307}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003308
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003309void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003310 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003311 bool surfaceAbandoned = false;
3312 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003313 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003314 {
3315 Mutex::Autolock l(mRequestLock);
3316 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3317 // repeating requests.
3318 for (const auto& request : mRepeatingRequests) {
3319 for (const auto& s : request->mOutputStreams) {
3320 if (s->isAbandoned()) {
3321 surfaceAbandoned = true;
3322 clearRepeatingRequestsLocked(&lastFrameNumber);
3323 break;
3324 }
3325 }
3326 if (surfaceAbandoned) {
3327 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003328 }
3329 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003330 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003331 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003332
3333 if (listener != NULL && surfaceAbandoned) {
3334 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003335 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003336}
3337
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003338bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003339 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003340 status_t res;
3341 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003342 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003343 uint32_t numRequestProcessed = 0;
3344 for (size_t i = 0; i < batchSize; i++) {
3345 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003346 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003347 }
3348
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003349 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3350
3351 bool triggerRemoveFailed = false;
3352 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3353 for (size_t i = 0; i < numRequestProcessed; i++) {
3354 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3355 nextRequest.submitted = true;
3356
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003357 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003358
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003359 if (!triggerRemoveFailed) {
3360 // Remove any previously queued triggers (after unlock)
3361 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3362 if (removeTriggerRes != OK) {
3363 triggerRemoveFailed = true;
3364 triggerFailedRequest = nextRequest;
3365 }
3366 }
3367 }
3368
3369 if (triggerRemoveFailed) {
3370 SET_ERR("RequestThread: Unable to remove triggers "
3371 "(capture request %d, HAL device: %s (%d)",
3372 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3373 cleanUpFailedRequests(/*sendRequestError*/ false);
3374 return false;
3375 }
3376
3377 if (res != OK) {
3378 // Should only get a failure here for malformed requests or device-level
3379 // errors, so consider all errors fatal. Bad metadata failures should
3380 // come through notify.
3381 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3382 mNextRequests[numRequestProcessed].halRequest.frame_number,
3383 strerror(-res), res);
3384 cleanUpFailedRequests(/*sendRequestError*/ false);
3385 return false;
3386 }
3387 return true;
3388}
3389
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003390Camera3Device::RequestThread::ExpectedDurationInfo
3391 Camera3Device::RequestThread::calculateExpectedDurationRange(
3392 const camera_metadata_t *request) {
3393 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003394 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003395 InFlightRequest::kDefaultMaxExpectedDuration,
3396 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003397 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3398 find_camera_metadata_ro_entry(request,
3399 ANDROID_CONTROL_AE_MODE,
3400 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003401 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003402
3403 switch (e.data.u8[0]) {
3404 case ANDROID_CONTROL_AE_MODE_OFF:
3405 find_camera_metadata_ro_entry(request,
3406 ANDROID_SENSOR_EXPOSURE_TIME,
3407 &e);
3408 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003409 expectedDurationInfo.minDuration = e.data.i64[0];
3410 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003411 }
3412 find_camera_metadata_ro_entry(request,
3413 ANDROID_SENSOR_FRAME_DURATION,
3414 &e);
3415 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003416 expectedDurationInfo.minDuration =
3417 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3418 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003419 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003420 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003421 break;
3422 default:
3423 find_camera_metadata_ro_entry(request,
3424 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3425 &e);
3426 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003427 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3428 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003429 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003430 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003431 break;
3432 }
3433
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003434 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003435}
3436
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003437bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3438 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3439 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3440 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3441 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3442 return true;
3443 }
3444
3445 return false;
3446}
3447
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003448void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3449 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003450 camera_capture_request_t& halRequest = nextRequest.halRequest;
3451 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003452 Mutex::Autolock al(mLatestRequestMutex);
3453
Shuzhen Wang83bff122020-11-20 15:51:39 -08003454 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003455 mLatestRequest.acquire(cloned);
3456
3457 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003458 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3459 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3460 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003461 CameraMetadata(cloned));
3462 }
3463
3464 sp<Camera3Device> parent = mParent.promote();
3465 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003466 int32_t inputStreamId = -1;
3467 if (halRequest.input_buffer != nullptr) {
3468 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3469 }
3470
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003471 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003472 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003473 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3474 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003475 }
3476 }
3477
Shuzhen Wang83bff122020-11-20 15:51:39 -08003478 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003479 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003480 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003481 }
3482
Shuzhen Wang83bff122020-11-20 15:51:39 -08003483 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003484}
3485
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003486bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3487 ATRACE_CALL();
3488 bool updatesDetected = false;
3489
Emilian Peev4ec17882019-01-24 17:16:58 -08003490 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003491 for (auto tag : mSessionParamKeys) {
3492 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003493 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003494
3495 if (entry.count > 0) {
3496 bool isDifferent = false;
3497 if (lastEntry.count > 0) {
3498 // Have a last value, compare to see if changed
3499 if (lastEntry.type == entry.type &&
3500 lastEntry.count == entry.count) {
3501 // Same type and count, compare values
3502 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3503 size_t entryBytes = bytesPerValue * lastEntry.count;
3504 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3505 if (cmp != 0) {
3506 isDifferent = true;
3507 }
3508 } else {
3509 // Count or type has changed
3510 isDifferent = true;
3511 }
3512 } else {
3513 // No last entry, so always consider to be different
3514 isDifferent = true;
3515 }
3516
3517 if (isDifferent) {
3518 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003519 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3520 updatesDetected = true;
3521 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003522 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003523 }
3524 } else if (lastEntry.count > 0) {
3525 // Value has been removed
3526 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003527 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003528 updatesDetected = true;
3529 }
3530 }
3531
Emilian Peev4ec17882019-01-24 17:16:58 -08003532 bool reconfigureRequired;
3533 if (updatesDetected) {
3534 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3535 updatedParams);
3536 mLatestSessionParams = updatedParams;
3537 } else {
3538 reconfigureRequired = false;
3539 }
3540
3541 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003542}
3543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003544bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003545 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003546 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003547 // Any function called from threadLoop() must not hold mInterfaceLock since
3548 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3549 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003550
3551 // Handle paused state.
3552 if (waitIfPaused()) {
3553 return true;
3554 }
3555
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003556 // Wait for the next batch of requests.
3557 waitForNextRequestBatch();
3558 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003559 return true;
3560 }
3561
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003562 // Get the latest request ID, if any
3563 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003564 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003565 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003566 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003567 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003568 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003569 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3570 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003571 }
3572
Emilian Peevd865f0d2023-03-17 17:13:07 -07003573 for (size_t i = 0; i < mNextRequests.size(); i++) {
3574 auto& nextRequest = mNextRequests.editItemAt(i);
3575 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3576 // Do not override rotate&crop for stream configurations that include
3577 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3578 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3579 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3580 overrideAutoRotateAndCrop(captureRequest);
3581 captureRequest->mAutoframingChanged = overrideAutoframing(captureRequest);
3582 }
3583
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003584 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3585 // or a single request from streaming or burst. In either case the first element
3586 // should contain the latest camera settings that we need to check for any session
3587 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003588 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003589 res = OK;
3590
3591 //Input stream buffers are already acquired at this point so an input stream
3592 //will not be able to move to idle state unless we force it.
3593 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3594 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3595 if (res != OK) {
3596 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3597 cleanUpFailedRequests(/*sendRequestError*/ false);
3598 return false;
3599 }
3600 }
3601
3602 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003603 sp<Camera3Device> parent = mParent.promote();
3604 if (parent != nullptr) {
3605 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003606 }
3607
3608 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3609 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3610 if (res != OK) {
3611 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3612 cleanUpFailedRequests(/*sendRequestError*/ false);
3613 return false;
3614 }
3615 }
3616 }
3617 }
3618
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003619 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003620 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003621 if (res == TIMED_OUT) {
3622 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003623 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003624 // Check if any stream is abandoned.
3625 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003626 return true;
3627 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003628 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003629 return false;
3630 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003631
Zhijun Hecc27e112013-10-03 16:12:43 -07003632 // Inform waitUntilRequestProcessed thread of a new request ID
3633 {
3634 Mutex::Autolock al(mLatestRequestMutex);
3635
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003636 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003637 mLatestRequestSignal.signal();
3638 }
3639
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 // Submit a batch of requests to HAL.
3641 // Use flush lock only when submitting multilple requests in a batch.
3642 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3643 // which may take a long time to finish so synchronizing flush() and
3644 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3645 // For now, only synchronize for high speed recording and we should figure something out for
3646 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003647 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003648
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003649 if (useFlushLock) {
3650 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003651 }
3652
Zhijun Hef0645c12016-08-02 00:58:11 -07003653 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003654 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003655
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003656 sp<Camera3Device> parent = mParent.promote();
3657 if (parent != nullptr) {
3658 parent->mRequestBufferSM.onSubmittingRequest();
3659 }
3660
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003661 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003662 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003663 submitRequestSuccess = sendRequestsBatch();
3664
Shuzhen Wang686f6442017-06-20 16:16:04 -07003665 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3666 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003667
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003668 if (useFlushLock) {
3669 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003670 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003671
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003672 // Unset as current request
3673 {
3674 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003675 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003676 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003677 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003678
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003679 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003680}
3681
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003682status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3683 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3684 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3685 ANDROID_SCALER_CROP_REGION_SET};
3686 if (request == nullptr) {
3687 ALOGE("%s request metadata nullptr", __FUNCTION__);
3688 return BAD_VALUE;
3689 }
3690 status_t res = OK;
3691 for (const auto &key : kFwkOnlyRegionKeys) {
3692 if (request->exists(key)) {
3693 res = request->erase(key);
3694 if (res != OK) {
3695 return res;
3696 }
3697 }
3698 }
3699 return OK;
3700}
3701
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003702status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003703 ATRACE_CALL();
3704
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003705 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003706 for (size_t i = 0; i < mNextRequests.size(); i++) {
3707 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003708 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003709 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3710 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711
3712 // Prepare a request to HAL
3713 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3714
3715 // Insert any queued triggers (before metadata is locked)
3716 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003717 if (res < 0) {
3718 SET_ERR("RequestThread: Unable to insert triggers "
3719 "(capture request %d, HAL device: %s (%d)",
3720 halRequest->frame_number, strerror(-res), res);
3721 return INVALID_OPERATION;
3722 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003723
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003724 int triggerCount = res;
3725 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3726 mPrevTriggers = triggerCount;
3727
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003728 bool testPatternChanged = overrideTestPattern(captureRequest);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003729 bool settingsOverrideChanged = overrideSettingsOverride(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003730
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003731 // If the request is the same as last, or we had triggers now or last time or
3732 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003733 bool newRequest =
Emilian Peevd865f0d2023-03-17 17:13:07 -07003734 (mPrevRequest != captureRequest || triggersMixedIn ||
3735 captureRequest->mRotateAndCropChanged ||
3736 captureRequest->mAutoframingChanged ||
Shuzhen Wangaf22e912023-04-11 16:03:17 -07003737 testPatternChanged || settingsOverrideChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003738 // Request settings are all the same within one batch, so only treat the first
3739 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003740 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003741 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003742 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003743 /**
3744 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003745 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003746 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003747 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003748 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003749 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003750 "(capture request %d, HAL device: %s (%d)",
3751 halRequest->frame_number, strerror(-res), res);
3752 return INVALID_OPERATION;
3753 }
3754
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003755 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003756 sp<Camera3Device> parent = mParent.promote();
3757 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003758 List<PhysicalCameraSettings>::iterator it;
3759 for (it = captureRequest->mSettingsList.begin();
3760 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003761 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3762 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003763 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3764 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3765 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3766 res);
3767 return INVALID_OPERATION;
3768 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003769 continue;
3770 }
3771
3772 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3773 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3774 updateCaptureRequest(&(it->metadata));
3775 if (res != OK) {
3776 SET_ERR("RequestThread: Unable to correct capture requests "
3777 "for scaler crop region and metering regions for request "
3778 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3779 res);
3780 return INVALID_OPERATION;
3781 }
3782 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003783 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3784 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3785 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3786 res);
3787 return INVALID_OPERATION;
3788 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003789 }
3790 }
3791
3792 // Correct metadata regions for distortion correction if enabled
3793 for (it = captureRequest->mSettingsList.begin();
3794 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003795 if (parent->mDistortionMappers.find(it->cameraId) ==
3796 parent->mDistortionMappers.end()) {
3797 continue;
3798 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003799
3800 if (!captureRequest->mDistortionCorrectionUpdated) {
3801 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3802 &(it->metadata));
3803 if (res != OK) {
3804 SET_ERR("RequestThread: Unable to correct capture requests "
3805 "for lens distortion for request %d: %s (%d)",
3806 halRequest->frame_number, strerror(-res), res);
3807 return INVALID_OPERATION;
3808 }
3809 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003810 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003811 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003812
3813 for (it = captureRequest->mSettingsList.begin();
3814 it != captureRequest->mSettingsList.end(); it++) {
3815 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3816 parent->mZoomRatioMappers.end()) {
3817 continue;
3818 }
3819
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003820 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003821 cameraIdsWithZoom.insert(it->cameraId);
3822 }
3823
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003824 if (!captureRequest->mZoomRatioUpdated) {
3825 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3826 &(it->metadata));
3827 if (res != OK) {
3828 SET_ERR("RequestThread: Unable to correct capture requests "
3829 "for zoom ratio for request %d: %s (%d)",
3830 halRequest->frame_number, strerror(-res), res);
3831 return INVALID_OPERATION;
3832 }
3833 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003834 }
3835 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003836 if (captureRequest->mRotateAndCropAuto &&
3837 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003838 for (it = captureRequest->mSettingsList.begin();
3839 it != captureRequest->mSettingsList.end(); it++) {
3840 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3841 if (mapper != parent->mRotateAndCropMappers.end()) {
3842 res = mapper->second.updateCaptureRequest(&(it->metadata));
3843 if (res != OK) {
3844 SET_ERR("RequestThread: Unable to correct capture requests "
3845 "for rotate-and-crop for request %d: %s (%d)",
3846 halRequest->frame_number, strerror(-res), res);
3847 return INVALID_OPERATION;
3848 }
3849 }
3850 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003851 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003852 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003853
3854 for (it = captureRequest->mSettingsList.begin();
3855 it != captureRequest->mSettingsList.end(); it++) {
3856 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3857 mVndkVersion, it->metadata, false /*isStatic*/);
3858 if (res != OK) {
3859 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3860 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3861 return INVALID_OPERATION;
3862 }
3863 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003864 }
3865 }
3866
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003867 /**
3868 * The request should be presorted so accesses in HAL
3869 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3870 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003871 captureRequest->mSettingsList.begin()->metadata.sort();
3872 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003873 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003874 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003875 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3876
3877 IF_ALOGV() {
3878 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3879 find_camera_metadata_ro_entry(
3880 halRequest->settings,
3881 ANDROID_CONTROL_AF_TRIGGER,
3882 &e
3883 );
3884 if (e.count > 0) {
3885 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3886 __FUNCTION__,
3887 halRequest->frame_number,
3888 e.data.u8[0]);
3889 }
3890 }
3891 } else {
3892 // leave request.settings NULL to indicate 'reuse latest given'
3893 ALOGVV("%s: Request settings are REUSED",
3894 __FUNCTION__);
3895 }
3896
Emilian Peevaebbe412018-01-15 13:53:24 +00003897 if (captureRequest->mSettingsList.size() > 1) {
3898 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3899 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003900 if (newRequest) {
3901 halRequest->physcam_settings =
3902 new const camera_metadata* [halRequest->num_physcam_settings];
3903 } else {
3904 halRequest->physcam_settings = nullptr;
3905 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003906 auto it = ++captureRequest->mSettingsList.begin();
3907 size_t i = 0;
3908 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3909 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003910 if (newRequest) {
3911 it->metadata.sort();
3912 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3913 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003914 }
3915 }
3916
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003917 uint32_t totalNumBuffers = 0;
3918
3919 // Fill in buffers
3920 if (captureRequest->mInputStream != NULL) {
3921 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003922
3923 halRequest->input_width = captureRequest->mInputBufferSize.width;
3924 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003925 totalNumBuffers += 1;
3926 } else {
3927 halRequest->input_buffer = NULL;
3928 }
3929
Emilian Peevf4816702020-04-03 15:44:51 -07003930 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003931 captureRequest->mOutputStreams.size());
3932 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003933 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003934
3935 sp<Camera3Device> parent = mParent.promote();
3936 if (parent == NULL) {
3937 // Should not happen, and nowhere to send errors to, so just log it
3938 CLOGE("RequestThread: Parent is gone");
3939 return INVALID_OPERATION;
3940 }
3941 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3942
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003943 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003944 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003945 sp<Camera3OutputStreamInterface> outputStream =
3946 captureRequest->mOutputStreams.editItemAt(j);
3947 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003948
3949 // Prepare video buffers for high speed recording on the first video request.
3950 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3951 // Only try to prepare video stream on the first video request.
3952 mPrepareVideoStream = false;
3953
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003954 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3955 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003956 while (res == NOT_ENOUGH_DATA) {
3957 res = outputStream->prepareNextBuffer();
3958 }
3959 if (res != OK) {
3960 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3961 __FUNCTION__, strerror(-res), res);
3962 outputStream->cancelPrepare();
3963 }
3964 }
3965
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003966 std::vector<size_t> uniqueSurfaceIds;
3967 res = outputStream->getUniqueSurfaceIds(
3968 captureRequest->mOutputSurfaces[streamId],
3969 &uniqueSurfaceIds);
3970 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3971 if (res != OK && res != INVALID_OPERATION) {
3972 ALOGE("%s: failed to query stream %d unique surface IDs",
3973 __FUNCTION__, streamId);
3974 return res;
3975 }
3976 if (res == OK) {
3977 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3978 }
3979
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003980 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003981 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003982 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003983 return TIMED_OUT;
3984 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003985 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003986 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003987 buffer.stream = outputStream->asHalStream();
3988 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003989 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003990 buffer.acquire_fence = -1;
3991 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003992 // Mark the output stream as unpreparable to block clients from calling
3993 // 'prepare' after this request reaches CameraHal and before the respective
3994 // buffers are requested.
3995 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003996 } else {
3997 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3998 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003999 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004000 if (res != OK) {
4001 // Can't get output buffer from gralloc queue - this could be due to
4002 // abandoned queue or other consumer misbehavior, so not a fatal
4003 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004004 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004005 " %s (%d)", strerror(-res), res);
4006
4007 return TIMED_OUT;
4008 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004009 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004010
4011 {
4012 sp<Camera3Device> parent = mParent.promote();
4013 if (parent != nullptr) {
4014 const String8& streamCameraId = outputStream->getPhysicalCameraId();
Emilian Peevdf6d0502023-07-26 22:39:33 +00004015 // Consider the case where clients are sending a single logical camera request
4016 // to physical output/outputs
4017 bool singleRequest = captureRequest->mSettingsList.size() == 1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004018 for (const auto& settings : captureRequest->mSettingsList) {
Emilian Peevdf6d0502023-07-26 22:39:33 +00004019 if (((streamCameraId.isEmpty() || singleRequest) &&
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004020 parent->getId() == settings.cameraId.c_str()) ||
4021 streamCameraId == settings.cameraId.c_str()) {
4022 outputStream->fireBufferRequestForFrameNumber(
4023 captureRequest->mResultExtras.frameNumber,
4024 settings.metadata);
4025 }
4026 }
4027 }
4028 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004029
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004030 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08004031 int32_t streamGroupId = outputStream->getHalStreamGroupId();
4032 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
4033 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
4034 } else if (!physicalCameraId.isEmpty()) {
4035 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004036 }
4037 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004038 }
4039 totalNumBuffers += halRequest->num_output_buffers;
4040
4041 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004042 // If this request list is for constrained high speed recording (not
4043 // preview), and the current request is not the last one in the batch,
4044 // do not send callback to the app.
4045 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004046 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004047 hasCallback = false;
4048 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004049 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004050 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004051 const camera_metadata_t* settings = halRequest->settings;
4052 bool shouldUnlockSettings = false;
4053 if (settings == nullptr) {
4054 shouldUnlockSettings = true;
4055 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
4056 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004057 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4058 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004059 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01004060 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4061 isStillCapture = true;
4062 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4063 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004064
Emilian Peevaf8416e2021-02-04 17:52:43 -08004065 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004066 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004067 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4068 isZslCapture = true;
4069 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004070 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004071 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072 res = parent->registerInFlight(halRequest->frame_number,
4073 totalNumBuffers, captureRequest->mResultExtras,
4074 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004075 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07004076 expectedDurationInfo.minDuration,
4077 expectedDurationInfo.maxDuration,
4078 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004079 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004080 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
4081 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004082 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004083 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004084 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4085 ", burstId = %" PRId32 ".",
4086 __FUNCTION__,
4087 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4088 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08004089
4090 if (shouldUnlockSettings) {
4091 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
4092 }
4093
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004094 if (res != OK) {
4095 SET_ERR("RequestThread: Unable to register new in-flight request:"
4096 " %s (%d)", strerror(-res), res);
4097 return INVALID_OPERATION;
4098 }
4099 }
4100
4101 return OK;
4102}
4103
Igor Murashkin1e479c02013-09-06 16:55:14 -07004104CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004105 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004106 Mutex::Autolock al(mLatestRequestMutex);
4107
4108 ALOGV("RequestThread::%s", __FUNCTION__);
4109
4110 return mLatestRequest;
4111}
4112
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004113bool Camera3Device::RequestThread::isStreamPending(
4114 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004115 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004116 Mutex::Autolock l(mRequestLock);
4117
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004118 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004119 if (!nextRequest.submitted) {
4120 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4121 if (stream == s) return true;
4122 }
4123 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004124 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004125 }
4126
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004127 for (const auto& request : mRequestQueue) {
4128 for (const auto& s : request->mOutputStreams) {
4129 if (stream == s) return true;
4130 }
4131 if (stream == request->mInputStream) return true;
4132 }
4133
4134 for (const auto& request : mRepeatingRequests) {
4135 for (const auto& s : request->mOutputStreams) {
4136 if (stream == s) return true;
4137 }
4138 if (stream == request->mInputStream) return true;
4139 }
4140
4141 return false;
4142}
Jianing Weicb0652e2014-03-12 18:29:36 -07004143
Emilian Peev40ead602017-09-26 15:46:36 +01004144bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4145 ATRACE_CALL();
4146 Mutex::Autolock l(mRequestLock);
4147
4148 for (const auto& nextRequest : mNextRequests) {
4149 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4150 if (s.first == streamId) {
4151 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4152 if (it != s.second.end()) {
4153 return true;
4154 }
4155 }
4156 }
4157 }
4158
4159 for (const auto& request : mRequestQueue) {
4160 for (const auto& s : request->mOutputSurfaces) {
4161 if (s.first == streamId) {
4162 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4163 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004164 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004165 }
4166 }
4167 }
4168 }
4169
4170 for (const auto& request : mRepeatingRequests) {
4171 for (const auto& s : request->mOutputSurfaces) {
4172 if (s.first == streamId) {
4173 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4174 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004175 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004176 }
4177 }
4178 }
4179 }
4180
4181 return false;
4182}
4183
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004184void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4185 if (!mUseHalBufManager) {
4186 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4187 return;
4188 }
4189
4190 Mutex::Autolock pl(mPauseLock);
4191 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004192 mInterface->signalPipelineDrain(streamIds);
4193 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004194 }
4195 // If request thread is still busy, wait until paused then notify HAL
4196 mNotifyPipelineDrain = true;
4197 mStreamIdsToBeDrained = streamIds;
4198}
4199
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004200void Camera3Device::RequestThread::resetPipelineDrain() {
4201 Mutex::Autolock pl(mPauseLock);
4202 mNotifyPipelineDrain = false;
4203 mStreamIdsToBeDrained.clear();
4204}
4205
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004206void Camera3Device::RequestThread::clearPreviousRequest() {
4207 Mutex::Autolock l(mRequestLock);
4208 mPrevRequest.clear();
4209}
4210
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004211status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4212 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4213 ATRACE_CALL();
4214 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004215 mRotateAndCropOverride = rotateAndCropValue;
4216 return OK;
4217}
4218
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004219status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4220 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4221 ATRACE_CALL();
4222 Mutex::Autolock l(mTriggerMutex);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004223 mAutoframingOverride = autoframingValue;
4224 return OK;
4225}
4226
Emilian Peeve23f1d92021-09-20 14:56:01 -07004227status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4228 ATRACE_CALL();
4229 Mutex::Autolock l(mTriggerMutex);
4230 mComposerOutput = composerSurfacePresent;
4231 return OK;
4232}
4233
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004234status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004235 ATRACE_CALL();
4236 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004237 if (muteMode != mCameraMute) {
4238 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004239 mCameraMuteChanged = true;
4240 }
4241 return OK;
4242}
4243
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004244status_t Camera3Device::RequestThread::setZoomOverride(int32_t zoomOverride) {
4245 ATRACE_CALL();
4246 Mutex::Autolock l(mTriggerMutex);
4247 mSettingsOverride = zoomOverride;
4248 return OK;
4249}
4250
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004251nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004252 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004253 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004254 return mExpectedInflightDuration > kMinInflightDuration ?
4255 mExpectedInflightDuration : kMinInflightDuration;
4256}
4257
Emilian Peevaebbe412018-01-15 13:53:24 +00004258void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004259 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004260 if ((request == nullptr) || (halRequest == nullptr)) {
4261 ALOGE("%s: Invalid request!", __FUNCTION__);
4262 return;
4263 }
4264
4265 if (halRequest->num_physcam_settings > 0) {
4266 if (halRequest->physcam_id != nullptr) {
4267 delete [] halRequest->physcam_id;
4268 halRequest->physcam_id = nullptr;
4269 }
4270 if (halRequest->physcam_settings != nullptr) {
4271 auto it = ++(request->mSettingsList.begin());
4272 size_t i = 0;
4273 for (; it != request->mSettingsList.end(); it++, i++) {
4274 it->metadata.unlock(halRequest->physcam_settings[i]);
4275 }
4276 delete [] halRequest->physcam_settings;
4277 halRequest->physcam_settings = nullptr;
4278 }
4279 }
4280}
4281
Ravneetaeb20dc2022-03-30 05:33:03 +00004282status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4283 Mutex::Autolock il(mInterfaceLock);
4284 Mutex::Autolock l(mLock);
4285
4286 if (mCameraServiceWatchdog != NULL) {
4287 mCameraServiceWatchdog->setEnabled(enabled);
4288 }
4289
4290 return OK;
4291}
4292
Shuzhen Wang16610a62022-12-15 22:38:07 -08004293void Camera3Device::setStreamUseCaseOverrides(
4294 const std::vector<int64_t>& useCaseOverrides) {
4295 Mutex::Autolock il(mInterfaceLock);
4296 Mutex::Autolock l(mLock);
4297 mStreamUseCaseOverrides = useCaseOverrides;
4298}
4299
4300void Camera3Device::clearStreamUseCaseOverrides() {
4301 Mutex::Autolock il(mInterfaceLock);
4302 Mutex::Autolock l(mLock);
4303 mStreamUseCaseOverrides.clear();
4304}
4305
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004306bool Camera3Device::hasDeviceError() {
4307 Mutex::Autolock il(mInterfaceLock);
4308 Mutex::Autolock l(mLock);
4309 return mStatus == STATUS_ERROR;
4310}
4311
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004312void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4313 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004314 return;
4315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004316
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004317 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004318 // Skip the ones that have been submitted successfully.
4319 if (nextRequest.submitted) {
4320 continue;
4321 }
4322
4323 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004324 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4325 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004326
4327 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004328 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004329 }
4330
Emilian Peevaebbe412018-01-15 13:53:24 +00004331 cleanupPhysicalSettings(captureRequest, halRequest);
4332
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004333 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004334 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004335 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4336 }
4337
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004338 // No output buffer can be returned when using HAL buffer manager
4339 if (!mUseHalBufManager) {
4340 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4341 //Buffers that failed processing could still have
4342 //valid acquire fence.
4343 int acquireFence = (*outputBuffers)[i].acquire_fence;
4344 if (0 <= acquireFence) {
4345 close(acquireFence);
4346 outputBuffers->editItemAt(i).acquire_fence = -1;
4347 }
Emilian Peevf4816702020-04-03 15:44:51 -07004348 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004349 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4350 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004351 /*timestampIncreasing*/true, std::vector<size_t> (),
4352 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004353 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004354 }
4355
4356 if (sendRequestError) {
4357 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004358 sp<NotificationListener> listener = mListener.promote();
4359 if (listener != NULL) {
4360 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004361 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004362 captureRequest->mResultExtras);
4363 }
Kwangkyu Park9dd5eda2023-06-20 21:12:06 +09004364 {
4365 Mutex::Autolock al(mLatestRequestMutex);
4366
4367 mLatestFailedRequestId = captureRequest->mResultExtras.requestId;
4368 mLatestRequestSignal.signal();
4369 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004370 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004371
4372 // Remove yet-to-be submitted inflight request from inflightMap
4373 {
4374 sp<Camera3Device> parent = mParent.promote();
4375 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004376 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004377 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4378 if (idx >= 0) {
4379 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4380 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4381 parent->removeInFlightMapEntryLocked(idx);
4382 }
4383 }
4384 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004385 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004386
4387 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004388 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004389}
4390
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004391void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004392 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004393 // Optimized a bit for the simple steady-state case (single repeating
4394 // request), to avoid putting that request in the queue temporarily.
4395 Mutex::Autolock l(mRequestLock);
4396
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004397 assert(mNextRequests.empty());
4398
4399 NextRequest nextRequest;
4400 nextRequest.captureRequest = waitForNextRequestLocked();
4401 if (nextRequest.captureRequest == nullptr) {
4402 return;
4403 }
4404
Emilian Peevf4816702020-04-03 15:44:51 -07004405 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004406 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004407 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004408
4409 // Wait for additional requests
4410 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4411
4412 for (size_t i = 1; i < batchSize; i++) {
4413 NextRequest additionalRequest;
4414 additionalRequest.captureRequest = waitForNextRequestLocked();
4415 if (additionalRequest.captureRequest == nullptr) {
4416 break;
4417 }
4418
Emilian Peevf4816702020-04-03 15:44:51 -07004419 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004420 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004421 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004422 }
4423
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004424 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004425 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004426 mNextRequests.size(), batchSize);
4427 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004428 }
4429
4430 return;
4431}
4432
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004433void Camera3Device::RequestThread::setRequestClearing() {
4434 Mutex::Autolock l(mRequestLock);
4435 mRequestClearing = true;
4436}
4437
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004438sp<Camera3Device::CaptureRequest>
4439 Camera3Device::RequestThread::waitForNextRequestLocked() {
4440 status_t res;
4441 sp<CaptureRequest> nextRequest;
4442
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004443 while (mRequestQueue.empty()) {
4444 if (!mRepeatingRequests.empty()) {
4445 // Always atomically enqueue all requests in a repeating request
4446 // list. Guarantees a complete in-sequence set of captures to
4447 // application.
4448 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004449 if (mFirstRepeating) {
4450 mFirstRepeating = false;
4451 } else {
4452 for (auto& request : requests) {
4453 // For repeating requests, override timestamp request using
4454 // the time a request is inserted into the request queue,
4455 // because the original repeating request will have an old
4456 // fixed timestamp.
4457 request->mRequestTimeNs = systemTime();
4458 }
4459 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004460 RequestList::const_iterator firstRequest =
4461 requests.begin();
4462 nextRequest = *firstRequest;
4463 mRequestQueue.insert(mRequestQueue.end(),
4464 ++firstRequest,
4465 requests.end());
4466 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004467
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004468 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004469
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004470 break;
4471 }
4472
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004473 if (!mRequestClearing) {
4474 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4475 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004476
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004477 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4478 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 Mutex::Autolock pl(mPauseLock);
4480 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004481 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004482 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004483 if (mNotifyPipelineDrain) {
4484 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4485 mNotifyPipelineDrain = false;
4486 mStreamIdsToBeDrained.clear();
4487 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004488 // Let the tracker know
4489 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4490 if (statusTracker != 0) {
4491 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4492 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004493 sp<Camera3Device> parent = mParent.promote();
4494 if (parent != nullptr) {
4495 parent->mRequestBufferSM.onRequestThreadPaused();
4496 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004497 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004498 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004499 // Stop waiting for now and let thread management happen
4500 return NULL;
4501 }
4502 }
4503
4504 if (nextRequest == NULL) {
4505 // Don't have a repeating request already in hand, so queue
4506 // must have an entry now.
4507 RequestList::iterator firstRequest =
4508 mRequestQueue.begin();
4509 nextRequest = *firstRequest;
4510 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004511 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4512 sp<NotificationListener> listener = mListener.promote();
4513 if (listener != NULL) {
4514 listener->notifyRequestQueueEmpty();
4515 }
4516 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004517 }
4518
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004519 // In case we've been unpaused by setPaused clearing mDoPause, need to
4520 // update internal pause state (capture/setRepeatingRequest unpause
4521 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004522 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004523 if (mPaused) {
4524 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4525 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4526 if (statusTracker != 0) {
4527 statusTracker->markComponentActive(mStatusId);
4528 }
4529 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004530 mPaused = false;
4531
4532 // Check if we've reconfigured since last time, and reset the preview
4533 // request if so. Can't use 'NULL request == repeat' across configure calls.
4534 if (mReconfigured) {
4535 mPrevRequest.clear();
4536 mReconfigured = false;
4537 }
4538
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004539 if (nextRequest != NULL) {
4540 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004541 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4542 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004543
4544 // Since RequestThread::clear() removes buffers from the input stream,
4545 // get the right buffer here before unlocking mRequestLock
4546 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004547 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4548 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004549 if (res != OK) {
4550 // Can't get input buffer from gralloc queue - this could be due to
4551 // disconnected queue or other producer misbehavior, so not a fatal
4552 // error
4553 ALOGE("%s: Can't get input buffer, skipping request:"
4554 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004555
4556 sp<NotificationListener> listener = mListener.promote();
4557 if (listener != NULL) {
4558 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004559 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004560 nextRequest->mResultExtras);
4561 }
4562 return NULL;
4563 }
4564 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004565 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004566
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004567 return nextRequest;
4568}
4569
4570bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004571 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004572 status_t res;
4573 Mutex::Autolock l(mPauseLock);
4574 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004575 if (mPaused == false) {
4576 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004577 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004578 if (mNotifyPipelineDrain) {
4579 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4580 mNotifyPipelineDrain = false;
4581 mStreamIdsToBeDrained.clear();
4582 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004583 // Let the tracker know
4584 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4585 if (statusTracker != 0) {
4586 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4587 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004588 sp<Camera3Device> parent = mParent.promote();
4589 if (parent != nullptr) {
4590 parent->mRequestBufferSM.onRequestThreadPaused();
4591 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004592 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004593
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004594 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004595 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004596 return true;
4597 }
4598 }
4599 // We don't set mPaused to false here, because waitForNextRequest needs
4600 // to further manage the paused state in case of starvation.
4601 return false;
4602}
4603
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004604void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004605 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004606 // With work to do, mark thread as unpaused.
4607 // If paused by request (setPaused), don't resume, to avoid
4608 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004609 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004610 Mutex::Autolock p(mPauseLock);
4611 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004612 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4613 if (mPaused) {
4614 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4615 if (statusTracker != 0) {
4616 statusTracker->markComponentActive(mStatusId);
4617 }
4618 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004619 mPaused = false;
4620 }
4621}
4622
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004623void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4624 sp<Camera3Device> parent = mParent.promote();
4625 if (parent != NULL) {
4626 va_list args;
4627 va_start(args, fmt);
4628
4629 parent->setErrorStateV(fmt, args);
4630
4631 va_end(args);
4632 }
4633}
4634
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004635status_t Camera3Device::RequestThread::insertTriggers(
4636 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004637 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004638 Mutex::Autolock al(mTriggerMutex);
4639
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004640 sp<Camera3Device> parent = mParent.promote();
4641 if (parent == NULL) {
4642 CLOGE("RequestThread: Parent is gone");
4643 return DEAD_OBJECT;
4644 }
4645
Emilian Peevaebbe412018-01-15 13:53:24 +00004646 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004647 size_t count = mTriggerMap.size();
4648
4649 for (size_t i = 0; i < count; ++i) {
4650 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004651 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004652
4653 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4654 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4655 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004656 if (isAeTrigger) {
4657 request->mResultExtras.precaptureTriggerId = triggerId;
4658 mCurrentPreCaptureTriggerId = triggerId;
4659 } else {
4660 request->mResultExtras.afTriggerId = triggerId;
4661 mCurrentAfTriggerId = triggerId;
4662 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004663 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004664 }
4665
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004666 camera_metadata_entry entry = metadata.find(tag);
4667
4668 if (entry.count > 0) {
4669 /**
4670 * Already has an entry for this trigger in the request.
4671 * Rewrite it with our requested trigger value.
4672 */
4673 RequestTrigger oldTrigger = trigger;
4674
4675 oldTrigger.entryValue = entry.data.u8[0];
4676
4677 mTriggerReplacedMap.add(tag, oldTrigger);
4678 } else {
4679 /**
4680 * More typical, no trigger entry, so we just add it
4681 */
4682 mTriggerRemovedMap.add(tag, trigger);
4683 }
4684
4685 status_t res;
4686
4687 switch (trigger.getTagType()) {
4688 case TYPE_BYTE: {
4689 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4690 res = metadata.update(tag,
4691 &entryValue,
4692 /*count*/1);
4693 break;
4694 }
4695 case TYPE_INT32:
4696 res = metadata.update(tag,
4697 &trigger.entryValue,
4698 /*count*/1);
4699 break;
4700 default:
4701 ALOGE("%s: Type not supported: 0x%x",
4702 __FUNCTION__,
4703 trigger.getTagType());
4704 return INVALID_OPERATION;
4705 }
4706
4707 if (res != OK) {
4708 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4709 ", value %d", __FUNCTION__, trigger.getTagName(),
4710 trigger.entryValue);
4711 return res;
4712 }
4713
4714 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4715 trigger.getTagName(),
4716 trigger.entryValue);
4717 }
4718
4719 mTriggerMap.clear();
4720
4721 return count;
4722}
4723
4724status_t Camera3Device::RequestThread::removeTriggers(
4725 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004726 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004727 Mutex::Autolock al(mTriggerMutex);
4728
Emilian Peevaebbe412018-01-15 13:53:24 +00004729 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004730
4731 /**
4732 * Replace all old entries with their old values.
4733 */
4734 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4735 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4736
4737 status_t res;
4738
4739 uint32_t tag = trigger.metadataTag;
4740 switch (trigger.getTagType()) {
4741 case TYPE_BYTE: {
4742 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4743 res = metadata.update(tag,
4744 &entryValue,
4745 /*count*/1);
4746 break;
4747 }
4748 case TYPE_INT32:
4749 res = metadata.update(tag,
4750 &trigger.entryValue,
4751 /*count*/1);
4752 break;
4753 default:
4754 ALOGE("%s: Type not supported: 0x%x",
4755 __FUNCTION__,
4756 trigger.getTagType());
4757 return INVALID_OPERATION;
4758 }
4759
4760 if (res != OK) {
4761 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4762 ", trigger value %d", __FUNCTION__,
4763 trigger.getTagName(), trigger.entryValue);
4764 return res;
4765 }
4766 }
4767 mTriggerReplacedMap.clear();
4768
4769 /**
4770 * Remove all new entries.
4771 */
4772 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4773 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4774 status_t res = metadata.erase(trigger.metadataTag);
4775
4776 if (res != OK) {
4777 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4778 ", trigger value %d", __FUNCTION__,
4779 trigger.getTagName(), trigger.entryValue);
4780 return res;
4781 }
4782 }
4783 mTriggerRemovedMap.clear();
4784
4785 return OK;
4786}
4787
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004788status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004789 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004790 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004791 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004792 status_t res;
4793
Emilian Peevaebbe412018-01-15 13:53:24 +00004794 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004795
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004796 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004797 // exists
4798 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4799 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4800 if (afTrigger.count > 0 &&
4801 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4802 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004803 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004804 if (res != OK) return res;
4805 }
4806
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004807 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004808 // if none already exists
4809 camera_metadata_entry pcTrigger =
4810 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4811 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4812 if (pcTrigger.count > 0 &&
4813 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4814 pcId.count == 0) {
4815 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004816 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004817 if (res != OK) return res;
4818 }
4819
4820 return OK;
4821}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004822
Emilian Peevd865f0d2023-03-17 17:13:07 -07004823bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4824 ATRACE_CALL();
4825 Mutex::Autolock l(mTriggerMutex);
4826 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4827 this->mRotateAndCropOverride);
4828}
4829
4830bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4831 bool overrideToPortrait,
4832 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004833 ATRACE_CALL();
4834
Emilian Peevd865f0d2023-03-17 17:13:07 -07004835 if (overrideToPortrait) {
4836 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger18b30a72022-10-27 12:20:29 -07004837 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4838 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4839 &rotateAndCrop_u8, 1);
4840 return true;
4841 }
4842
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004843 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004844 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4845
4846 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4847 if (rotateAndCropEntry.count > 0) {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004848 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004849 return false;
4850 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004851 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004852 return true;
4853 }
4854 } else {
Emilian Peevd865f0d2023-03-17 17:13:07 -07004855 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4856 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004857 return true;
4858 }
4859 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004860
4861 return false;
4862}
4863
4864bool Camera3Device::overrideAutoframing(const sp<CaptureRequest> &request /*out*/,
4865 camera_metadata_enum_android_control_autoframing_t autoframingOverride) {
4866 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4867 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4868 if (autoframingEntry.count > 0) {
4869 if (autoframingEntry.data.u8[0] == autoframingOverride) {
4870 return false;
4871 } else {
4872 autoframingEntry.data.u8[0] = autoframingOverride;
4873 return true;
4874 }
4875 } else {
4876 uint8_t autoframing_u8 = autoframingOverride;
4877 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4878 &autoframing_u8, 1);
4879 return true;
4880 }
4881
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004882 return false;
4883}
4884
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004885bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4886 ATRACE_CALL();
4887
4888 if (request->mAutoframingAuto) {
4889 Mutex::Autolock l(mTriggerMutex);
Emilian Peevd865f0d2023-03-17 17:13:07 -07004890 return Camera3Device::overrideAutoframing(request, mAutoframingOverride);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004891 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07004892
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004893 return false;
4894}
4895
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004896bool Camera3Device::RequestThread::overrideTestPattern(
4897 const sp<CaptureRequest> &request) {
4898 ATRACE_CALL();
4899
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004900 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004901
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004902 Mutex::Autolock l(mTriggerMutex);
4903
4904 bool changed = false;
4905
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004906 // For a multi-camera, the physical cameras support the same set of
4907 // test pattern modes as the logical camera.
4908 for (auto& settings : request->mSettingsList) {
4909 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004910
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004911 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4912 int32_t testPatternData[4] = {
4913 settings.mOriginalTestPatternData[0],
4914 settings.mOriginalTestPatternData[1],
4915 settings.mOriginalTestPatternData[2],
4916 settings.mOriginalTestPatternData[3]
4917 };
4918 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4919 testPatternMode = mCameraMute;
4920 testPatternData[0] = 0;
4921 testPatternData[1] = 0;
4922 testPatternData[2] = 0;
4923 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004924 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004925
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004926 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4927 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4928 if (testPatternEntry.count > 0) {
4929 if (testPatternEntry.data.i32[0] != testPatternMode) {
4930 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004931 changed = true;
4932 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004933 } else if (supportTestPatternModeKey) {
4934 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4935 &testPatternMode, 1);
4936 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004937 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004938
4939 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4940 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4941 if (testPatternColor.count >= 4) {
4942 for (size_t i = 0; i < 4; i++) {
4943 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4944 testPatternColor.data.i32[i] = testPatternData[i];
4945 changed = true;
4946 }
4947 }
4948 } else if (supportTestPatternDataKey) {
4949 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4950 testPatternData, 4);
4951 changed = true;
4952 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004953 }
4954
4955 return changed;
4956}
4957
Shuzhen Wangaf22e912023-04-11 16:03:17 -07004958bool Camera3Device::RequestThread::overrideSettingsOverride(
4959 const sp<CaptureRequest> &request) {
4960 ATRACE_CALL();
4961
4962 if (!mSupportSettingsOverride) return false;
4963
4964 Mutex::Autolock l(mTriggerMutex);
4965
4966 // For a multi-camera, only override the logical camera's metadata.
4967 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4968 camera_metadata_entry entry = metadata.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
4969 int32_t originalValue = request->mSettingsList.begin()->mOriginalSettingsOverride;
4970 if (mSettingsOverride != -1 &&
4971 (entry.count == 0 || entry.data.i32[0] != mSettingsOverride)) {
4972 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4973 &mSettingsOverride, 1);
4974 return true;
4975 } else if (mSettingsOverride == -1 &&
4976 (entry.count == 0 || entry.data.i32[0] != originalValue)) {
4977 metadata.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
4978 &originalValue, 1);
4979 return true;
4980 }
4981
4982 return false;
4983}
4984
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004985status_t Camera3Device::RequestThread::setHalInterface(
4986 sp<HalInterface> newHalInterface) {
4987 if (newHalInterface.get() == nullptr) {
4988 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4989 return DEAD_OBJECT;
4990 }
4991
4992 mInterface = newHalInterface;
4993
4994 return OK;
4995}
4996
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004997/**
4998 * PreparerThread inner class methods
4999 */
5000
5001Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005002 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005003 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004}
5005
5006Camera3Device::PreparerThread::~PreparerThread() {
5007 Thread::requestExitAndWait();
5008 if (mCurrentStream != nullptr) {
5009 mCurrentStream->cancelPrepare();
5010 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5011 mCurrentStream.clear();
5012 }
5013 clear();
5014}
5015
Ruben Brunkc78ac262015-08-13 17:58:46 -07005016status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005017 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005018 status_t res;
5019
5020 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005021 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005022
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005023 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005024 if (res == OK) {
5025 // No preparation needed, fire listener right off
5026 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005027 if (listener != NULL) {
5028 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005029 }
5030 return OK;
5031 } else if (res != NOT_ENOUGH_DATA) {
5032 return res;
5033 }
5034
5035 // Need to prepare, start up thread if necessary
5036 if (!mActive) {
5037 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5038 // isn't running
5039 Thread::requestExitAndWait();
5040 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5041 if (res != OK) {
5042 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005043 if (listener != NULL) {
5044 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005045 }
5046 return res;
5047 }
5048 mCancelNow = false;
5049 mActive = true;
5050 ALOGV("%s: Preparer stream started", __FUNCTION__);
5051 }
5052
5053 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005054 mPendingStreams.push_back(
5055 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005056 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5057
5058 return OK;
5059}
5060
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005061void Camera3Device::PreparerThread::pause() {
5062 ATRACE_CALL();
5063
5064 Mutex::Autolock l(mLock);
5065
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005066 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
5067 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005068 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5069 int currentMaxCount = mCurrentMaxCount;
5070 mPendingStreams.clear();
5071 mCancelNow = true;
5072 while (mActive) {
5073 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5074 if (res == TIMED_OUT) {
5075 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5076 return;
5077 } else if (res != OK) {
5078 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5079 return;
5080 }
5081 }
5082
5083 //Check whether the prepare thread was able to complete the current
5084 //stream. In case work is still pending emplace it along with the rest
5085 //of the streams in the pending list.
5086 if (currentStream != nullptr) {
5087 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005088 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005089 }
5090 }
5091
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005092 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005093 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005094 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005095 }
5096}
5097
5098status_t Camera3Device::PreparerThread::resume() {
5099 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005100 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005101 status_t res;
5102
5103 Mutex::Autolock l(mLock);
5104 sp<NotificationListener> listener = mListener.promote();
5105
5106 if (mActive) {
5107 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5108 return NO_INIT;
5109 }
5110
5111 auto it = mPendingStreams.begin();
5112 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005113 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005114 if (res == OK) {
5115 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005116 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005117 }
5118 it = mPendingStreams.erase(it);
5119 } else if (res != NOT_ENOUGH_DATA) {
5120 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5121 res, strerror(-res));
5122 it = mPendingStreams.erase(it);
5123 } else {
5124 it++;
5125 }
5126 }
5127
5128 if (mPendingStreams.empty()) {
5129 return OK;
5130 }
5131
5132 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5133 if (res != OK) {
5134 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5135 __FUNCTION__, res, strerror(-res));
5136 return res;
5137 }
5138 mCancelNow = false;
5139 mActive = true;
5140 ALOGV("%s: Preparer stream started", __FUNCTION__);
5141
5142 return OK;
5143}
5144
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005145status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005146 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005147 Mutex::Autolock l(mLock);
5148
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005149 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005150 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005151 }
5152 mPendingStreams.clear();
5153 mCancelNow = true;
5154
5155 return OK;
5156}
5157
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005158void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005159 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005160 Mutex::Autolock l(mLock);
5161 mListener = listener;
5162}
5163
5164bool Camera3Device::PreparerThread::threadLoop() {
5165 status_t res;
5166 {
5167 Mutex::Autolock l(mLock);
5168 if (mCurrentStream == nullptr) {
5169 // End thread if done with work
5170 if (mPendingStreams.empty()) {
5171 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5172 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5173 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5174 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005175 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005176 return false;
5177 }
5178
5179 // Get next stream to prepare
5180 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005181 mCurrentMaxCount = std::get<0>(*it);
5182 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005183 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005184 mPendingStreams.erase(it);
5185 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5186 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5187 } else if (mCancelNow) {
5188 mCurrentStream->cancelPrepare();
5189 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5190 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5191 mCurrentStream.clear();
5192 mCancelNow = false;
5193 return true;
5194 }
5195 }
5196
5197 res = mCurrentStream->prepareNextBuffer();
5198 if (res == NOT_ENOUGH_DATA) return true;
5199 if (res != OK) {
5200 // Something bad happened; try to recover by cancelling prepare and
5201 // signalling listener anyway
5202 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5203 mCurrentStream->getId(), res, strerror(-res));
5204 mCurrentStream->cancelPrepare();
5205 }
5206
5207 // This stream has finished, notify listener
5208 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005209 sp<NotificationListener> listener = mListener.promote();
5210 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005211 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5212 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005213 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005214 }
5215
5216 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5217 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005218 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005219
5220 return true;
5221}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005222
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005223status_t Camera3Device::RequestBufferStateMachine::initialize(
5224 sp<camera3::StatusTracker> statusTracker) {
5225 if (statusTracker == nullptr) {
5226 ALOGE("%s: statusTracker is null", __FUNCTION__);
5227 return BAD_VALUE;
5228 }
5229
5230 std::lock_guard<std::mutex> lock(mLock);
5231 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005232 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005233 return OK;
5234}
5235
5236bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5237 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005238 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005239 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005240 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005241 return true;
5242 }
5243 return false;
5244}
5245
5246void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5247 std::lock_guard<std::mutex> lock(mLock);
5248 if (!mRequestBufferOngoing) {
5249 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5250 return;
5251 }
5252 mRequestBufferOngoing = false;
5253 if (mStatus == RB_STATUS_PENDING_STOP) {
5254 checkSwitchToStopLocked();
5255 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005256 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005257}
5258
5259void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5260 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005261 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005262 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005263 return;
5264}
5265
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005266void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005267 std::lock_guard<std::mutex> lock(mLock);
5268 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005269 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5270 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005271 mInflightMapEmpty = false;
5272 if (mStatus == RB_STATUS_STOPPED) {
5273 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005274 }
5275 return;
5276}
5277
5278void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5279 std::lock_guard<std::mutex> lock(mLock);
5280 mRequestThreadPaused = true;
5281 if (mStatus == RB_STATUS_PENDING_STOP) {
5282 checkSwitchToStopLocked();
5283 }
5284 return;
5285}
5286
5287void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5288 std::lock_guard<std::mutex> lock(mLock);
5289 mInflightMapEmpty = true;
5290 if (mStatus == RB_STATUS_PENDING_STOP) {
5291 checkSwitchToStopLocked();
5292 }
5293 return;
5294}
5295
5296void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5297 std::lock_guard<std::mutex> lock(mLock);
5298 if (!checkSwitchToStopLocked()) {
5299 mStatus = RB_STATUS_PENDING_STOP;
5300 }
5301 return;
5302}
5303
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005304bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5305 std::lock_guard<std::mutex> lock(mLock);
5306 if (mRequestBufferOngoing) {
5307 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5308 __FUNCTION__);
5309 return false;
5310 }
5311 mSwitchedToOffline = true;
5312 mInflightMapEmpty = true;
5313 mRequestThreadPaused = true;
5314 mStatus = RB_STATUS_STOPPED;
5315 return true;
5316}
5317
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005318void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5319 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5320 if (statusTracker != nullptr) {
5321 if (active) {
5322 statusTracker->markComponentActive(mRequestBufferStatusId);
5323 } else {
5324 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5325 }
5326 }
5327}
5328
5329bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5330 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5331 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005332 return true;
5333 }
5334 return false;
5335}
5336
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005337bool Camera3Device::startRequestBuffer() {
5338 return mRequestBufferSM.startRequestBuffer();
5339}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005340
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005341void Camera3Device::endRequestBuffer() {
5342 mRequestBufferSM.endRequestBuffer();
5343}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005344
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005345nsecs_t Camera3Device::getWaitDuration() {
5346 return kBaseGetBufferWait + getExpectedInFlightDuration();
5347}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005348
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005349void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5350 mInterface->getInflightBufferKeys(out);
5351}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005352
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005353void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5354 mInterface->getInflightRequestBufferKeys(out);
5355}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005356
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005357std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5358 std::vector<sp<Camera3StreamInterface>> ret;
5359 bool hasInputStream = mInputStream != nullptr;
5360 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5361 if (hasInputStream) {
5362 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005363 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005364 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5365 ret.push_back(mOutputStreams[i]);
5366 }
5367 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5368 ret.push_back(mDeletedStreams[i]);
5369 }
5370 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005371}
5372
Emilian Peevcc0b7952020-01-07 13:54:47 -08005373void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5374 ATRACE_CALL();
5375
5376 if (offlineStreamIds == nullptr) {
5377 return;
5378 }
5379
5380 Mutex::Autolock il(mInterfaceLock);
5381
5382 auto streamIds = mOutputStreams.getStreamIds();
5383 bool hasInputStream = mInputStream != nullptr;
5384 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5385 offlineStreamIds->push_back(mInputStream->getId());
5386 }
5387
5388 for (const auto & streamId : streamIds) {
5389 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5390 // Streams that use the camera buffer manager are currently not supported in
5391 // offline mode
5392 if (stream->getOfflineProcessingSupport() &&
5393 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5394 offlineStreamIds->push_back(streamId);
5395 }
5396 }
5397}
5398
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005399status_t Camera3Device::setRotateAndCropAutoBehavior(
Jayant Chowdhary44d5f622023-09-20 03:11:41 +00005400 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue, bool fromHal) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005401 ATRACE_CALL();
Jayant Chowdhary44d5f622023-09-20 03:11:41 +00005402 // We shouldn't hold mInterfaceLock when called as an effect of a HAL
5403 // callback since this can lead to a deadlock : b/299348355.
5404 // mLock still protects state.
5405 std::optional<Mutex::Autolock> maybeMutex =
5406 fromHal ? std::nullopt : std::optional<Mutex::Autolock>(mInterfaceLock);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005407 Mutex::Autolock l(mLock);
5408 if (mRequestThread == nullptr) {
5409 return INVALID_OPERATION;
5410 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005411 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5412 return BAD_VALUE;
5413 }
5414 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005415 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5416}
5417
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005418status_t Camera3Device::setAutoframingAutoBehavior(
5419 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5420 ATRACE_CALL();
5421 Mutex::Autolock il(mInterfaceLock);
5422 Mutex::Autolock l(mLock);
5423 if (mRequestThread == nullptr) {
5424 return INVALID_OPERATION;
5425 }
Emilian Peevd865f0d2023-03-17 17:13:07 -07005426 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
5427 return BAD_VALUE;
5428 }
5429 mAutoframingOverride = autoframingValue;
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005430 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5431}
5432
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005433bool Camera3Device::supportsCameraMute() {
5434 Mutex::Autolock il(mInterfaceLock);
5435 Mutex::Autolock l(mLock);
5436
5437 return mSupportCameraMute;
5438}
5439
5440status_t Camera3Device::setCameraMute(bool enabled) {
5441 ATRACE_CALL();
5442 Mutex::Autolock il(mInterfaceLock);
5443 Mutex::Autolock l(mLock);
5444
5445 if (mRequestThread == nullptr || !mSupportCameraMute) {
5446 return INVALID_OPERATION;
5447 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005448 int32_t muteMode =
5449 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5450 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5451 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5452 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005453}
5454
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005455bool Camera3Device::supportsZoomOverride() {
5456 Mutex::Autolock il(mInterfaceLock);
5457 Mutex::Autolock l(mLock);
5458
5459 return mSupportZoomOverride;
5460}
5461
5462status_t Camera3Device::setZoomOverride(int32_t zoomOverride) {
5463 ATRACE_CALL();
5464 Mutex::Autolock il(mInterfaceLock);
5465 Mutex::Autolock l(mLock);
5466
5467 if (mRequestThread == nullptr || !mSupportZoomOverride) {
5468 return INVALID_OPERATION;
5469 }
5470
5471 return mRequestThread->setZoomOverride(zoomOverride);
5472}
5473
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005474status_t Camera3Device::injectCamera(const String8& injectedCamId,
5475 sp<CameraProviderManager> manager) {
5476 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5477 ATRACE_CALL();
5478 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005479 // When the camera device is active, injectCamera() and stopInjection() will call
5480 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5481 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5482 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5483 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5484 // waitUntilStateThenRelock().
5485 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005486
5487 status_t res = NO_ERROR;
5488 if (mInjectionMethods->isInjecting()) {
5489 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5490 return OK;
5491 } else {
5492 res = mInjectionMethods->stopInjection();
5493 if (res != OK) {
5494 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5495 __FUNCTION__, res);
5496 return res;
5497 }
5498 }
5499 }
5500
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005501 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005502 if (res != OK) {
5503 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5504 __FUNCTION__, res);
5505 return res;
5506 }
5507
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005508 // When the second display of android is cast to the remote device, and the opened camera is
5509 // also cast to the second display, in this case, because the camera has configured the streams
5510 // at this time, we can directly call injectCamera() to replace the internal camera with
5511 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005512 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5513 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5514
5515 camera3::camera_stream_configuration injectionConfig;
5516 std::vector<uint32_t> injectionBufferSizes;
5517 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5518 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5519 || injectionBufferSizes.size() <= 0) {
5520 ALOGE("Failed to inject camera due to abandoned configuration! "
5521 "mOperatingMode: %d injectionConfig.num_streams: %d "
5522 "injectionBufferSizes.size(): %zu", mOperatingMode,
5523 injectionConfig.num_streams, injectionBufferSizes.size());
5524 return DEAD_OBJECT;
5525 }
5526
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005527 res = mInjectionMethods->injectCamera(
5528 injectionConfig, injectionBufferSizes);
5529 if (res != OK) {
5530 ALOGE("Can't finish inject camera process!");
5531 return res;
5532 }
5533 }
5534
5535 return OK;
5536}
5537
5538status_t Camera3Device::stopInjection() {
5539 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5540 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005541 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005542 return mInjectionMethods->stopInjection();
5543}
5544
Shuzhen Wang16610a62022-12-15 22:38:07 -08005545void Camera3Device::overrideStreamUseCaseLocked() {
5546 if (mStreamUseCaseOverrides.size() == 0) {
5547 return;
5548 }
5549
5550 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5551 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5552 // Refer to CameraService::printHelp for details.
5553 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5554 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5555 outputStreamsIndices[i] = i;
5556 }
5557
5558 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5559 [&](int a, int b) -> bool {
5560
5561 auto formatScore = [](int format) {
5562 switch (format) {
5563 case HAL_PIXEL_FORMAT_BLOB:
5564 return 4;
5565 case HAL_PIXEL_FORMAT_RAW16:
5566 case HAL_PIXEL_FORMAT_RAW10:
5567 case HAL_PIXEL_FORMAT_RAW12:
5568 return 3;
5569 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5570 return 2;
5571 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5572 return 1;
5573 default:
5574 return 0;
5575 }
5576 };
5577
5578 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5579 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5580 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5581 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5582 if (sizeA > sizeB ||
5583 (sizeA == sizeB && formatAScore >= formatBScore)) {
5584 return true;
5585 } else {
5586 return false;
5587 }
5588 });
5589
5590 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5591 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5592 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5593 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5594 }
5595}
5596
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005597}; // namespace android