blob: 3ff985d8ef4d3f6b22dbd51703873d70f7bc26f7 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080073
74namespace android {
75
Austin Borger3560b7e2022-10-27 12:20:29 -070076Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool overrideToPortrait,
77 bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080078 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070079 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080086 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
Austin Borger3560b7e2022-10-27 12:20:29 -070098 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -080099 mOverrideToPortrait(overrideToPortrait),
Emilian Peevb9f83812023-03-17 17:13:07 -0700100 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
101 mComposerOutput(false),
Austin Borgerc8099762023-01-12 17:08:46 -0800102 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103{
104 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800106}
107
108Camera3Device::~Camera3Device()
109{
110 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700112 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800113}
114
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800116 return mId;
117}
118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119status_t Camera3Device::initializeCommonLocked() {
120
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700121 /** Start up status tracker thread */
122 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700124 if (res != OK) {
125 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
126 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800127 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700128 mStatusTracker.clear();
129 return res;
130 }
131
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700132 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700133 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700134
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700135 if (mUseHalBufManager) {
136 res = mRequestBufferSM.initialize(mStatusTracker);
137 if (res != OK) {
138 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
139 strerror(-res), res);
140 mInterface->close();
141 mStatusTracker.clear();
142 return res;
143 }
144 }
145
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800146 /** Create buffer manager */
147 mBufferManager = new Camera3BufferManager();
148
149 Vector<int32_t> sessionParamKeys;
150 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
151 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
152 if (sessionKeysEntry.count > 0) {
153 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
154 }
155
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700156 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
157 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
158 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
159 if (availableTestPatternModes.data.i32[i] ==
160 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
161 mSupportCameraMute = true;
162 mSupportTestPatternSolidColor = true;
163 break;
164 } else if (availableTestPatternModes.data.i32[i] ==
165 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
166 mSupportCameraMute = true;
167 mSupportTestPatternSolidColor = false;
168 }
169 }
170
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700171 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800172 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700173 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger3560b7e2022-10-27 12:20:29 -0700174 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800175 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800176 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700177 SET_ERR_L("Unable to start request queue thread: %s (%d)",
178 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800179 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800180 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800181 return res;
182 }
183
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700184 mPreparerThread = new PreparerThread();
185
Ruben Brunk183f0562015-08-12 12:55:02 -0700186 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800187 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400188 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700189 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700190 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800191 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800192
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800193 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800194 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800195 camera_metadata_entry timestampSource =
196 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
197 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
198 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800199 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800200 }
201
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700202 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100203 camera_metadata_entry partialResultsCount =
204 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
205 if (partialResultsCount.count > 0) {
206 mNumPartialResults = partialResultsCount.data.i32[0];
207 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700208 }
209
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800210 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
211 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700212 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700213 if (res != OK) {
214 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
215 return res;
216 }
217 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800219 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800220 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800221
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700222 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
223 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
224 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
225 }
226
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800227 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
228 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
229 }
230
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800231 // Hidl/AidlCamera3DeviceInjectionMethods
232 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800233
Ravneet74cd3732022-03-30 05:33:03 +0000234 /** Start watchdog thread */
235 mCameraServiceWatchdog = new CameraServiceWatchdog();
236 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
237 if (res != OK) {
238 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
239 strerror(-res), res);
240 return res;
241 }
242
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800243 return OK;
244}
245
246status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700247 return disconnectImpl();
248}
249
250status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800251 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700252 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800253
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700254 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700255 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 Mutex::Autolock il(mInterfaceLock);
258 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
259 {
260 Mutex::Autolock l(mLock);
261 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000263 if (mRequestThread != NULL) {
264 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
265 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800266 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000267 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800268 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000269 } else {
270 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
271 if (res != OK) {
272 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
273 maxExpectedDuration);
274 // Continue to close device even in case of error
275 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800276 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700277 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000278 // Signal to request thread that we're not expecting any
279 // more requests. This will be true since once we're in
280 // disconnect and we've cleared off the request queue, the
281 // request thread can't receive any new requests through
282 // binder calls - since disconnect holds
283 // mBinderSerialization lock.
284 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700285 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800286
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800287 if (mStatus == STATUS_ERROR) {
288 CLOGE("Shutting down in an error state");
289 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800291 if (mStatusTracker != NULL) {
292 mStatusTracker->requestExit();
293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800295 if (mRequestThread != NULL) {
296 mRequestThread->requestExit();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
300 for (size_t i = 0; i < mOutputStreams.size(); i++) {
301 streams.push_back(mOutputStreams[i]);
302 }
303 if (mInputStream != nullptr) {
304 streams.push_back(mInputStream);
305 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700306 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
309 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
311 // HAL may be in a bad state, so waiting for request thread
312 // (which may be stuck in the HAL processCaptureRequest call)
313 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800314 // give up mInterfaceLock here and then lock it again. Could this lead
315 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 mRequestThread->join();
317 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800319 Mutex::Autolock il(mInterfaceLock);
320 if (mStatusTracker != NULL) {
321 mStatusTracker->join();
322 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800323
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800324 if (mInjectionMethods->isInjecting()) {
325 mInjectionMethods->stopInjection();
326 }
327
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800328 HalInterface* interface;
329 {
330 Mutex::Autolock l(mLock);
331 mRequestThread.clear();
332 Mutex::Autolock stLock(mTrackerLock);
333 mStatusTracker.clear();
334 interface = mInterface.get();
335 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700336
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800337 // Call close without internal mutex held, as the HAL close may need to
338 // wait on assorted callbacks,etc, to complete before it can return.
Ravneet98ffa752022-03-02 07:22:46 +0000339 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700340
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800341 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800342
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800343 {
344 Mutex::Autolock l(mLock);
345 mInterface->clear();
346 mOutputStreams.clear();
347 mInputStream.clear();
348 mDeletedStreams.clear();
349 mBufferManager.clear();
350 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
351 }
352
353 for (auto& weakStream : streams) {
354 sp<Camera3StreamInterface> stream = weakStream.promote();
355 if (stream != nullptr) {
356 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
357 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
358 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700359 }
360 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700361 ALOGI("%s: X", __FUNCTION__);
Ravneet98ffa752022-03-02 07:22:46 +0000362
363 if (mCameraServiceWatchdog != NULL) {
364 mCameraServiceWatchdog->requestExit();
365 mCameraServiceWatchdog.clear();
366 }
367
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700368 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800369}
370
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700371// For dumping/debugging only -
372// try to acquire a lock a few times, eventually give up to proceed with
373// debug/dump operations
374bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
375 bool gotLock = false;
376 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
377 if (lock.tryLock() == NO_ERROR) {
378 gotLock = true;
379 break;
380 } else {
381 usleep(kDumpSleepDuration);
382 }
383 }
384 return gotLock;
385}
386
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800387nsecs_t Camera3Device::getMonoToBoottimeOffset() {
388 // try three times to get the clock offset, choose the one
389 // with the minimum gap in measurements.
390 const int tries = 3;
391 nsecs_t bestGap, measured;
392 for (int i = 0; i < tries; ++i) {
393 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
394 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
395 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
396 const nsecs_t gap = tmono2 - tmono;
397 if (i == 0 || gap < bestGap) {
398 bestGap = gap;
399 measured = tbase - ((tmono + tmono2) >> 1);
400 }
401 }
402 return measured;
403}
404
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800405ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
406 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700407 // Get max jpeg size (area-wise) for default sensor pixel mode
408 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800409 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700410 /*isUltraHighResolutionSensor*/false);
411 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
412 // not ultra high res sensor
413 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800414 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700415 /*isUltraHighResolution*/true);
416 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800417 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
418 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700419 return BAD_VALUE;
420 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700421 bool useMaxSensorPixelModeThreshold = false;
422 if (uhrMaxJpegResolution.width != 0 &&
423 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
424 // Use the ultra high res max jpeg size and max jpeg buffer size
425 useMaxSensorPixelModeThreshold = true;
426 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700427
Zhijun Hef7da0962014-04-24 13:27:56 -0700428 // Get max jpeg buffer size
429 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800430 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700431 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800432 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
433 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700434 return BAD_VALUE;
435 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700436 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700437
438 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
439 if (useMaxSensorPixelModeThreshold) {
440 maxJpegBufferSize =
441 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
442 maxDefaultJpegResolution, maxJpegBufferSize);
443 chosenMaxJpegResolution = uhrMaxJpegResolution;
444 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800445 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700446
447 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700448 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700449 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800450 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
451 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700452 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800453 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
454 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700455 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700456 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700457 return jpegBufferSize;
458}
459
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800460ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700461 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800462 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700463 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800464 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
465 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700466 return BAD_VALUE;
467 }
468 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
469 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
470 return maxBytesForPointCloud;
471}
472
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800473ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
474 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800475 const int PER_CONFIGURATION_SIZE = 3;
476 const int WIDTH_OFFSET = 0;
477 const int HEIGHT_OFFSET = 1;
478 const int SIZE_OFFSET = 2;
479 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800480 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800481 camera3::SessionConfigurationUtils::getAppropriateModeTag(
482 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
483 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800484 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800485 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800486 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
487 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800488 return BAD_VALUE;
489 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700490
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800491 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
492 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
493 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
494 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
495 }
496 }
497
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800498 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
499 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800500 return BAD_VALUE;
501}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700502
Jing Mikec7f9b132023-03-12 11:12:04 +0800503status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800504 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700505
506 // Try to lock, but continue in case of failure (to avoid blocking in
507 // deadlocks)
508 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
509 bool gotLock = tryLockSpinRightRound(mLock);
510
511 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
513 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700514 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800515 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
516 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700517
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800518 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700519
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800520 String16 templatesOption("-t");
521 int n = args.size();
522 for (int i = 0; i < n; i++) {
523 if (args[i] == templatesOption) {
524 dumpTemplates = true;
525 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000526 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700527 if (i + 1 < n) {
528 String8 monitorTags = String8(args[i + 1]);
529 if (monitorTags == "off") {
530 mTagMonitor.disableMonitoring();
531 } else {
532 mTagMonitor.parseTagsToMonitor(monitorTags);
533 }
534 } else {
535 mTagMonitor.disableMonitoring();
536 }
537 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800538 }
539
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800540 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800542 const char *status =
543 mStatus == STATUS_ERROR ? "ERROR" :
544 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700545 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
546 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800547 mStatus == STATUS_ACTIVE ? "ACTIVE" :
548 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700549
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800550 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700551 if (mStatus == STATUS_ERROR) {
552 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
553 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800555 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000556 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
557 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
558 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800559 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800560
561 if (mInputStream != NULL) {
562 write(fd, lines.string(), lines.size());
563 mInputStream->dump(fd, args);
564 } else {
565 lines.appendFormat(" No input stream.\n");
566 write(fd, lines.string(), lines.size());
567 }
568 for (size_t i = 0; i < mOutputStreams.size(); i++) {
569 mOutputStreams[i]->dump(fd,args);
570 }
571
Zhijun He431503c2016-03-07 17:30:16 -0800572 if (mBufferManager != NULL) {
573 lines = String8(" Camera3 Buffer Manager:\n");
574 write(fd, lines.string(), lines.size());
575 mBufferManager->dump(fd, args);
576 }
Zhijun He125684a2015-12-26 15:07:30 -0800577
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700578 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700579 if (mInFlightLock.try_lock()) {
580 if (mInFlightMap.size() == 0) {
581 lines.append(" None\n");
582 } else {
583 for (size_t i = 0; i < mInFlightMap.size(); i++) {
584 InFlightRequest r = mInFlightMap.valueAt(i);
585 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
586 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
587 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
588 r.numBuffersLeft);
589 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700590 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700591 mInFlightLock.unlock();
592 } else {
593 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700594 }
595 write(fd, lines.string(), lines.size());
596
Shuzhen Wang686f6442017-06-20 16:16:04 -0700597 if (mRequestThread != NULL) {
598 mRequestThread->dumpCaptureRequestLatency(fd,
599 " ProcessCaptureRequest latency histogram:");
600 }
601
Igor Murashkin1e479c02013-09-06 16:55:14 -0700602 {
603 lines = String8(" Last request sent:\n");
604 write(fd, lines.string(), lines.size());
605
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700607 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
608 }
609
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700611 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 "TEMPLATE_PREVIEW",
613 "TEMPLATE_STILL_CAPTURE",
614 "TEMPLATE_VIDEO_RECORD",
615 "TEMPLATE_VIDEO_SNAPSHOT",
616 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800617 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800618 };
619
Emilian Peevf4816702020-04-03 15:44:51 -0700620 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 camera_metadata_t *templateRequest = nullptr;
622 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700623 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 lines.append(" Not supported\n");
627 write(fd, lines.string(), lines.size());
628 } else {
629 write(fd, lines.string(), lines.size());
630 dump_indented_camera_metadata(templateRequest,
631 fd, /*verbosity*/2, /*indentation*/8);
632 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800634 }
635 }
636
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700637 mTagMonitor.dumpMonitoredMetadata(fd);
638
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800640 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800642 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 if (gotLock) mLock.unlock();
646 if (gotInterfaceLock) mInterfaceLock.unlock();
647
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800648 return OK;
649}
650
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700651status_t Camera3Device::startWatchingTags(const String8 &tags) {
652 mTagMonitor.parseTagsToMonitor(tags);
653 return OK;
654}
655
656status_t Camera3Device::stopWatchingTags() {
657 mTagMonitor.disableMonitoring();
658 return OK;
659}
660
661status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
662 mTagMonitor.getLatestMonitoredTagEvents(out);
663 return OK;
664}
665
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800666const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
669 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700670 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800671 mStatus == STATUS_ERROR ?
672 "when in error state" : "before init");
673 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700674 if (physicalId.isEmpty()) {
675 return mDeviceInfo;
676 } else {
677 std::string id(physicalId.c_str());
678 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
679 return mPhysicalDeviceInfoMap.at(id);
680 } else {
681 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
682 return mDeviceInfo;
683 }
684 }
685}
686
687const CameraMetadata& Camera3Device::info() const {
688 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800689 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800690}
691
Jianing Wei90e59c92014-03-12 18:29:36 -0700692status_t Camera3Device::checkStatusOkToCaptureLocked() {
693 switch (mStatus) {
694 case STATUS_ERROR:
695 CLOGE("Device has encountered a serious error");
696 return INVALID_OPERATION;
697 case STATUS_UNINITIALIZED:
698 CLOGE("Device not initialized");
699 return INVALID_OPERATION;
700 case STATUS_UNCONFIGURED:
701 case STATUS_CONFIGURED:
702 case STATUS_ACTIVE:
703 // OK
704 break;
705 default:
706 SET_ERR_L("Unexpected status: %d", mStatus);
707 return INVALID_OPERATION;
708 }
709 return OK;
710}
711
712status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000713 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700714 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700715 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700716 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700717 if (requestList == NULL) {
718 CLOGE("requestList cannot be NULL.");
719 return BAD_VALUE;
720 }
721
Jianing Weicb0652e2014-03-12 18:29:36 -0700722 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000723 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700724 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
725 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
726 ++metadataIt, ++surfaceMapIt) {
727 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700728 if (newRequest == 0) {
729 CLOGE("Can't create capture request");
730 return BAD_VALUE;
731 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700732
Shuzhen Wang9d066012016-09-30 11:30:20 -0700733 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700734 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700735
Jianing Weicb0652e2014-03-12 18:29:36 -0700736 // Setup burst Id and request Id
737 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800738 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
739 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700740 CLOGE("RequestID does not exist in metadata");
741 return BAD_VALUE;
742 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800743 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700744
Jianing Wei90e59c92014-03-12 18:29:36 -0700745 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700746
747 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700748 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
750 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
751 return BAD_VALUE;
752 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700753
754 // Setup batch size if this is a high speed video recording request.
755 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
756 auto firstRequest = requestList->begin();
757 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
758 if (outputStream->isVideoStream()) {
759 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800760 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700761 break;
762 }
763 }
764 }
765
Jianing Wei90e59c92014-03-12 18:29:36 -0700766 return OK;
767}
768
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800769status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771
Emilian Peevaebbe412018-01-15 13:53:24 +0000772 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700773 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000774 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700775
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800776 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777}
778
Emilian Peevaebbe412018-01-15 13:53:24 +0000779void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700780 std::list<const SurfaceMap>& surfaceMaps,
781 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000782 PhysicalCameraSettingsList requestList;
783 requestList.push_back({std::string(getId().string()), request});
784 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785
786 SurfaceMap surfaceMap;
787 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
788 // With no surface list passed in, stream and surface will have 1-to-1
789 // mapping. So the surface index is 0 for each stream in the surfaceMap.
790 for (size_t i = 0; i < streams.count; i++) {
791 surfaceMap[streams.data.i32[i]].push_back(0);
792 }
793 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800794}
795
Jianing Wei90e59c92014-03-12 18:29:36 -0700796status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000797 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 const std::list<const SurfaceMap> &surfaceMaps,
799 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 /*out*/
801 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700803 nsecs_t requestTimeNs = systemTime();
804
Jianing Wei90e59c92014-03-12 18:29:36 -0700805 Mutex::Autolock il(mInterfaceLock);
806 Mutex::Autolock l(mLock);
807
808 status_t res = checkStatusOkToCaptureLocked();
809 if (res != OK) {
810 // error logged by previous call
811 return res;
812 }
813
814 RequestList requestList;
815
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700817 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700818 if (res != OK) {
819 // error logged by previous call
820 return res;
821 }
822
823 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700824 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700826 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 }
828
829 if (res == OK) {
830 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
831 if (res != OK) {
832 SET_ERR_L("Can't transition to active in %f seconds!",
833 kActiveTimeout/1e9);
834 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700836 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837 } else {
838 CLOGE("Cannot queue request. Impossible.");
839 return BAD_VALUE;
840 }
841
842 return res;
843}
844
Emilian Peevaebbe412018-01-15 13:53:24 +0000845status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700847 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 ATRACE_CALL();
849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700851}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
854 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000859 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863}
864
Emilian Peevaebbe412018-01-15 13:53:24 +0000865status_t Camera3Device::setStreamingRequestList(
866 const List<const PhysicalCameraSettingsList> &requestsList,
867 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 ATRACE_CALL();
869
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700871}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872
873sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800875 status_t res;
876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700877 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800878 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
879 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000880 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700881 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700882 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800883 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700884 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700886 } else if (mStatus == STATUS_UNCONFIGURED) {
887 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700888 CLOGE("No streams configured");
889 return NULL;
890 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 }
892
Shuzhen Wang0129d522016-10-30 22:43:41 -0700893 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800895}
896
Jianing Weicb0652e2014-03-12 18:29:36 -0700897status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800900 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800901
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 switch (mStatus) {
903 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700904 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800905 return INVALID_OPERATION;
906 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700907 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800908 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 case STATUS_UNCONFIGURED:
910 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800911 case STATUS_ACTIVE:
912 // OK
913 break;
914 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700915 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800916 return INVALID_OPERATION;
917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700919
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700920 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800921}
922
923status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
924 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700927 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800928}
929
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700930status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800931 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700934 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700935 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
937 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700938
939 status_t res;
940 bool wasActive = false;
941
942 switch (mStatus) {
943 case STATUS_ERROR:
944 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
945 return INVALID_OPERATION;
946 case STATUS_UNINITIALIZED:
947 ALOGE("%s: Device not initialized", __FUNCTION__);
948 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 case STATUS_UNCONFIGURED:
950 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700951 // OK
952 break;
953 case STATUS_ACTIVE:
954 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700955 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700956 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700957 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700958 return res;
959 }
960 wasActive = true;
961 break;
962 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700963 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700964 return INVALID_OPERATION;
965 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700966 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700967
968 if (mInputStream != 0) {
969 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
970 return INVALID_OPERATION;
971 }
972
973 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
974 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700975 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700976
977 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800978 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979
980 *id = mNextStreamId++;
981
982 // Continue captures if active at start
983 if (wasActive) {
984 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100985 // Reuse current operating mode and session parameters for new stream config
986 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700987 if (res != OK) {
988 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
989 __FUNCTION__, mNextStreamId, strerror(-res), res);
990 return res;
991 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700992 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700993 }
994
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700996 return OK;
997}
998
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700999status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001000 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001001 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001002 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001003 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1004 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001005 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -08001006 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001007 ATRACE_CALL();
1008
1009 if (consumer == nullptr) {
1010 ALOGE("%s: consumer must not be null", __FUNCTION__);
1011 return BAD_VALUE;
1012 }
1013
1014 std::vector<sp<Surface>> consumers;
1015 consumers.push_back(consumer);
1016
1017 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001018 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001019 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001020 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001021}
1022
1023static bool isRawFormat(int format) {
1024 switch (format) {
1025 case HAL_PIXEL_FORMAT_RAW16:
1026 case HAL_PIXEL_FORMAT_RAW12:
1027 case HAL_PIXEL_FORMAT_RAW10:
1028 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1029 return true;
1030 default:
1031 return false;
1032 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001033}
1034
1035status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1036 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001037 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001038 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001039 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001040 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1041 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001042 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001043
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001044 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001045 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001046 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001047 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001048 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001049 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1050 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001051 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001052 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001053 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001054
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 status_t res;
1056 bool wasActive = false;
1057
1058 switch (mStatus) {
1059 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001060 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001061 return INVALID_OPERATION;
1062 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001063 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001065 case STATUS_UNCONFIGURED:
1066 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001067 // OK
1068 break;
1069 case STATUS_ACTIVE:
1070 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001071 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001072 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001073 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 return res;
1075 }
1076 wasActive = true;
1077 break;
1078 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001079 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080 return INVALID_OPERATION;
1081 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001082 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083
1084 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001085
Shuzhen Wang0129d522016-10-30 22:43:41 -07001086 if (consumers.size() == 0 && !hasDeferredConsumer) {
1087 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1088 return BAD_VALUE;
1089 }
Zhijun He5d677d12016-05-29 16:52:39 -07001090
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001092 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1093 return BAD_VALUE;
1094 }
1095
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001096 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1097 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1098 // be found in only one sensor pixel mode.
1099 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1100 return BAD_VALUE;
1101 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001102 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001103 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001104 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001105 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001106 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001107 if (blobBufferSize <= 0) {
1108 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1109 return BAD_VALUE;
1110 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001111 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1112 blobBufferSize = width * height;
1113 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001114 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001115 if (blobBufferSize <= 0) {
1116 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1117 return BAD_VALUE;
1118 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001119 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001121 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001122 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001123 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001124 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001125 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001126 bool maxResolution =
1127 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1128 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001129 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1130 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001131 if (rawOpaqueBufferSize <= 0) {
1132 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1133 return BAD_VALUE;
1134 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001135 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001136 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001137 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001138 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001139 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001140 } else if (isShared) {
1141 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1142 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001143 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001144 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001145 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001146 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001147 newStream = new Camera3OutputStream(mNextStreamId,
1148 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001149 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001150 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001151 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001153 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001154 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001155 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001156 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001157 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 }
Emilian Peev40ead602017-09-26 15:46:36 +01001159
1160 size_t consumerCount = consumers.size();
1161 for (size_t i = 0; i < consumerCount; i++) {
1162 int id = newStream->getSurfaceId(consumers[i]);
1163 if (id < 0) {
1164 SET_ERR_L("Invalid surface id");
1165 return BAD_VALUE;
1166 }
1167 if (surfaceIds != nullptr) {
1168 surfaceIds->push_back(id);
1169 }
1170 }
1171
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173
Emilian Peev08dd2452017-04-06 16:55:14 +01001174 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001175
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001176 newStream->setImageDumpMask(mImageDumpMask);
1177
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 res = mOutputStreams.add(mNextStreamId, newStream);
1179 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181 return res;
1182 }
1183
Shuzhen Wang316781a2020-08-18 18:11:01 -07001184 mSessionStatsBuilder.addStream(mNextStreamId);
1185
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001187 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188
1189 // Continue captures if active at start
1190 if (wasActive) {
1191 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001192 // Reuse current operating mode and session parameters for new stream config
1193 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001195 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1196 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return res;
1198 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001201 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001203}
1204
Emilian Peev710c1422017-08-30 11:19:38 +01001205status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001207 if (nullptr == streamInfo) {
1208 return BAD_VALUE;
1209 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 switch (mStatus) {
1214 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001215 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return INVALID_OPERATION;
1217 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 case STATUS_UNCONFIGURED:
1221 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 case STATUS_ACTIVE:
1223 // OK
1224 break;
1225 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001226 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 return INVALID_OPERATION;
1228 }
1229
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001230 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1231 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001233 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 }
1235
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001236 streamInfo->width = stream->getWidth();
1237 streamInfo->height = stream->getHeight();
1238 streamInfo->format = stream->getFormat();
1239 streamInfo->dataSpace = stream->getDataSpace();
1240 streamInfo->formatOverridden = stream->isFormatOverridden();
1241 streamInfo->originalFormat = stream->getOriginalFormat();
1242 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1243 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001244 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
1248status_t Camera3Device::setStreamTransform(int id,
1249 int transform) {
1250 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 switch (mStatus) {
1255 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001256 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 return INVALID_OPERATION;
1258 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001259 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001261 case STATUS_UNCONFIGURED:
1262 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 case STATUS_ACTIVE:
1264 // OK
1265 break;
1266 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001267 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 return INVALID_OPERATION;
1269 }
1270
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001271 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1272 if (stream == nullptr) {
1273 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001274 return BAD_VALUE;
1275 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001276 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001277}
1278
1279status_t Camera3Device::deleteStream(int id) {
1280 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 Mutex::Autolock l(mLock);
1283 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001284
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001285 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001286
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 // CameraDevice semantics require device to already be idle before
1288 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001290 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001291 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 }
1293
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001294 if (mStatus == STATUS_ERROR) {
1295 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1296 __FUNCTION__, mId.string());
1297 return -EBUSY;
1298 }
1299
Igor Murashkin2fba5842013-04-22 14:03:54 -07001300 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001301 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 if (mInputStream != NULL && id == mInputStream->getId()) {
1303 deletedStream = mInputStream;
1304 mInputStream.clear();
1305 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001306 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001307 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 return BAD_VALUE;
1309 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001310 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001311 }
1312
1313 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001314 if (stream != nullptr) {
1315 deletedStream = stream;
1316 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317 }
1318
1319 // Free up the stream endpoint so that it can be used by some other stream
1320 res = deletedStream->disconnect();
1321 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001322 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001323 // fall through since we want to still list the stream as deleted.
1324 }
1325 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001326 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001327
1328 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001329}
1330
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001331status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001332 ATRACE_CALL();
1333 ALOGV("%s: E", __FUNCTION__);
1334
1335 Mutex::Autolock il(mInterfaceLock);
1336 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001337
Emilian Peev811d2952018-05-25 11:08:40 +01001338 // In case the client doesn't include any session parameter, try a
1339 // speculative configuration using the values from the last cached
1340 // default request.
1341 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001342 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001343 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1344 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1345 mLastTemplateId);
1346 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1347 operatingMode);
1348 }
1349
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001350 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1351}
1352
1353status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1354 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001355 //Filter out any incoming session parameters
1356 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001357 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1358 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001359 CameraMetadata filteredParams(availableSessionKeys.count);
1360 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1361 filteredParams.getAndLock());
1362 set_camera_metadata_vendor_id(meta, mVendorTagId);
1363 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001364 if (availableSessionKeys.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07001365 bool rotateAndCropSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001366 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1367 camera_metadata_ro_entry entry = params.find(
1368 availableSessionKeys.data.i32[i]);
1369 if (entry.count > 0) {
1370 filteredParams.update(entry);
1371 }
Emilian Peevb9f83812023-03-17 17:13:07 -07001372 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1373 rotateAndCropSessionKey = true;
1374 }
1375 }
1376
1377 if (rotateAndCropSessionKey) {
1378 sp<CaptureRequest> request = new CaptureRequest();
1379 PhysicalCameraSettings settingsList;
1380 settingsList.metadata = filteredParams;
1381 request->mSettingsList.push_back(settingsList);
1382
1383 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1384 if (rotateAndCropEntry.count > 0 &&
1385 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1386 request->mRotateAndCropAuto = true;
1387 } else {
1388 request->mRotateAndCropAuto = false;
1389 }
1390
1391 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1392 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001393 }
1394 }
1395
1396 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001397}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001398
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001399status_t Camera3Device::getInputBufferProducer(
1400 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001401 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001402 Mutex::Autolock il(mInterfaceLock);
1403 Mutex::Autolock l(mLock);
1404
1405 if (producer == NULL) {
1406 return BAD_VALUE;
1407 } else if (mInputStream == NULL) {
1408 return INVALID_OPERATION;
1409 }
1410
1411 return mInputStream->getInputBufferProducer(producer);
1412}
1413
Emilian Peevf4816702020-04-03 15:44:51 -07001414status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001415 CameraMetadata *request) {
1416 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001417 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001418
Emilian Peevf4816702020-04-03 15:44:51 -07001419 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001420 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001421 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001422 return BAD_VALUE;
1423 }
1424
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001425 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001427 {
1428 Mutex::Autolock l(mLock);
1429 switch (mStatus) {
1430 case STATUS_ERROR:
1431 CLOGE("Device has encountered a serious error");
1432 return INVALID_OPERATION;
1433 case STATUS_UNINITIALIZED:
1434 CLOGE("Device is not initialized!");
1435 return INVALID_OPERATION;
1436 case STATUS_UNCONFIGURED:
1437 case STATUS_CONFIGURED:
1438 case STATUS_ACTIVE:
1439 // OK
1440 break;
1441 default:
1442 SET_ERR_L("Unexpected status: %d", mStatus);
1443 return INVALID_OPERATION;
1444 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001445
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001446 if (!mRequestTemplateCache[templateId].isEmpty()) {
1447 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001448 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001449 return OK;
1450 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001451 }
1452
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001453 camera_metadata_t *rawRequest;
1454 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001455 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001456
1457 {
1458 Mutex::Autolock l(mLock);
1459 if (res == BAD_VALUE) {
1460 ALOGI("%s: template %d is not supported on this camera device",
1461 __FUNCTION__, templateId);
1462 return res;
1463 } else if (res != OK) {
1464 CLOGE("Unable to construct request template %d: %s (%d)",
1465 templateId, strerror(-res), res);
1466 return res;
1467 }
1468
1469 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1470 mRequestTemplateCache[templateId].acquire(rawRequest);
1471
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001472 // Override the template request with zoomRatioMapper
1473 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1474 &mRequestTemplateCache[templateId]);
1475 if (res != OK) {
1476 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1477 templateId, strerror(-res), res);
1478 return res;
1479 }
1480
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001481 // Fill in JPEG_QUALITY if not available
1482 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1483 static const uint8_t kDefaultJpegQuality = 95;
1484 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1485 &kDefaultJpegQuality, 1);
1486 }
1487
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001488 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001489 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001491 return OK;
1492}
1493
1494status_t Camera3Device::waitUntilDrained() {
1495 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001497 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001500 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001501}
1502
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001503status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 switch (mStatus) {
1505 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 ALOGV("%s: Already idle", __FUNCTION__);
1508 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001509 case STATUS_CONFIGURED:
1510 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 case STATUS_ERROR:
1512 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 break;
1515 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001516 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 return INVALID_OPERATION;
1518 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001519 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1520 maxExpectedDuration);
1521 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001522 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001523 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001524 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1525 res);
1526 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001527 return res;
1528}
1529
Ruben Brunk183f0562015-08-12 12:55:02 -07001530void Camera3Device::internalUpdateStatusLocked(Status status) {
1531 mStatus = status;
1532 mRecentStatusUpdates.add(mStatus);
1533 mStatusChanged.broadcast();
1534}
1535
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001537status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001538 if (mRequestThread.get() != nullptr) {
1539 mRequestThread->setPaused(true);
1540 } else {
1541 return NO_INIT;
1542 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001544 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1545 maxExpectedDuration);
1546 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 if (res != OK) {
1548 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001549 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 }
1551
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 return res;
1553}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555// Resume after internalPauseAndWaitLocked
1556status_t Camera3Device::internalResumeLocked() {
1557 status_t res;
1558
1559 mRequestThread->setPaused(false);
1560
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001561 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1562 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1564 if (res != OK) {
1565 SET_ERR_L("Can't transition to active in %f seconds!",
1566 kActiveTimeout/1e9);
1567 }
1568 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001570}
1571
Ruben Brunk183f0562015-08-12 12:55:02 -07001572status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001574
1575 size_t startIndex = 0;
1576 if (mStatusWaiters == 0) {
1577 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1578 // this status list
1579 mRecentStatusUpdates.clear();
1580 } else {
1581 // If other threads are waiting on updates to this status list, set the position of the
1582 // first element that this list will check rather than clearing the list.
1583 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 }
1585
Ruben Brunk183f0562015-08-12 12:55:02 -07001586 mStatusWaiters++;
1587
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001588 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001589 if (!active && mUseHalBufManager) {
1590 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001591 if (mStatus == STATUS_ACTIVE) {
1592 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001593 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001594 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001595 mRequestBufferSM.onWaitUntilIdle();
1596 }
1597
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001598 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001599 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001601 if (active == (mStatus == STATUS_ACTIVE)) {
1602 // Desired state is current
1603 break;
1604 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001605
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001606 nsecs_t timeElapsed = systemTime() - startTime;
1607 nsecs_t timeToWait = timeout - timeElapsed;
1608 if (timeToWait <= 0) {
1609 // Thread woke up spuriously but has timed out since.
1610 // Force out of loop with TIMED_OUT result.
1611 res = TIMED_OUT;
1612 break;
1613 }
1614 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001615 if (res != OK) break;
1616
Ruben Brunk183f0562015-08-12 12:55:02 -07001617 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1618 // transitions.
1619 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1620 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1621 __FUNCTION__);
1622
1623 // Encountered desired state since we began waiting
1624 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1626 stateSeen = true;
1627 break;
1628 }
1629 }
1630 } while (!stateSeen);
1631
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001632 if (signalPipelineDrain) {
1633 mRequestThread->resetPipelineDrain();
1634 }
1635
Ruben Brunk183f0562015-08-12 12:55:02 -07001636 mStatusWaiters--;
1637
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 return res;
1639}
1640
1641
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001642status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001644 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001645
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001646 if (listener != NULL && mListener != NULL) {
1647 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1648 }
1649 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001650 mRequestThread->setNotificationListener(listener);
1651 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001652
1653 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001654}
1655
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001656bool Camera3Device::willNotify3A() {
1657 return false;
1658}
1659
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001661 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001662 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001664 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001665 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1666 if (st == std::cv_status::timeout) {
1667 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001668 }
1669 }
1670 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001671}
1672
Jianing Weicb0652e2014-03-12 18:29:36 -07001673status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001675 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001677 if (mResultQueue.empty()) {
1678 return NOT_ENOUGH_DATA;
1679 }
1680
Jianing Weicb0652e2014-03-12 18:29:36 -07001681 if (frame == NULL) {
1682 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1683 return BAD_VALUE;
1684 }
1685
1686 CaptureResult &result = *(mResultQueue.begin());
1687 frame->mResultExtras = result.mResultExtras;
1688 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001689 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001690 mResultQueue.erase(mResultQueue.begin());
1691
1692 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693}
1694
1695status_t Camera3Device::triggerAutofocus(uint32_t id) {
1696 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001697 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001699 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1700 // Mix-in this trigger into the next request and only the next request.
1701 RequestTrigger trigger[] = {
1702 {
1703 ANDROID_CONTROL_AF_TRIGGER,
1704 ANDROID_CONTROL_AF_TRIGGER_START
1705 },
1706 {
1707 ANDROID_CONTROL_AF_TRIGGER_ID,
1708 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001709 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001710 };
1711
1712 return mRequestThread->queueTrigger(trigger,
1713 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001714}
1715
1716status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1717 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001718 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001719
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001720 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1721 // Mix-in this trigger into the next request and only the next request.
1722 RequestTrigger trigger[] = {
1723 {
1724 ANDROID_CONTROL_AF_TRIGGER,
1725 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1726 },
1727 {
1728 ANDROID_CONTROL_AF_TRIGGER_ID,
1729 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001730 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001731 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001732
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001733 return mRequestThread->queueTrigger(trigger,
1734 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001735}
1736
1737status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1738 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001739 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001741 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1742 // Mix-in this trigger into the next request and only the next request.
1743 RequestTrigger trigger[] = {
1744 {
1745 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1746 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1747 },
1748 {
1749 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1750 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001751 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001752 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001754 return mRequestThread->queueTrigger(trigger,
1755 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001756}
1757
Jianing Weicb0652e2014-03-12 18:29:36 -07001758status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001759 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001760 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001761 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001762
Zhijun He7ef20392014-04-21 16:04:17 -07001763 {
1764 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001765
1766 // b/116514106 "disconnect()" can get called twice for the same device. The
1767 // camera device will not be initialized during the second run.
1768 if (mStatus == STATUS_UNINITIALIZED) {
1769 return OK;
1770 }
1771
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001772 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001773
1774 // Stop session and stream counter
1775 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001776 }
1777
Ravneet98ffa752022-03-02 07:22:46 +00001778 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal72c96652022-06-29 01:34:01 +00001779 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneet98ffa752022-03-02 07:22:46 +00001780 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1781 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1782
1783 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001784}
1785
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001786status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001787 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1788}
1789
1790status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001791 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001792 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001793 Mutex::Autolock il(mInterfaceLock);
1794 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001795
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001796 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1797 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001798 CLOGE("Stream %d does not exist", streamId);
1799 return BAD_VALUE;
1800 }
1801
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001802 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001803 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001804 return BAD_VALUE;
1805 }
1806
1807 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001808 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001809 return BAD_VALUE;
1810 }
1811
Ruben Brunkc78ac262015-08-13 17:58:46 -07001812 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001813}
1814
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001815status_t Camera3Device::tearDown(int streamId) {
1816 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001817 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001818 Mutex::Autolock il(mInterfaceLock);
1819 Mutex::Autolock l(mLock);
1820
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001821 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1822 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001823 CLOGE("Stream %d does not exist", streamId);
1824 return BAD_VALUE;
1825 }
1826
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001827 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1828 CLOGE("Stream %d is a target of a in-progress request", streamId);
1829 return BAD_VALUE;
1830 }
1831
1832 return stream->tearDown();
1833}
1834
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001835status_t Camera3Device::addBufferListenerForStream(int streamId,
1836 wp<Camera3StreamBufferListener> listener) {
1837 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001838 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001839 Mutex::Autolock il(mInterfaceLock);
1840 Mutex::Autolock l(mLock);
1841
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001842 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1843 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001844 CLOGE("Stream %d does not exist", streamId);
1845 return BAD_VALUE;
1846 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001847 stream->addBufferListener(listener);
1848
1849 return OK;
1850}
1851
Austin Borger4a870a32022-02-25 01:48:41 +00001852float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1853 camera_metadata_entry minDurations =
1854 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1855 for (size_t i = 0; i < minDurations.count; i += 4) {
1856 if (minDurations.data.i64[i] == stream->getFormat()
1857 && minDurations.data.i64[i+1] == stream->getWidth()
1858 && minDurations.data.i64[i+2] == stream->getHeight()) {
1859 int64_t minFrameDuration = minDurations.data.i64[i+3];
1860 return 1e9f / minFrameDuration;
1861 }
1862 }
1863 return 0.0f;
1864}
1865
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001866/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 * Methods called by subclasses
1868 */
1869
1870void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001871 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001872 std::vector<int> streamIds;
1873 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001874 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001875
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876 {
1877 // Need mLock to safely update state and synchronize to current
1878 // state of methods in flight.
1879 Mutex::Autolock l(mLock);
1880 // We can get various system-idle notices from the status tracker
1881 // while starting up. Only care about them if we've actually sent
1882 // in some requests recently.
1883 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1884 return;
1885 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001886 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1887 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001888 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001889
1890 // Skip notifying listener if we're doing some user-transparent
1891 // state changes
1892 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001893
Austin Borger4a870a32022-02-25 01:48:41 +00001894 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1895 auto stream = mOutputStreams[i];
1896 if (stream.get() == nullptr) continue;
1897
1898 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1899 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1900
1901 // Populate stream statistics in case of Idle
1902 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001903 streamIds.push_back(stream->getId());
1904 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1905 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001906 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001907 if (camera3Stream != nullptr) {
1908 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001909 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001910 }
1911 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001912 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001913 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001914 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001915 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001916 }
1917 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001919
1920 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001921 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001922 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001923 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001924 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001925 status_t res = OK;
1926 if (listener != nullptr) {
1927 if (idle) {
1928 // Get session stats from the builder, and notify the listener.
1929 int64_t requestCount, resultErrorCount;
1930 bool deviceError;
1931 std::map<int, StreamStats> streamStatsMap;
1932 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1933 &deviceError, &streamStatsMap);
1934 for (size_t i = 0; i < streamIds.size(); i++) {
1935 int streamId = streamIds[i];
1936 auto stats = streamStatsMap.find(streamId);
1937 if (stats != streamStatsMap.end()) {
1938 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1939 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1940 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1941 streamStats[i].mHistogramType =
1942 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1943 streamStats[i].mHistogramBins.assign(
1944 stats->second.mCaptureLatencyBins.begin(),
1945 stats->second.mCaptureLatencyBins.end());
1946 streamStats[i].mHistogramCounts.assign(
1947 stats->second.mCaptureLatencyHistogram.begin(),
1948 stats->second.mCaptureLatencyHistogram.end());
1949 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001950 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001951 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1952 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001953 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001954 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001955 }
1956 if (res != OK) {
1957 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1958 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 }
1960}
1961
Shuzhen Wang758c2152017-01-10 18:26:18 -08001962status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001963 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001964 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001965 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1966 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001967
1968 if (surfaceIds == nullptr) {
1969 return BAD_VALUE;
1970 }
1971
Zhijun He5d677d12016-05-29 16:52:39 -07001972 Mutex::Autolock il(mInterfaceLock);
1973 Mutex::Autolock l(mLock);
1974
Shuzhen Wang758c2152017-01-10 18:26:18 -08001975 if (consumers.size() == 0) {
1976 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001977 return BAD_VALUE;
1978 }
1979
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001980 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1981 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001982 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001983 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001984 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001985
1986 // isConsumerConfigurationDeferred will be off after setConsumers
1987 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001988 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001989 if (res != OK) {
1990 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1991 return res;
1992 }
1993
Emilian Peev40ead602017-09-26 15:46:36 +01001994 for (auto &consumer : consumers) {
1995 int id = stream->getSurfaceId(consumer);
1996 if (id < 0) {
1997 CLOGE("Invalid surface id!");
1998 return BAD_VALUE;
1999 }
2000 surfaceIds->push_back(id);
2001 }
2002
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002003 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002004 if (!stream->isConfiguring()) {
2005 CLOGE("Stream %d was already fully configured.", streamId);
2006 return INVALID_OPERATION;
2007 }
Zhijun He5d677d12016-05-29 16:52:39 -07002008
Shuzhen Wang0129d522016-10-30 22:43:41 -07002009 res = stream->finishConfiguration();
2010 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002011 // If finishConfiguration fails due to abandoned surface, do not set
2012 // device to error state.
2013 bool isSurfaceAbandoned =
2014 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2015 if (!isSurfaceAbandoned) {
2016 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2017 stream->getId(), strerror(-res), res);
2018 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002019 return res;
2020 }
Zhijun He5d677d12016-05-29 16:52:39 -07002021 }
2022
2023 return OK;
2024}
2025
Emilian Peev40ead602017-09-26 15:46:36 +01002026status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2027 const std::vector<OutputStreamInfo> &outputInfo,
2028 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2029 Mutex::Autolock il(mInterfaceLock);
2030 Mutex::Autolock l(mLock);
2031
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002032 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2033 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002034 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002035 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002036 }
2037
2038 for (const auto &it : removedSurfaceIds) {
2039 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2040 CLOGE("Shared surface still part of a pending request!");
2041 return -EBUSY;
2042 }
2043 }
2044
Emilian Peev40ead602017-09-26 15:46:36 +01002045 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2046 if (res != OK) {
2047 CLOGE("Stream %d failed to update stream (error %d %s) ",
2048 streamId, res, strerror(-res));
2049 if (res == UNKNOWN_ERROR) {
2050 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2051 __FUNCTION__);
2052 }
2053 return res;
2054 }
2055
2056 return res;
2057}
2058
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002059status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2060 Mutex::Autolock il(mInterfaceLock);
2061 Mutex::Autolock l(mLock);
2062
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002063 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2064 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002065 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2066 return BAD_VALUE;
2067 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002068
2069 if (dropping) {
2070 mSessionStatsBuilder.stopCounter(streamId);
2071 } else {
2072 mSessionStatsBuilder.startCounter(streamId);
2073 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002074 return stream->dropBuffers(dropping);
2075}
2076
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002077/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078 * Camera3Device private methods
2079 */
2080
2081sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002082 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002085 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002086 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087
2088 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002089 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002090 if (inputStreams.count > 0) {
2091 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002092 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002093 CLOGE("Request references unknown input stream %d",
2094 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002095 return NULL;
2096 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002097
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002099 SET_ERR_L("%s: input stream %d is not configured!",
2100 __FUNCTION__, mInputStream->getId());
2101 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002103 // Check if stream prepare is blocking requests.
2104 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002105 CLOGE("Request references an input stream that's being prepared!");
2106 return NULL;
2107 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002108
2109 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002110 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002111 }
2112
2113 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002114 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002116 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 return NULL;
2118 }
2119
2120 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002121 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2122 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002123 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002124 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 return NULL;
2126 }
Zhijun He5d677d12016-05-29 16:52:39 -07002127 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002128 auto iter = surfaceMap.find(streams.data.i32[i]);
2129 if (iter != surfaceMap.end()) {
2130 const std::vector<size_t>& surfaces = iter->second;
2131 for (const auto& surface : surfaces) {
2132 if (stream->isConsumerConfigurationDeferred(surface)) {
2133 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2134 "due to deferred consumer", stream->getId(), surface);
2135 return NULL;
2136 }
2137 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002138 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002139 }
2140
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002141 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002142 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2143 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002145 // Check if stream prepare is blocking requests.
2146 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002147 CLOGE("Request references an output stream that's being prepared!");
2148 return NULL;
2149 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150
2151 newRequest->mOutputStreams.push(stream);
2152 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002153 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002154 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002156 auto rotateAndCropEntry =
2157 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2158 if (rotateAndCropEntry.count > 0 &&
2159 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2160 newRequest->mRotateAndCropAuto = true;
2161 } else {
2162 newRequest->mRotateAndCropAuto = false;
2163 }
2164
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002165 auto zoomRatioEntry =
2166 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2167 if (zoomRatioEntry.count > 0 &&
2168 zoomRatioEntry.data.f[0] == 1.0f) {
2169 newRequest->mZoomRatioIs1x = true;
2170 } else {
2171 newRequest->mZoomRatioIs1x = false;
2172 }
2173
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002174 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002175 for (auto& settings : newRequest->mSettingsList) {
2176 auto testPatternModeEntry =
2177 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2178 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2179 testPatternModeEntry.data.i32[0] :
2180 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002181
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002182 auto testPatternDataEntry =
2183 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2184 if (testPatternDataEntry.count >= 4) {
2185 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2186 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2187 } else {
2188 settings.mOriginalTestPatternData[0] = 0;
2189 settings.mOriginalTestPatternData[1] = 0;
2190 settings.mOriginalTestPatternData[2] = 0;
2191 settings.mOriginalTestPatternData[3] = 0;
2192 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002193 }
2194 }
2195
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002196 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002197}
2198
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002199void Camera3Device::cancelStreamsConfigurationLocked() {
2200 int res = OK;
2201 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2202 res = mInputStream->cancelConfiguration();
2203 if (res != OK) {
2204 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2205 mInputStream->getId(), strerror(-res), res);
2206 }
2207 }
2208
2209 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002210 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002211 if (outputStream->isConfiguring()) {
2212 res = outputStream->cancelConfiguration();
2213 if (res != OK) {
2214 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2215 outputStream->getId(), strerror(-res), res);
2216 }
2217 }
2218 }
2219
2220 // Return state to that at start of call, so that future configures
2221 // properly clean things up
2222 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2223 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002224
2225 res = mPreparerThread->resume();
2226 if (res != OK) {
2227 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2228 }
2229}
2230
Emilian Peev0d0191e2020-04-21 17:01:18 -07002231bool Camera3Device::checkAbandonedStreamsLocked() {
2232 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2233 return true;
2234 }
2235
2236 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2237 auto stream = mOutputStreams[i];
2238 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2239 return true;
2240 }
2241 }
2242
2243 return false;
2244}
2245
Emilian Peev3bead5f2020-05-28 17:29:08 -07002246bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002247 ATRACE_CALL();
2248 bool ret = false;
2249
Shuzhen Wang316781a2020-08-18 18:11:01 -07002250 nsecs_t startTime = systemTime();
2251
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002252 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002253 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2254
2255 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002256 if (checkAbandonedStreamsLocked()) {
2257 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2258 __FUNCTION__);
2259 return true;
2260 }
2261
Emilian Peev3bead5f2020-05-28 17:29:08 -07002262 status_t rc = NO_ERROR;
2263 bool markClientActive = false;
2264 if (mStatus == STATUS_ACTIVE) {
2265 markClientActive = true;
2266 mPauseStateNotify = true;
2267 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2268
2269 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2270 }
2271
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002272 if (rc == NO_ERROR) {
2273 mNeedConfig = true;
2274 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2275 if (rc == NO_ERROR) {
2276 ret = true;
2277 mPauseStateNotify = false;
2278 //Moving to active state while holding 'mLock' is important.
2279 //There could be pending calls to 'create-/deleteStream' which
2280 //will trigger another stream configuration while the already
2281 //present streams end up with outstanding buffers that will
2282 //not get drained.
2283 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002284 } else if (rc == DEAD_OBJECT) {
2285 // DEAD_OBJECT can be returned if either the consumer surface is
2286 // abandoned, or the HAL has died.
2287 // - If the HAL has died, configureStreamsLocked call will set
2288 // device to error state,
2289 // - If surface is abandoned, we should not set device to error
2290 // state.
2291 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002292 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002293 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002294 }
2295 } else {
2296 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2297 }
2298
Shuzhen Wang316781a2020-08-18 18:11:01 -07002299 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2300 ns2ms(systemTime() - startTime));
2301
Emilian Peev3bead5f2020-05-28 17:29:08 -07002302 if (markClientActive) {
2303 mStatusTracker->markComponentActive(clientStatusId);
2304 }
2305
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002306 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002307}
2308
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002309status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002310 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311 ATRACE_CALL();
2312 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002313
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002314 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002315 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 return INVALID_OPERATION;
2317 }
2318
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002319 if (operatingMode < 0) {
2320 CLOGE("Invalid operating mode: %d", operatingMode);
2321 return BAD_VALUE;
2322 }
2323
2324 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002325 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002326
2327 if (mOperatingMode != operatingMode) {
2328 mNeedConfig = true;
2329 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2330 mOperatingMode = operatingMode;
2331 }
2332
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002333 // Reset min expected duration when session is reconfigured.
2334 mMinExpectedDuration = 0;
2335
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002336 // In case called from configureStreams, abort queued input buffers not belonging to
2337 // any pending requests.
2338 if (mInputStream != NULL && notifyRequestThread) {
2339 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002340 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002341 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002342 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002343 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002344 if (res != OK) {
2345 // Exhausted acquiring all input buffers.
2346 break;
2347 }
2348
Emilian Peevf4816702020-04-03 15:44:51 -07002349 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002350 res = mInputStream->returnInputBuffer(inputBuffer);
2351 if (res != OK) {
2352 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2353 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2354 }
2355 }
2356 }
2357
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002358 if (!mNeedConfig) {
2359 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2360 return OK;
2361 }
2362
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002363 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002364 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002365 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2366 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002367 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002368 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002369 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002370 }
2371
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08002372 // Override stream use case based on "adb shell command"
2373 overrideStreamUseCaseLocked();
2374
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002376 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002378 mPreparerThread->pause();
2379
Emilian Peevf4816702020-04-03 15:44:51 -07002380 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002381 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002383 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384
Emilian Peevf4816702020-04-03 15:44:51 -07002385 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002387 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002388
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389
2390 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002391 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 inputStream = mInputStream->startConfiguration();
2393 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002394 CLOGE("Can't start input stream configuration");
2395 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002396 return INVALID_OPERATION;
2397 }
2398 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002399
2400 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 }
2402
Shuzhen Wang99080502021-03-07 21:08:20 -08002403 mGroupIdPhysicalCameraMap.clear();
Emilian Peevb9f83812023-03-17 17:13:07 -07002404 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002405 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002406
2407 // Don't configure bidi streams twice, nor add them twice to the list
2408 if (mOutputStreams[i].get() ==
2409 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2410
2411 config.num_streams--;
2412 continue;
2413 }
2414
Emilian Peevf4816702020-04-03 15:44:51 -07002415 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002416 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002418 CLOGE("Can't start output stream configuration");
2419 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 return INVALID_OPERATION;
2421 }
2422 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002423
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002424 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002425 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2426 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002427 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2428 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002429 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2430 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002431 } else if (outputStream->data_space ==
2432 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2433 bufferSizes[k] = outputStream->width * outputStream->height;
2434 } else {
2435 ALOGW("%s: Blob dataSpace %d not supported",
2436 __FUNCTION__, outputStream->data_space);
2437 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002438 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002439
2440 if (mOutputStreams[i]->isMultiResolution()) {
2441 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2442 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2443 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2444 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002445
2446 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevb9f83812023-03-17 17:13:07 -07002447 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002448 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002449 }
2450
2451 config.streams = streams.editArray();
2452
2453 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002454 // max_buffers, usage, and priv fields, as well as data_space and format
2455 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002456
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002457 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002458 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002459 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002460
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002461 if (res == BAD_VALUE) {
2462 // HAL rejected this set of streams as unsupported, clean up config
2463 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002464 CLOGE("Set of requested inputs/outputs not supported by HAL");
2465 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002466 return BAD_VALUE;
2467 } else if (res != OK) {
2468 // Some other kind of error from configure_streams - this is not
2469 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002470 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2471 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002472 return res;
2473 }
2474
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002475 // Finish all stream configuration immediately.
2476 // TODO: Try to relax this later back to lazy completion, which should be
2477 // faster
2478
Igor Murashkin073f8572013-05-02 14:59:28 -07002479 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002480 bool streamReConfigured = false;
2481 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002482 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002483 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002484 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002485 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002486 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2487 return DEAD_OBJECT;
2488 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002489 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002490 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002491 if (streamReConfigured) {
2492 mInterface->onStreamReConfigured(mInputStream->getId());
2493 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002494 }
2495
2496 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002497 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002498 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002499 bool streamReConfigured = false;
2500 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002501 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002503 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002505 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2506 return DEAD_OBJECT;
2507 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002508 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002509 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002510 if (streamReConfigured) {
2511 mInterface->onStreamReConfigured(outputStream->getId());
2512 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002513 }
2514 }
2515
Emilian Peevb9f83812023-03-17 17:13:07 -07002516 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002518 // Request thread needs to know to avoid using repeat-last-settings protocol
2519 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002520 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002521 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2522 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002523 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524
Zhijun He90f7c372016-08-16 16:19:43 -07002525 char value[PROPERTY_VALUE_MAX];
2526 property_get("camera.fifo.disable", value, "0");
2527 int32_t disableFifo = atoi(value);
2528 if (disableFifo != 1) {
2529 // Boost priority of request thread to SCHED_FIFO.
2530 pid_t requestThreadTid = mRequestThread->getTid();
2531 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002532 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002533 if (res != OK) {
2534 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2535 strerror(-res), res);
2536 } else {
2537 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2538 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002539 }
2540
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002541 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002542 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2543 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2544 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2545 sessionParams.unlock(newSessionParams);
2546 mSessionParams.unlock(currentSessionParams);
2547 if (updateSessionParams) {
2548 mSessionParams = sessionParams;
2549 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002550
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002551 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002553 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002554 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002556 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002557
Zhijun He0a210512014-07-24 13:45:15 -07002558 // tear down the deleted streams after configure streams.
2559 mDeletedStreams.clear();
2560
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002561 auto rc = mPreparerThread->resume();
2562 if (rc != OK) {
2563 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2564 return rc;
2565 }
2566
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002567 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002568 mRequestBufferSM.onStreamsConfigured();
2569 }
2570
Cliff Wu3b268182021-07-06 15:44:43 +08002571 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002572 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002573 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002574 // configure the injection streams.
2575 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002576 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002577 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2578 res = mInjectionMethods->injectCamera(config, bufferSizes);
2579 if (res != OK) {
2580 ALOGE("Can't finish inject camera process!");
2581 return res;
2582 }
Cliff Wu3b268182021-07-06 15:44:43 +08002583 } else {
2584 // First run configureStreamsLocked() and then call injectCamera() case:
2585 // If the stream configuration has been completed and camera deive is active, but the
2586 // injection camera has not been injected yet, we need to store the stream configuration of
2587 // the internal camera (because the stream configuration of the injection camera is based
2588 // on the internal camera). When injecting occurs later, this configuration can be used by
2589 // the injection camera.
2590 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2591 " injection camera has not been injected yet.", __FUNCTION__);
2592 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002593 }
2594
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002596}
2597
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002598status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002599 ATRACE_CALL();
2600 status_t res;
2601
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002602 if (mFakeStreamId != NO_STREAM) {
2603 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002604 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002605 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002606 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002607 return INVALID_OPERATION;
2608 }
2609
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002610 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002611
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002612 sp<Camera3OutputStreamInterface> fakeStream =
2613 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002614
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002615 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618 return res;
2619 }
2620
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002621 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002622 mNextStreamId++;
2623
2624 return OK;
2625}
2626
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002627status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002628 ATRACE_CALL();
2629 status_t res;
2630
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002631 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002632 if (mOutputStreams.size() == 1) return OK;
2633
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002634 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002635
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002636 // Ok, have a fake stream and there's at least one other output stream,
2637 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002638
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002639 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002640 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642 return INVALID_OPERATION;
2643 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002644 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002645
2646 // Free up the stream endpoint so that it can be used by some other stream
2647 res = deletedStream->disconnect();
2648 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650 // fall through since we want to still list the stream as deleted.
2651 }
2652 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002653 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002654
2655 return res;
2656}
2657
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002658void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002659 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002660 Mutex::Autolock l(mLock);
2661 va_list args;
2662 va_start(args, fmt);
2663
2664 setErrorStateLockedV(fmt, args);
2665
2666 va_end(args);
2667}
2668
2669void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002670 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002671 Mutex::Autolock l(mLock);
2672 setErrorStateLockedV(fmt, args);
2673}
2674
2675void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2676 va_list args;
2677 va_start(args, fmt);
2678
2679 setErrorStateLockedV(fmt, args);
2680
2681 va_end(args);
2682}
2683
2684void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002685 // Print out all error messages to log
2686 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002687 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002688
2689 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002690 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002691
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002692 mErrorCause = errorCause;
2693
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002694 if (mRequestThread != nullptr) {
2695 mRequestThread->setPaused(true);
2696 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002697 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002698
2699 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002700 sp<NotificationListener> listener = mListener.promote();
2701 if (listener != NULL) {
2702 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002703 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002704 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002705 }
2706
2707 // Save stack trace. View by dumping it later.
2708 CameraTraces::saveTrace();
2709 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002710}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711
2712/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002713 * In-flight request management
2714 */
2715
Jianing Weicb0652e2014-03-12 18:29:36 -07002716status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002717 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002718 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002719 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002720 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2721 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002722 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002724 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002725
2726 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002727 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002728 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002729 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2730 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002731 if (res < 0) return res;
2732
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002733 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002734 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2735 // avoid a deadlock during reprocess requests.
2736 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002737 if (mStatusTracker != nullptr) {
2738 mStatusTracker->markComponentActive(mInFlightStatusId);
2739 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002740 }
2741
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002742 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002743 return OK;
2744}
2745
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002746void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002747 // Indicate idle inFlightMap to the status tracker
2748 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002749 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002750 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2751 // avoid a deadlock during reprocess requests.
2752 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002753 if (mStatusTracker != nullptr) {
2754 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2755 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002756 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002757 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002758}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002759
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002760void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002761 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002762 // something has likely gone wrong. This might still be legit only if application send in
2763 // a long burst of long exposure requests.
2764 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2765 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2766 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2767 mInFlightMap.size(), mExpectedInflightDuration);
2768 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2769 kInFlightWarnLimitHighSpeed) {
2770 CLOGW("In-flight list too large for high speed configuration: %zu,"
2771 "total inflight duration %" PRIu64,
2772 mInFlightMap.size(), mExpectedInflightDuration);
2773 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002774 }
2775}
2776
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002777void Camera3Device::onInflightMapFlushedLocked() {
2778 mExpectedInflightDuration = 0;
2779}
2780
2781void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002782 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002783 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2784 mInFlightMap.removeItemsAt(idx, 1);
2785
2786 onInflightEntryRemovedLocked(duration);
2787}
2788
2789
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002790void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002791 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002792 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002793 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002794 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002795 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002796 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002797
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002798 FlushInflightReqStates states {
2799 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002800 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002801
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002802 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002803}
2804
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002805CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002806 ALOGV("%s", __FUNCTION__);
2807
Igor Murashkin1e479c02013-09-06 16:55:14 -07002808 CameraMetadata retVal;
2809
2810 if (mRequestThread != NULL) {
2811 retVal = mRequestThread->getLatestRequest();
2812 }
2813
Igor Murashkin1e479c02013-09-06 16:55:14 -07002814 return retVal;
2815}
2816
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002817void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002818 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002819 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002820 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2821 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002822
2823 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002824 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002825}
2826
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002827void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002828 std::vector<native_handle_t*> *handles, bool closeFd) {
2829 if (handles == nullptr) {
2830 return;
2831 }
2832 if (closeFd) {
2833 for (auto& handle : *handles) {
2834 native_handle_close(handle);
2835 }
2836 }
2837 for (auto& handle : *handles) {
2838 native_handle_delete(handle);
2839 }
2840 handles->clear();
2841 return;
2842}
2843
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002844/**
2845 * HalInterface inner class methods
2846 */
2847
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002848void Camera3Device::HalInterface::getInflightBufferKeys(
2849 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002850 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002851 return;
2852}
2853
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002854void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2855 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002856 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002857 return;
2858}
2859
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002860bool Camera3Device::HalInterface::verifyBufferIds(
2861 int32_t streamId, std::vector<uint64_t>& bufIds) {
2862 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002863}
2864
2865status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002866 int32_t frameNumber, int32_t streamId,
2867 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002868 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002869}
2870
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002871status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002872 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002873 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002874}
2875
2876// Find and pop a buffer_handle_t based on bufferId
2877status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002878 uint64_t bufferId,
2879 /*out*/ buffer_handle_t** buffer,
2880 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002881 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002882}
2883
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002884std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2885 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002886 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002887}
2888
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002889uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2890 const native_handle_t* handle) {
2891 return mBufferRecords.removeOneBufferCache(streamId, handle);
2892}
2893
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002894void Camera3Device::HalInterface::onBufferFreed(
2895 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002896 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2897 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2898 if (bufferId != BUFFER_ID_NO_BUFFER) {
2899 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002900 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002901}
2902
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002903void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002904 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2905 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2906 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002907 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2908 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002909}
2910
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002911/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002912 * RequestThread inner class methods
2913 */
2914
2915Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002916 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002917 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002918 bool useHalBufManager,
Austin Borger3560b7e2022-10-27 12:20:29 -07002919 bool supportCameraMute,
2920 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002921 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002922 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002923 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002924 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002925 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002926 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002927 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002928 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002929 mReconfigured(false),
2930 mDoPause(false),
2931 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002932 mNotifyPipelineDrain(false),
Kwangkyu Park453a66a2023-09-04 18:53:06 +09002933 mPrevTriggers(0),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002934 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002935 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002936 mCurrentAfTriggerId(0),
2937 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002938 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002939 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002940 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002941 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002942 mRepeatingLastFrameNumber(
2943 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002944 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002945 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002946 mRequestLatency(kRequestLatencyBinSize),
2947 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002948 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002949 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002950 mSupportCameraMute(supportCameraMute),
2951 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002952 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002953}
2954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002955Camera3Device::RequestThread::~RequestThread() {}
2956
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002957void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002958 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002959 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002960 Mutex::Autolock l(mRequestLock);
2961 mListener = listener;
2962}
2963
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002964void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002965 const CameraMetadata& sessionParams,
2966 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002967 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002968 Mutex::Autolock l(mRequestLock);
2969 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002970 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002971 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002972 // Prepare video stream for high speed recording.
2973 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002974 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002975}
2976
Jianing Wei90e59c92014-03-12 18:29:36 -07002977status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002978 List<sp<CaptureRequest> > &requests,
2979 /*out*/
2980 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002981 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002982 Mutex::Autolock l(mRequestLock);
2983 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2984 ++it) {
2985 mRequestQueue.push_back(*it);
2986 }
2987
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002988 if (lastFrameNumber != NULL) {
2989 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2990 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2991 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2992 *lastFrameNumber);
2993 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002994
Jianing Wei90e59c92014-03-12 18:29:36 -07002995 unpauseForNewRequests();
2996
2997 return OK;
2998}
2999
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003000
3001status_t Camera3Device::RequestThread::queueTrigger(
3002 RequestTrigger trigger[],
3003 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003004 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003005 Mutex::Autolock l(mTriggerMutex);
3006 status_t ret;
3007
3008 for (size_t i = 0; i < count; ++i) {
3009 ret = queueTriggerLocked(trigger[i]);
3010
3011 if (ret != OK) {
3012 return ret;
3013 }
3014 }
3015
3016 return OK;
3017}
3018
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003019const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3020 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003021 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003022 if (d != nullptr) return d->mId;
3023 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003024}
3025
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003026status_t Camera3Device::RequestThread::queueTriggerLocked(
3027 RequestTrigger trigger) {
3028
3029 uint32_t tag = trigger.metadataTag;
3030 ssize_t index = mTriggerMap.indexOfKey(tag);
3031
3032 switch (trigger.getTagType()) {
3033 case TYPE_BYTE:
3034 // fall-through
3035 case TYPE_INT32:
3036 break;
3037 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003038 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3039 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003040 return INVALID_OPERATION;
3041 }
3042
3043 /**
3044 * Collect only the latest trigger, since we only have 1 field
3045 * in the request settings per trigger tag, and can't send more than 1
3046 * trigger per request.
3047 */
3048 if (index != NAME_NOT_FOUND) {
3049 mTriggerMap.editValueAt(index) = trigger;
3050 } else {
3051 mTriggerMap.add(tag, trigger);
3052 }
3053
3054 return OK;
3055}
3056
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003057status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003058 const RequestList &requests,
3059 /*out*/
3060 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003061 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003062 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003063 if (lastFrameNumber != NULL) {
3064 *lastFrameNumber = mRepeatingLastFrameNumber;
3065 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003066 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003067 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003068 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3069 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003070
3071 unpauseForNewRequests();
3072
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003073 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003074 return OK;
3075}
3076
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003077bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003078 if (mRepeatingRequests.empty()) {
3079 return false;
3080 }
3081 int32_t requestId = requestIn->mResultExtras.requestId;
3082 const RequestList &repeatRequests = mRepeatingRequests;
3083 // All repeating requests are guaranteed to have same id so only check first quest
3084 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3085 return (firstRequest->mResultExtras.requestId == requestId);
3086}
3087
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003088status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003089 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003090 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003091 return clearRepeatingRequestsLocked(lastFrameNumber);
3092
3093}
3094
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003095status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3096 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003097 std::vector<int32_t> streamIds;
3098 for (const auto& request : mRepeatingRequests) {
3099 for (const auto& stream : request->mOutputStreams) {
3100 streamIds.push_back(stream->getId());
3101 }
3102 }
3103
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003104 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003105 if (lastFrameNumber != NULL) {
3106 *lastFrameNumber = mRepeatingLastFrameNumber;
3107 }
Emilian Peev2295df72021-11-12 18:14:10 -08003108
3109 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003111 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003112 return OK;
3113}
3114
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003115status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003116 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003117 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003118 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003119 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003120
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003121 // Send errors for all requests pending in the request queue, including
3122 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003123 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003124 if (listener != NULL) {
3125 for (RequestList::iterator it = mRequestQueue.begin();
3126 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003127 // Abort the input buffers for reprocess requests.
3128 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003129 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003130 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003131 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003132 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003133 if (res != OK) {
3134 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3135 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3136 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003137 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003138 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3139 if (res != OK) {
3140 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3141 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3142 }
3143 }
3144 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003145 // Set the frame number this request would have had, if it
3146 // had been submitted; this frame number will not be reused.
3147 // The requestId and burstId fields were set when the request was
3148 // submitted originally (in convertMetadataListToRequestListLocked)
3149 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003150 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003151 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003152 }
3153 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003154 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003155
3156 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003157 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003158 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003159 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003160 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003161 return OK;
3162}
3163
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003164status_t Camera3Device::RequestThread::flush() {
3165 ATRACE_CALL();
3166 Mutex::Autolock l(mFlushLock);
3167
Emilian Peev08dd2452017-04-06 16:55:14 +01003168 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003169}
3170
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003171void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003172 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003173 Mutex::Autolock l(mPauseLock);
3174 mDoPause = paused;
3175 mDoPauseSignal.signal();
3176}
3177
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003178status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3179 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003180 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003181 Mutex::Autolock l(mLatestRequestMutex);
3182 status_t res;
3183 while (mLatestRequestId != requestId) {
3184 nsecs_t startTime = systemTime();
3185
3186 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3187 if (res != OK) return res;
3188
3189 timeout -= (systemTime() - startTime);
3190 }
3191
3192 return OK;
3193}
3194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003195void Camera3Device::RequestThread::requestExit() {
3196 // Call parent to set up shutdown
3197 Thread::requestExit();
3198 // The exit from any possible waits
3199 mDoPauseSignal.signal();
3200 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003201
3202 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3203 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003204}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003205
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003206void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003207 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003208 bool surfaceAbandoned = false;
3209 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003210 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003211 {
3212 Mutex::Autolock l(mRequestLock);
3213 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3214 // repeating requests.
3215 for (const auto& request : mRepeatingRequests) {
3216 for (const auto& s : request->mOutputStreams) {
3217 if (s->isAbandoned()) {
3218 surfaceAbandoned = true;
3219 clearRepeatingRequestsLocked(&lastFrameNumber);
3220 break;
3221 }
3222 }
3223 if (surfaceAbandoned) {
3224 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003225 }
3226 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003227 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003228 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003229
3230 if (listener != NULL && surfaceAbandoned) {
3231 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003232 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003233}
3234
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003235bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003236 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003237 status_t res;
3238 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003239 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003240 uint32_t numRequestProcessed = 0;
3241 for (size_t i = 0; i < batchSize; i++) {
3242 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003243 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003244 }
3245
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003246 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3247
3248 bool triggerRemoveFailed = false;
3249 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3250 for (size_t i = 0; i < numRequestProcessed; i++) {
3251 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3252 nextRequest.submitted = true;
3253
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003254 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003255
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003256 if (!triggerRemoveFailed) {
3257 // Remove any previously queued triggers (after unlock)
3258 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3259 if (removeTriggerRes != OK) {
3260 triggerRemoveFailed = true;
3261 triggerFailedRequest = nextRequest;
3262 }
3263 }
3264 }
3265
3266 if (triggerRemoveFailed) {
3267 SET_ERR("RequestThread: Unable to remove triggers "
3268 "(capture request %d, HAL device: %s (%d)",
3269 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3270 cleanUpFailedRequests(/*sendRequestError*/ false);
3271 return false;
3272 }
3273
3274 if (res != OK) {
3275 // Should only get a failure here for malformed requests or device-level
3276 // errors, so consider all errors fatal. Bad metadata failures should
3277 // come through notify.
3278 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3279 mNextRequests[numRequestProcessed].halRequest.frame_number,
3280 strerror(-res), res);
3281 cleanUpFailedRequests(/*sendRequestError*/ false);
3282 return false;
3283 }
3284 return true;
3285}
3286
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003287Camera3Device::RequestThread::ExpectedDurationInfo
3288 Camera3Device::RequestThread::calculateExpectedDurationRange(
3289 const camera_metadata_t *request) {
3290 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003291 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003292 InFlightRequest::kDefaultMaxExpectedDuration,
3293 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003294 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3295 find_camera_metadata_ro_entry(request,
3296 ANDROID_CONTROL_AE_MODE,
3297 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003298 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003299
3300 switch (e.data.u8[0]) {
3301 case ANDROID_CONTROL_AE_MODE_OFF:
3302 find_camera_metadata_ro_entry(request,
3303 ANDROID_SENSOR_EXPOSURE_TIME,
3304 &e);
3305 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003306 expectedDurationInfo.minDuration = e.data.i64[0];
3307 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003308 }
3309 find_camera_metadata_ro_entry(request,
3310 ANDROID_SENSOR_FRAME_DURATION,
3311 &e);
3312 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003313 expectedDurationInfo.minDuration =
3314 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3315 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003316 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003317 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003318 break;
3319 default:
3320 find_camera_metadata_ro_entry(request,
3321 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3322 &e);
3323 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003324 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3325 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003326 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003327 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003328 break;
3329 }
3330
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003331 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003332}
3333
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003334bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3335 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3336 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3337 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3338 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3339 return true;
3340 }
3341
3342 return false;
3343}
3344
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003345void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3346 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003347 camera_capture_request_t& halRequest = nextRequest.halRequest;
3348 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003349 Mutex::Autolock al(mLatestRequestMutex);
3350
Shuzhen Wang83bff122020-11-20 15:51:39 -08003351 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003352 mLatestRequest.acquire(cloned);
3353
3354 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003355 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3356 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3357 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003358 CameraMetadata(cloned));
3359 }
3360
3361 sp<Camera3Device> parent = mParent.promote();
3362 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003363 int32_t inputStreamId = -1;
3364 if (halRequest.input_buffer != nullptr) {
3365 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3366 }
3367
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003368 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003369 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003370 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3371 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003372 }
3373 }
3374
Shuzhen Wang83bff122020-11-20 15:51:39 -08003375 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003376 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003377 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003378 }
3379
Shuzhen Wang83bff122020-11-20 15:51:39 -08003380 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003381}
3382
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003383bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3384 ATRACE_CALL();
3385 bool updatesDetected = false;
3386
Emilian Peev4ec17882019-01-24 17:16:58 -08003387 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003388 for (auto tag : mSessionParamKeys) {
3389 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003390 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003391
3392 if (entry.count > 0) {
3393 bool isDifferent = false;
3394 if (lastEntry.count > 0) {
3395 // Have a last value, compare to see if changed
3396 if (lastEntry.type == entry.type &&
3397 lastEntry.count == entry.count) {
3398 // Same type and count, compare values
3399 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3400 size_t entryBytes = bytesPerValue * lastEntry.count;
3401 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3402 if (cmp != 0) {
3403 isDifferent = true;
3404 }
3405 } else {
3406 // Count or type has changed
3407 isDifferent = true;
3408 }
3409 } else {
3410 // No last entry, so always consider to be different
3411 isDifferent = true;
3412 }
3413
3414 if (isDifferent) {
3415 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003416 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3417 updatesDetected = true;
3418 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003419 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003420 }
3421 } else if (lastEntry.count > 0) {
3422 // Value has been removed
3423 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003424 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003425 updatesDetected = true;
3426 }
3427 }
3428
Emilian Peev4ec17882019-01-24 17:16:58 -08003429 bool reconfigureRequired;
3430 if (updatesDetected) {
3431 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3432 updatedParams);
3433 mLatestSessionParams = updatedParams;
3434 } else {
3435 reconfigureRequired = false;
3436 }
3437
3438 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003439}
3440
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003441bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003442 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003443 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003444 // Any function called from threadLoop() must not hold mInterfaceLock since
3445 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3446 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003447
3448 // Handle paused state.
3449 if (waitIfPaused()) {
3450 return true;
3451 }
3452
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003453 // Wait for the next batch of requests.
3454 waitForNextRequestBatch();
3455 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003456 return true;
3457 }
3458
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003459 // Get the latest request ID, if any
3460 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003461 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003462 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003463 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003464 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003465 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003466 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3467 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003468 }
3469
Emilian Peevb9f83812023-03-17 17:13:07 -07003470 for (size_t i = 0; i < mNextRequests.size(); i++) {
3471 auto& nextRequest = mNextRequests.editItemAt(i);
3472 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3473 // Do not override rotate&crop for stream configurations that include
3474 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3475 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3476 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3477 overrideAutoRotateAndCrop(captureRequest);
3478 }
3479
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003480 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3481 // or a single request from streaming or burst. In either case the first element
3482 // should contain the latest camera settings that we need to check for any session
3483 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003484 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003485 res = OK;
3486
3487 //Input stream buffers are already acquired at this point so an input stream
3488 //will not be able to move to idle state unless we force it.
3489 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3490 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3491 if (res != OK) {
3492 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3493 cleanUpFailedRequests(/*sendRequestError*/ false);
3494 return false;
3495 }
3496 }
3497
3498 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003499 sp<Camera3Device> parent = mParent.promote();
3500 if (parent != nullptr) {
3501 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003502 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003503 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003504
3505 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3506 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3507 if (res != OK) {
3508 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3509 cleanUpFailedRequests(/*sendRequestError*/ false);
3510 return false;
3511 }
3512 }
3513 }
3514 }
3515
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003516 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003517 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003518 if (res == TIMED_OUT) {
3519 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003520 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003521 // Check if any stream is abandoned.
3522 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003523 return true;
3524 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003525 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003526 return false;
3527 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003528
Zhijun Hecc27e112013-10-03 16:12:43 -07003529 // Inform waitUntilRequestProcessed thread of a new request ID
3530 {
3531 Mutex::Autolock al(mLatestRequestMutex);
3532
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003533 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003534 mLatestRequestSignal.signal();
3535 }
3536
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003537 // Submit a batch of requests to HAL.
3538 // Use flush lock only when submitting multilple requests in a batch.
3539 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3540 // which may take a long time to finish so synchronizing flush() and
3541 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3542 // For now, only synchronize for high speed recording and we should figure something out for
3543 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003544 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003545
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003546 if (useFlushLock) {
3547 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003548 }
3549
Zhijun Hef0645c12016-08-02 00:58:11 -07003550 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003551 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003552
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003553 sp<Camera3Device> parent = mParent.promote();
3554 if (parent != nullptr) {
3555 parent->mRequestBufferSM.onSubmittingRequest();
3556 }
3557
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003558 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003559 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003560 submitRequestSuccess = sendRequestsBatch();
3561
Shuzhen Wang686f6442017-06-20 16:16:04 -07003562 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3563 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003564
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003565 if (useFlushLock) {
3566 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003567 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003568
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003569 // Unset as current request
3570 {
3571 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003572 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003573 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003574 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003575
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003576 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003577}
3578
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003579status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3580 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3581 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3582 ANDROID_SCALER_CROP_REGION_SET};
3583 if (request == nullptr) {
3584 ALOGE("%s request metadata nullptr", __FUNCTION__);
3585 return BAD_VALUE;
3586 }
3587 status_t res = OK;
3588 for (const auto &key : kFwkOnlyRegionKeys) {
3589 if (request->exists(key)) {
3590 res = request->erase(key);
3591 if (res != OK) {
3592 return res;
3593 }
3594 }
3595 }
3596 return OK;
3597}
3598
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003599status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003600 ATRACE_CALL();
3601
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003602 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003603 for (size_t i = 0; i < mNextRequests.size(); i++) {
3604 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003605 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003606 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3607 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003608
3609 // Prepare a request to HAL
3610 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3611
3612 // Insert any queued triggers (before metadata is locked)
3613 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003614 if (res < 0) {
3615 SET_ERR("RequestThread: Unable to insert triggers "
3616 "(capture request %d, HAL device: %s (%d)",
3617 halRequest->frame_number, strerror(-res), res);
3618 return INVALID_OPERATION;
3619 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003620
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003621 int triggerCount = res;
3622 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3623 mPrevTriggers = triggerCount;
3624
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003625 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003626
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003627 // If the request is the same as last, or we had triggers now or last time or
3628 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003629 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003630 (mPrevRequest != captureRequest || triggersMixedIn ||
Emilian Peevb9f83812023-03-17 17:13:07 -07003631 captureRequest->mRotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003632 // Request settings are all the same within one batch, so only treat the first
3633 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003634 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003635 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003636 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003637 /**
3638 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003639 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003641 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003642 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003643 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003644 "(capture request %d, HAL device: %s (%d)",
3645 halRequest->frame_number, strerror(-res), res);
3646 return INVALID_OPERATION;
3647 }
3648
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003649 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003650 sp<Camera3Device> parent = mParent.promote();
3651 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003652 List<PhysicalCameraSettings>::iterator it;
3653 for (it = captureRequest->mSettingsList.begin();
3654 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003655 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3656 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003657 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3658 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3659 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3660 res);
3661 return INVALID_OPERATION;
3662 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003663 continue;
3664 }
3665
3666 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3667 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3668 updateCaptureRequest(&(it->metadata));
3669 if (res != OK) {
3670 SET_ERR("RequestThread: Unable to correct capture requests "
3671 "for scaler crop region and metering regions for request "
3672 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3673 res);
3674 return INVALID_OPERATION;
3675 }
3676 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003677 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3678 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3679 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3680 res);
3681 return INVALID_OPERATION;
3682 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003683 }
3684 }
3685
3686 // Correct metadata regions for distortion correction if enabled
3687 for (it = captureRequest->mSettingsList.begin();
3688 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003689 if (parent->mDistortionMappers.find(it->cameraId) ==
3690 parent->mDistortionMappers.end()) {
3691 continue;
3692 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003693
3694 if (!captureRequest->mDistortionCorrectionUpdated) {
3695 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3696 &(it->metadata));
3697 if (res != OK) {
3698 SET_ERR("RequestThread: Unable to correct capture requests "
3699 "for lens distortion for request %d: %s (%d)",
3700 halRequest->frame_number, strerror(-res), res);
3701 return INVALID_OPERATION;
3702 }
3703 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003704 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003705 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003706
3707 for (it = captureRequest->mSettingsList.begin();
3708 it != captureRequest->mSettingsList.end(); it++) {
3709 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3710 parent->mZoomRatioMappers.end()) {
3711 continue;
3712 }
3713
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003714 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003715 cameraIdsWithZoom.insert(it->cameraId);
3716 }
3717
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003718 if (!captureRequest->mZoomRatioUpdated) {
3719 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3720 &(it->metadata));
3721 if (res != OK) {
3722 SET_ERR("RequestThread: Unable to correct capture requests "
3723 "for zoom ratio for request %d: %s (%d)",
3724 halRequest->frame_number, strerror(-res), res);
3725 return INVALID_OPERATION;
3726 }
3727 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003728 }
3729 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003730 if (captureRequest->mRotateAndCropAuto &&
3731 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003732 for (it = captureRequest->mSettingsList.begin();
3733 it != captureRequest->mSettingsList.end(); it++) {
3734 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3735 if (mapper != parent->mRotateAndCropMappers.end()) {
3736 res = mapper->second.updateCaptureRequest(&(it->metadata));
3737 if (res != OK) {
3738 SET_ERR("RequestThread: Unable to correct capture requests "
3739 "for rotate-and-crop for request %d: %s (%d)",
3740 halRequest->frame_number, strerror(-res), res);
3741 return INVALID_OPERATION;
3742 }
3743 }
3744 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003745 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003746 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003747 }
3748 }
3749
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003750 /**
3751 * The request should be presorted so accesses in HAL
3752 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3753 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003754 captureRequest->mSettingsList.begin()->metadata.sort();
3755 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003756 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003757 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003758 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3759
3760 IF_ALOGV() {
3761 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3762 find_camera_metadata_ro_entry(
3763 halRequest->settings,
3764 ANDROID_CONTROL_AF_TRIGGER,
3765 &e
3766 );
3767 if (e.count > 0) {
3768 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3769 __FUNCTION__,
3770 halRequest->frame_number,
3771 e.data.u8[0]);
3772 }
3773 }
3774 } else {
3775 // leave request.settings NULL to indicate 'reuse latest given'
3776 ALOGVV("%s: Request settings are REUSED",
3777 __FUNCTION__);
3778 }
3779
Emilian Peevaebbe412018-01-15 13:53:24 +00003780 if (captureRequest->mSettingsList.size() > 1) {
3781 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3782 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003783 if (newRequest) {
3784 halRequest->physcam_settings =
3785 new const camera_metadata* [halRequest->num_physcam_settings];
3786 } else {
3787 halRequest->physcam_settings = nullptr;
3788 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003789 auto it = ++captureRequest->mSettingsList.begin();
3790 size_t i = 0;
3791 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3792 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003793 if (newRequest) {
3794 it->metadata.sort();
3795 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3796 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003797 }
3798 }
3799
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003800 uint32_t totalNumBuffers = 0;
3801
3802 // Fill in buffers
3803 if (captureRequest->mInputStream != NULL) {
3804 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003805
3806 halRequest->input_width = captureRequest->mInputBufferSize.width;
3807 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003808 totalNumBuffers += 1;
3809 } else {
3810 halRequest->input_buffer = NULL;
3811 }
3812
Emilian Peevf4816702020-04-03 15:44:51 -07003813 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003814 captureRequest->mOutputStreams.size());
3815 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003816 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003817
3818 sp<Camera3Device> parent = mParent.promote();
3819 if (parent == NULL) {
3820 // Should not happen, and nowhere to send errors to, so just log it
3821 CLOGE("RequestThread: Parent is gone");
3822 return INVALID_OPERATION;
3823 }
3824 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3825
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003826 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003827 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003828 sp<Camera3OutputStreamInterface> outputStream =
3829 captureRequest->mOutputStreams.editItemAt(j);
3830 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003831
3832 // Prepare video buffers for high speed recording on the first video request.
3833 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3834 // Only try to prepare video stream on the first video request.
3835 mPrepareVideoStream = false;
3836
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003837 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3838 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003839 while (res == NOT_ENOUGH_DATA) {
3840 res = outputStream->prepareNextBuffer();
3841 }
3842 if (res != OK) {
3843 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3844 __FUNCTION__, strerror(-res), res);
3845 outputStream->cancelPrepare();
3846 }
3847 }
3848
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003849 std::vector<size_t> uniqueSurfaceIds;
3850 res = outputStream->getUniqueSurfaceIds(
3851 captureRequest->mOutputSurfaces[streamId],
3852 &uniqueSurfaceIds);
3853 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3854 if (res != OK && res != INVALID_OPERATION) {
3855 ALOGE("%s: failed to query stream %d unique surface IDs",
3856 __FUNCTION__, streamId);
3857 return res;
3858 }
3859 if (res == OK) {
3860 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3861 }
3862
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003863 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003864 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003865 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003866 return TIMED_OUT;
3867 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003868 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003869 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003870 buffer.stream = outputStream->asHalStream();
3871 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003872 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003873 buffer.acquire_fence = -1;
3874 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003875 // Mark the output stream as unpreparable to block clients from calling
3876 // 'prepare' after this request reaches CameraHal and before the respective
3877 // buffers are requested.
3878 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003879 } else {
3880 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3881 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003882 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003883 if (res != OK) {
3884 // Can't get output buffer from gralloc queue - this could be due to
3885 // abandoned queue or other consumer misbehavior, so not a fatal
3886 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003887 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003888 " %s (%d)", strerror(-res), res);
3889
3890 return TIMED_OUT;
3891 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003892 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003893
3894 {
3895 sp<Camera3Device> parent = mParent.promote();
3896 if (parent != nullptr) {
3897 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3898 for (const auto& settings : captureRequest->mSettingsList) {
3899 if ((streamCameraId.isEmpty() &&
3900 parent->getId() == settings.cameraId.c_str()) ||
3901 streamCameraId == settings.cameraId.c_str()) {
3902 outputStream->fireBufferRequestForFrameNumber(
3903 captureRequest->mResultExtras.frameNumber,
3904 settings.metadata);
3905 }
3906 }
3907 }
3908 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003909
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003910 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003911 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3912 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3913 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3914 } else if (!physicalCameraId.isEmpty()) {
3915 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003916 }
3917 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003918 }
3919 totalNumBuffers += halRequest->num_output_buffers;
3920
3921 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003922 // If this request list is for constrained high speed recording (not
3923 // preview), and the current request is not the last one in the batch,
3924 // do not send callback to the app.
3925 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003926 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003927 hasCallback = false;
3928 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003929 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003930 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003931 const camera_metadata_t* settings = halRequest->settings;
3932 bool shouldUnlockSettings = false;
3933 if (settings == nullptr) {
3934 shouldUnlockSettings = true;
3935 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3936 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003937 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3938 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003939 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003940 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3941 isStillCapture = true;
3942 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3943 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003944
Emilian Peevaf8416e2021-02-04 17:52:43 -08003945 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003946 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003947 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3948 isZslCapture = true;
3949 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003950 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003951 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003952 res = parent->registerInFlight(halRequest->frame_number,
3953 totalNumBuffers, captureRequest->mResultExtras,
3954 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003955 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003956 expectedDurationInfo.minDuration,
3957 expectedDurationInfo.maxDuration,
3958 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003959 requestedPhysicalCameras, isStillCapture, isZslCapture,
3960 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003961 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003962 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003963 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3964 ", burstId = %" PRId32 ".",
3965 __FUNCTION__,
3966 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3967 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003968
3969 if (shouldUnlockSettings) {
3970 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3971 }
3972
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003973 if (res != OK) {
3974 SET_ERR("RequestThread: Unable to register new in-flight request:"
3975 " %s (%d)", strerror(-res), res);
3976 return INVALID_OPERATION;
3977 }
3978 }
3979
3980 return OK;
3981}
3982
Igor Murashkin1e479c02013-09-06 16:55:14 -07003983CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003984 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003985 Mutex::Autolock al(mLatestRequestMutex);
3986
3987 ALOGV("RequestThread::%s", __FUNCTION__);
3988
3989 return mLatestRequest;
3990}
3991
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003992bool Camera3Device::RequestThread::isStreamPending(
3993 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003994 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003995 Mutex::Autolock l(mRequestLock);
3996
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003997 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003998 if (!nextRequest.submitted) {
3999 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4000 if (stream == s) return true;
4001 }
4002 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004003 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004004 }
4005
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004006 for (const auto& request : mRequestQueue) {
4007 for (const auto& s : request->mOutputStreams) {
4008 if (stream == s) return true;
4009 }
4010 if (stream == request->mInputStream) return true;
4011 }
4012
4013 for (const auto& request : mRepeatingRequests) {
4014 for (const auto& s : request->mOutputStreams) {
4015 if (stream == s) return true;
4016 }
4017 if (stream == request->mInputStream) return true;
4018 }
4019
4020 return false;
4021}
Jianing Weicb0652e2014-03-12 18:29:36 -07004022
Emilian Peev40ead602017-09-26 15:46:36 +01004023bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4024 ATRACE_CALL();
4025 Mutex::Autolock l(mRequestLock);
4026
4027 for (const auto& nextRequest : mNextRequests) {
4028 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4029 if (s.first == streamId) {
4030 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4031 if (it != s.second.end()) {
4032 return true;
4033 }
4034 }
4035 }
4036 }
4037
4038 for (const auto& request : mRequestQueue) {
4039 for (const auto& s : request->mOutputSurfaces) {
4040 if (s.first == streamId) {
4041 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4042 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004043 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004044 }
4045 }
4046 }
4047 }
4048
4049 for (const auto& request : mRepeatingRequests) {
4050 for (const auto& s : request->mOutputSurfaces) {
4051 if (s.first == streamId) {
4052 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4053 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004054 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004055 }
4056 }
4057 }
4058 }
4059
4060 return false;
4061}
4062
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004063void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4064 if (!mUseHalBufManager) {
4065 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4066 return;
4067 }
4068
4069 Mutex::Autolock pl(mPauseLock);
4070 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004071 mInterface->signalPipelineDrain(streamIds);
4072 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004073 }
4074 // If request thread is still busy, wait until paused then notify HAL
4075 mNotifyPipelineDrain = true;
4076 mStreamIdsToBeDrained = streamIds;
4077}
4078
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004079void Camera3Device::RequestThread::resetPipelineDrain() {
4080 Mutex::Autolock pl(mPauseLock);
4081 mNotifyPipelineDrain = false;
4082 mStreamIdsToBeDrained.clear();
4083}
4084
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004085void Camera3Device::RequestThread::clearPreviousRequest() {
4086 Mutex::Autolock l(mRequestLock);
4087 mPrevRequest.clear();
4088}
4089
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004090status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4091 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4092 ATRACE_CALL();
4093 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004094 mRotateAndCropOverride = rotateAndCropValue;
4095 return OK;
4096}
4097
Emilian Peeve23f1d92021-09-20 14:56:01 -07004098status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4099 ATRACE_CALL();
4100 Mutex::Autolock l(mTriggerMutex);
4101 mComposerOutput = composerSurfacePresent;
4102 return OK;
4103}
4104
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004105status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004106 ATRACE_CALL();
4107 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004108 if (muteMode != mCameraMute) {
4109 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004110 mCameraMuteChanged = true;
4111 }
4112 return OK;
4113}
4114
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004115nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004116 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004117 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004118 return mExpectedInflightDuration > kMinInflightDuration ?
4119 mExpectedInflightDuration : kMinInflightDuration;
4120}
4121
Emilian Peevaebbe412018-01-15 13:53:24 +00004122void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004123 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004124 if ((request == nullptr) || (halRequest == nullptr)) {
4125 ALOGE("%s: Invalid request!", __FUNCTION__);
4126 return;
4127 }
4128
4129 if (halRequest->num_physcam_settings > 0) {
4130 if (halRequest->physcam_id != nullptr) {
4131 delete [] halRequest->physcam_id;
4132 halRequest->physcam_id = nullptr;
4133 }
4134 if (halRequest->physcam_settings != nullptr) {
4135 auto it = ++(request->mSettingsList.begin());
4136 size_t i = 0;
4137 for (; it != request->mSettingsList.end(); it++, i++) {
4138 it->metadata.unlock(halRequest->physcam_settings[i]);
4139 }
4140 delete [] halRequest->physcam_settings;
4141 halRequest->physcam_settings = nullptr;
4142 }
4143 }
4144}
4145
Ravneet74cd3732022-03-30 05:33:03 +00004146status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4147 Mutex::Autolock il(mInterfaceLock);
4148 Mutex::Autolock l(mLock);
4149
4150 if (mCameraServiceWatchdog != NULL) {
4151 mCameraServiceWatchdog->setEnabled(enabled);
4152 }
4153
4154 return OK;
4155}
4156
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004157void Camera3Device::setStreamUseCaseOverrides(
4158 const std::vector<int64_t>& useCaseOverrides) {
4159 Mutex::Autolock il(mInterfaceLock);
4160 Mutex::Autolock l(mLock);
4161 mStreamUseCaseOverrides = useCaseOverrides;
4162}
4163
4164void Camera3Device::clearStreamUseCaseOverrides() {
4165 Mutex::Autolock il(mInterfaceLock);
4166 Mutex::Autolock l(mLock);
4167 mStreamUseCaseOverrides.clear();
4168}
4169
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004170void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4171 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004172 return;
4173 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004174
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004175 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004176 // Skip the ones that have been submitted successfully.
4177 if (nextRequest.submitted) {
4178 continue;
4179 }
4180
4181 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004182 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4183 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004184
4185 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004186 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004187 }
4188
Emilian Peevaebbe412018-01-15 13:53:24 +00004189 cleanupPhysicalSettings(captureRequest, halRequest);
4190
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004191 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004192 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004193 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4194 }
4195
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004196 // No output buffer can be returned when using HAL buffer manager
4197 if (!mUseHalBufManager) {
4198 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4199 //Buffers that failed processing could still have
4200 //valid acquire fence.
4201 int acquireFence = (*outputBuffers)[i].acquire_fence;
4202 if (0 <= acquireFence) {
4203 close(acquireFence);
4204 outputBuffers->editItemAt(i).acquire_fence = -1;
4205 }
Emilian Peevf4816702020-04-03 15:44:51 -07004206 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004207 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4208 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004209 /*timestampIncreasing*/true, std::vector<size_t> (),
4210 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004211 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004212 }
4213
4214 if (sendRequestError) {
4215 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004216 sp<NotificationListener> listener = mListener.promote();
4217 if (listener != NULL) {
4218 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004219 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004220 captureRequest->mResultExtras);
4221 }
4222 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004223
4224 // Remove yet-to-be submitted inflight request from inflightMap
4225 {
4226 sp<Camera3Device> parent = mParent.promote();
4227 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004228 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004229 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4230 if (idx >= 0) {
4231 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4232 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4233 parent->removeInFlightMapEntryLocked(idx);
4234 }
4235 }
4236 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004237 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004238
4239 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004240 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004241}
4242
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004243void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004244 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004245 // Optimized a bit for the simple steady-state case (single repeating
4246 // request), to avoid putting that request in the queue temporarily.
4247 Mutex::Autolock l(mRequestLock);
4248
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004249 assert(mNextRequests.empty());
4250
4251 NextRequest nextRequest;
4252 nextRequest.captureRequest = waitForNextRequestLocked();
4253 if (nextRequest.captureRequest == nullptr) {
4254 return;
4255 }
4256
Emilian Peevf4816702020-04-03 15:44:51 -07004257 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004258 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004259 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004260
4261 // Wait for additional requests
4262 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4263
4264 for (size_t i = 1; i < batchSize; i++) {
4265 NextRequest additionalRequest;
4266 additionalRequest.captureRequest = waitForNextRequestLocked();
4267 if (additionalRequest.captureRequest == nullptr) {
4268 break;
4269 }
4270
Emilian Peevf4816702020-04-03 15:44:51 -07004271 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004272 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004273 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004274 }
4275
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004276 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004277 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004278 mNextRequests.size(), batchSize);
4279 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004280 }
4281
4282 return;
4283}
4284
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004285void Camera3Device::RequestThread::setRequestClearing() {
4286 Mutex::Autolock l(mRequestLock);
4287 mRequestClearing = true;
4288}
4289
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004290sp<Camera3Device::CaptureRequest>
4291 Camera3Device::RequestThread::waitForNextRequestLocked() {
4292 status_t res;
4293 sp<CaptureRequest> nextRequest;
4294
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 while (mRequestQueue.empty()) {
4296 if (!mRepeatingRequests.empty()) {
4297 // Always atomically enqueue all requests in a repeating request
4298 // list. Guarantees a complete in-sequence set of captures to
4299 // application.
4300 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004301 if (mFirstRepeating) {
4302 mFirstRepeating = false;
4303 } else {
4304 for (auto& request : requests) {
4305 // For repeating requests, override timestamp request using
4306 // the time a request is inserted into the request queue,
4307 // because the original repeating request will have an old
4308 // fixed timestamp.
4309 request->mRequestTimeNs = systemTime();
4310 }
4311 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 RequestList::const_iterator firstRequest =
4313 requests.begin();
4314 nextRequest = *firstRequest;
4315 mRequestQueue.insert(mRequestQueue.end(),
4316 ++firstRequest,
4317 requests.end());
4318 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004319
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004320 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004321
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 break;
4323 }
4324
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004325 if (!mRequestClearing) {
4326 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4327 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004328
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004329 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4330 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331 Mutex::Autolock pl(mPauseLock);
4332 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004333 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004335 if (mNotifyPipelineDrain) {
4336 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4337 mNotifyPipelineDrain = false;
4338 mStreamIdsToBeDrained.clear();
4339 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004340 // Let the tracker know
4341 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4342 if (statusTracker != 0) {
4343 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4344 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004345 sp<Camera3Device> parent = mParent.promote();
4346 if (parent != nullptr) {
4347 parent->mRequestBufferSM.onRequestThreadPaused();
4348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004349 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004350 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 // Stop waiting for now and let thread management happen
4352 return NULL;
4353 }
4354 }
4355
4356 if (nextRequest == NULL) {
4357 // Don't have a repeating request already in hand, so queue
4358 // must have an entry now.
4359 RequestList::iterator firstRequest =
4360 mRequestQueue.begin();
4361 nextRequest = *firstRequest;
4362 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004363 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4364 sp<NotificationListener> listener = mListener.promote();
4365 if (listener != NULL) {
4366 listener->notifyRequestQueueEmpty();
4367 }
4368 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004369 }
4370
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004371 // In case we've been unpaused by setPaused clearing mDoPause, need to
4372 // update internal pause state (capture/setRepeatingRequest unpause
4373 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004374 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004375 if (mPaused) {
4376 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4377 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4378 if (statusTracker != 0) {
4379 statusTracker->markComponentActive(mStatusId);
4380 }
4381 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004382 mPaused = false;
4383
4384 // Check if we've reconfigured since last time, and reset the preview
4385 // request if so. Can't use 'NULL request == repeat' across configure calls.
4386 if (mReconfigured) {
4387 mPrevRequest.clear();
4388 mReconfigured = false;
4389 }
4390
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004391 if (nextRequest != NULL) {
4392 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004393 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4394 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004395
4396 // Since RequestThread::clear() removes buffers from the input stream,
4397 // get the right buffer here before unlocking mRequestLock
4398 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004399 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4400 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004401 if (res != OK) {
4402 // Can't get input buffer from gralloc queue - this could be due to
4403 // disconnected queue or other producer misbehavior, so not a fatal
4404 // error
4405 ALOGE("%s: Can't get input buffer, skipping request:"
4406 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004407
4408 sp<NotificationListener> listener = mListener.promote();
4409 if (listener != NULL) {
4410 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004411 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004412 nextRequest->mResultExtras);
4413 }
4414 return NULL;
4415 }
4416 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004417 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004418
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004419 return nextRequest;
4420}
4421
4422bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004423 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004424 status_t res;
4425 Mutex::Autolock l(mPauseLock);
4426 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004427 if (mPaused == false) {
4428 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004429 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004430 if (mNotifyPipelineDrain) {
4431 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4432 mNotifyPipelineDrain = false;
4433 mStreamIdsToBeDrained.clear();
4434 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004435 // Let the tracker know
4436 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4437 if (statusTracker != 0) {
4438 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4439 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004440 sp<Camera3Device> parent = mParent.promote();
4441 if (parent != nullptr) {
4442 parent->mRequestBufferSM.onRequestThreadPaused();
4443 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004444 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004445
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004446 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004447 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 return true;
4449 }
4450 }
4451 // We don't set mPaused to false here, because waitForNextRequest needs
4452 // to further manage the paused state in case of starvation.
4453 return false;
4454}
4455
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004456void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004457 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004458 // With work to do, mark thread as unpaused.
4459 // If paused by request (setPaused), don't resume, to avoid
4460 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004461 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004462 Mutex::Autolock p(mPauseLock);
4463 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004464 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4465 if (mPaused) {
4466 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4467 if (statusTracker != 0) {
4468 statusTracker->markComponentActive(mStatusId);
4469 }
4470 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004471 mPaused = false;
4472 }
4473}
4474
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004475void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4476 sp<Camera3Device> parent = mParent.promote();
4477 if (parent != NULL) {
4478 va_list args;
4479 va_start(args, fmt);
4480
4481 parent->setErrorStateV(fmt, args);
4482
4483 va_end(args);
4484 }
4485}
4486
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004487status_t Camera3Device::RequestThread::insertTriggers(
4488 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004489 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004490 Mutex::Autolock al(mTriggerMutex);
4491
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004492 sp<Camera3Device> parent = mParent.promote();
4493 if (parent == NULL) {
4494 CLOGE("RequestThread: Parent is gone");
4495 return DEAD_OBJECT;
4496 }
4497
Emilian Peevaebbe412018-01-15 13:53:24 +00004498 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004499 size_t count = mTriggerMap.size();
4500
4501 for (size_t i = 0; i < count; ++i) {
4502 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004503 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004504
4505 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4506 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4507 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004508 if (isAeTrigger) {
4509 request->mResultExtras.precaptureTriggerId = triggerId;
4510 mCurrentPreCaptureTriggerId = triggerId;
4511 } else {
4512 request->mResultExtras.afTriggerId = triggerId;
4513 mCurrentAfTriggerId = triggerId;
4514 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004515 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004516 }
4517
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004518 camera_metadata_entry entry = metadata.find(tag);
4519
4520 if (entry.count > 0) {
4521 /**
4522 * Already has an entry for this trigger in the request.
4523 * Rewrite it with our requested trigger value.
4524 */
4525 RequestTrigger oldTrigger = trigger;
4526
4527 oldTrigger.entryValue = entry.data.u8[0];
4528
4529 mTriggerReplacedMap.add(tag, oldTrigger);
4530 } else {
4531 /**
4532 * More typical, no trigger entry, so we just add it
4533 */
4534 mTriggerRemovedMap.add(tag, trigger);
4535 }
4536
4537 status_t res;
4538
4539 switch (trigger.getTagType()) {
4540 case TYPE_BYTE: {
4541 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4542 res = metadata.update(tag,
4543 &entryValue,
4544 /*count*/1);
4545 break;
4546 }
4547 case TYPE_INT32:
4548 res = metadata.update(tag,
4549 &trigger.entryValue,
4550 /*count*/1);
4551 break;
4552 default:
4553 ALOGE("%s: Type not supported: 0x%x",
4554 __FUNCTION__,
4555 trigger.getTagType());
4556 return INVALID_OPERATION;
4557 }
4558
4559 if (res != OK) {
4560 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4561 ", value %d", __FUNCTION__, trigger.getTagName(),
4562 trigger.entryValue);
4563 return res;
4564 }
4565
4566 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4567 trigger.getTagName(),
4568 trigger.entryValue);
4569 }
4570
4571 mTriggerMap.clear();
4572
4573 return count;
4574}
4575
4576status_t Camera3Device::RequestThread::removeTriggers(
4577 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004578 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004579 Mutex::Autolock al(mTriggerMutex);
4580
Emilian Peevaebbe412018-01-15 13:53:24 +00004581 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004582
4583 /**
4584 * Replace all old entries with their old values.
4585 */
4586 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4587 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4588
4589 status_t res;
4590
4591 uint32_t tag = trigger.metadataTag;
4592 switch (trigger.getTagType()) {
4593 case TYPE_BYTE: {
4594 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4595 res = metadata.update(tag,
4596 &entryValue,
4597 /*count*/1);
4598 break;
4599 }
4600 case TYPE_INT32:
4601 res = metadata.update(tag,
4602 &trigger.entryValue,
4603 /*count*/1);
4604 break;
4605 default:
4606 ALOGE("%s: Type not supported: 0x%x",
4607 __FUNCTION__,
4608 trigger.getTagType());
4609 return INVALID_OPERATION;
4610 }
4611
4612 if (res != OK) {
4613 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4614 ", trigger value %d", __FUNCTION__,
4615 trigger.getTagName(), trigger.entryValue);
4616 return res;
4617 }
4618 }
4619 mTriggerReplacedMap.clear();
4620
4621 /**
4622 * Remove all new entries.
4623 */
4624 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4625 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4626 status_t res = metadata.erase(trigger.metadataTag);
4627
4628 if (res != OK) {
4629 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4630 ", trigger value %d", __FUNCTION__,
4631 trigger.getTagName(), trigger.entryValue);
4632 return res;
4633 }
4634 }
4635 mTriggerRemovedMap.clear();
4636
4637 return OK;
4638}
4639
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004640status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004641 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004642 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004643 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004644 status_t res;
4645
Emilian Peevaebbe412018-01-15 13:53:24 +00004646 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004647
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004648 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004649 // exists
4650 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4651 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4652 if (afTrigger.count > 0 &&
4653 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4654 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004655 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004656 if (res != OK) return res;
4657 }
4658
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004659 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004660 // if none already exists
4661 camera_metadata_entry pcTrigger =
4662 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4663 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4664 if (pcTrigger.count > 0 &&
4665 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4666 pcId.count == 0) {
4667 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004668 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004669 if (res != OK) return res;
4670 }
4671
4672 return OK;
4673}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004674
Emilian Peevb9f83812023-03-17 17:13:07 -07004675bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4676 ATRACE_CALL();
4677 Mutex::Autolock l(mTriggerMutex);
4678 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4679 this->mRotateAndCropOverride);
4680}
4681
4682bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4683 bool overrideToPortrait,
4684 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004685 ATRACE_CALL();
4686
Emilian Peevb9f83812023-03-17 17:13:07 -07004687 if (overrideToPortrait) {
4688 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger3560b7e2022-10-27 12:20:29 -07004689 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4690 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4691 &rotateAndCrop_u8, 1);
4692 return true;
4693 }
4694
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004695 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004696 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4697
4698 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4699 if (rotateAndCropEntry.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07004700 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004701 return false;
4702 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004703 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004704 return true;
4705 }
4706 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004707 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4708 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004709 return true;
4710 }
4711 }
Emilian Peevb9f83812023-03-17 17:13:07 -07004712
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004713 return false;
4714}
4715
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004716bool Camera3Device::RequestThread::overrideTestPattern(
4717 const sp<CaptureRequest> &request) {
4718 ATRACE_CALL();
4719
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004720 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004721
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004722 Mutex::Autolock l(mTriggerMutex);
4723
4724 bool changed = false;
4725
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004726 // For a multi-camera, the physical cameras support the same set of
4727 // test pattern modes as the logical camera.
4728 for (auto& settings : request->mSettingsList) {
4729 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004730
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004731 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4732 int32_t testPatternData[4] = {
4733 settings.mOriginalTestPatternData[0],
4734 settings.mOriginalTestPatternData[1],
4735 settings.mOriginalTestPatternData[2],
4736 settings.mOriginalTestPatternData[3]
4737 };
4738 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4739 testPatternMode = mCameraMute;
4740 testPatternData[0] = 0;
4741 testPatternData[1] = 0;
4742 testPatternData[2] = 0;
4743 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004744 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004745
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004746 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4747 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4748 if (testPatternEntry.count > 0) {
4749 if (testPatternEntry.data.i32[0] != testPatternMode) {
4750 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004751 changed = true;
4752 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004753 } else if (supportTestPatternModeKey) {
4754 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4755 &testPatternMode, 1);
4756 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004757 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004758
4759 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4760 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4761 if (testPatternColor.count >= 4) {
4762 for (size_t i = 0; i < 4; i++) {
4763 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4764 testPatternColor.data.i32[i] = testPatternData[i];
4765 changed = true;
4766 }
4767 }
4768 } else if (supportTestPatternDataKey) {
4769 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4770 testPatternData, 4);
4771 changed = true;
4772 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004773 }
4774
4775 return changed;
4776}
4777
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004778status_t Camera3Device::RequestThread::setHalInterface(
4779 sp<HalInterface> newHalInterface) {
4780 if (newHalInterface.get() == nullptr) {
4781 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4782 return DEAD_OBJECT;
4783 }
4784
4785 mInterface = newHalInterface;
4786
4787 return OK;
4788}
4789
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004790/**
4791 * PreparerThread inner class methods
4792 */
4793
4794Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004795 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004796 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004797}
4798
4799Camera3Device::PreparerThread::~PreparerThread() {
4800 Thread::requestExitAndWait();
4801 if (mCurrentStream != nullptr) {
4802 mCurrentStream->cancelPrepare();
4803 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4804 mCurrentStream.clear();
4805 }
4806 clear();
4807}
4808
Ruben Brunkc78ac262015-08-13 17:58:46 -07004809status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004810 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004811 status_t res;
4812
4813 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004814 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004815
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004816 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817 if (res == OK) {
4818 // No preparation needed, fire listener right off
4819 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004820 if (listener != NULL) {
4821 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004822 }
4823 return OK;
4824 } else if (res != NOT_ENOUGH_DATA) {
4825 return res;
4826 }
4827
4828 // Need to prepare, start up thread if necessary
4829 if (!mActive) {
4830 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4831 // isn't running
4832 Thread::requestExitAndWait();
4833 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4834 if (res != OK) {
4835 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004836 if (listener != NULL) {
4837 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004838 }
4839 return res;
4840 }
4841 mCancelNow = false;
4842 mActive = true;
4843 ALOGV("%s: Preparer stream started", __FUNCTION__);
4844 }
4845
4846 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004847 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004848 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4849
4850 return OK;
4851}
4852
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004853void Camera3Device::PreparerThread::pause() {
4854 ATRACE_CALL();
4855
4856 Mutex::Autolock l(mLock);
4857
4858 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4859 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4860 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4861 int currentMaxCount = mCurrentMaxCount;
4862 mPendingStreams.clear();
4863 mCancelNow = true;
4864 while (mActive) {
4865 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4866 if (res == TIMED_OUT) {
4867 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4868 return;
4869 } else if (res != OK) {
4870 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4871 return;
4872 }
4873 }
4874
4875 //Check whether the prepare thread was able to complete the current
4876 //stream. In case work is still pending emplace it along with the rest
4877 //of the streams in the pending list.
4878 if (currentStream != nullptr) {
4879 if (!mCurrentPrepareComplete) {
4880 pendingStreams.emplace(currentMaxCount, currentStream);
4881 }
4882 }
4883
4884 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4885 for (const auto& it : mPendingStreams) {
4886 it.second->cancelPrepare();
4887 }
4888}
4889
4890status_t Camera3Device::PreparerThread::resume() {
4891 ATRACE_CALL();
4892 status_t res;
4893
4894 Mutex::Autolock l(mLock);
4895 sp<NotificationListener> listener = mListener.promote();
4896
4897 if (mActive) {
4898 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4899 return NO_INIT;
4900 }
4901
4902 auto it = mPendingStreams.begin();
4903 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004904 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004905 if (res == OK) {
4906 if (listener != NULL) {
4907 listener->notifyPrepared(it->second->getId());
4908 }
4909 it = mPendingStreams.erase(it);
4910 } else if (res != NOT_ENOUGH_DATA) {
4911 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4912 res, strerror(-res));
4913 it = mPendingStreams.erase(it);
4914 } else {
4915 it++;
4916 }
4917 }
4918
4919 if (mPendingStreams.empty()) {
4920 return OK;
4921 }
4922
4923 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4924 if (res != OK) {
4925 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4926 __FUNCTION__, res, strerror(-res));
4927 return res;
4928 }
4929 mCancelNow = false;
4930 mActive = true;
4931 ALOGV("%s: Preparer stream started", __FUNCTION__);
4932
4933 return OK;
4934}
4935
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004936status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004937 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004938 Mutex::Autolock l(mLock);
4939
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004940 for (const auto& it : mPendingStreams) {
4941 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004942 }
4943 mPendingStreams.clear();
4944 mCancelNow = true;
4945
4946 return OK;
4947}
4948
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004949void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004950 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004951 Mutex::Autolock l(mLock);
4952 mListener = listener;
4953}
4954
4955bool Camera3Device::PreparerThread::threadLoop() {
4956 status_t res;
4957 {
4958 Mutex::Autolock l(mLock);
4959 if (mCurrentStream == nullptr) {
4960 // End thread if done with work
4961 if (mPendingStreams.empty()) {
4962 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4963 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4964 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4965 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004966 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004967 return false;
4968 }
4969
4970 // Get next stream to prepare
4971 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004972 mCurrentStream = it->second;
4973 mCurrentMaxCount = it->first;
4974 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004975 mPendingStreams.erase(it);
4976 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4977 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4978 } else if (mCancelNow) {
4979 mCurrentStream->cancelPrepare();
4980 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4981 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4982 mCurrentStream.clear();
4983 mCancelNow = false;
4984 return true;
4985 }
4986 }
4987
4988 res = mCurrentStream->prepareNextBuffer();
4989 if (res == NOT_ENOUGH_DATA) return true;
4990 if (res != OK) {
4991 // Something bad happened; try to recover by cancelling prepare and
4992 // signalling listener anyway
4993 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4994 mCurrentStream->getId(), res, strerror(-res));
4995 mCurrentStream->cancelPrepare();
4996 }
4997
4998 // This stream has finished, notify listener
4999 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005000 sp<NotificationListener> listener = mListener.promote();
5001 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005002 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5003 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005004 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005005 }
5006
5007 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5008 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005009 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005010
5011 return true;
5012}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005013
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005014status_t Camera3Device::RequestBufferStateMachine::initialize(
5015 sp<camera3::StatusTracker> statusTracker) {
5016 if (statusTracker == nullptr) {
5017 ALOGE("%s: statusTracker is null", __FUNCTION__);
5018 return BAD_VALUE;
5019 }
5020
5021 std::lock_guard<std::mutex> lock(mLock);
5022 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005023 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005024 return OK;
5025}
5026
5027bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5028 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005029 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005030 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005031 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005032 return true;
5033 }
5034 return false;
5035}
5036
5037void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5038 std::lock_guard<std::mutex> lock(mLock);
5039 if (!mRequestBufferOngoing) {
5040 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5041 return;
5042 }
5043 mRequestBufferOngoing = false;
5044 if (mStatus == RB_STATUS_PENDING_STOP) {
5045 checkSwitchToStopLocked();
5046 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005047 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005048}
5049
5050void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5051 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005052 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005053 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005054 return;
5055}
5056
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005057void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005058 std::lock_guard<std::mutex> lock(mLock);
5059 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005060 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5061 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005062 mInflightMapEmpty = false;
5063 if (mStatus == RB_STATUS_STOPPED) {
5064 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005065 }
5066 return;
5067}
5068
5069void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5070 std::lock_guard<std::mutex> lock(mLock);
5071 mRequestThreadPaused = true;
5072 if (mStatus == RB_STATUS_PENDING_STOP) {
5073 checkSwitchToStopLocked();
5074 }
5075 return;
5076}
5077
5078void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5079 std::lock_guard<std::mutex> lock(mLock);
5080 mInflightMapEmpty = true;
5081 if (mStatus == RB_STATUS_PENDING_STOP) {
5082 checkSwitchToStopLocked();
5083 }
5084 return;
5085}
5086
5087void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5088 std::lock_guard<std::mutex> lock(mLock);
5089 if (!checkSwitchToStopLocked()) {
5090 mStatus = RB_STATUS_PENDING_STOP;
5091 }
5092 return;
5093}
5094
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005095bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5096 std::lock_guard<std::mutex> lock(mLock);
5097 if (mRequestBufferOngoing) {
5098 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5099 __FUNCTION__);
5100 return false;
5101 }
5102 mSwitchedToOffline = true;
5103 mInflightMapEmpty = true;
5104 mRequestThreadPaused = true;
5105 mStatus = RB_STATUS_STOPPED;
5106 return true;
5107}
5108
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005109void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5110 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5111 if (statusTracker != nullptr) {
5112 if (active) {
5113 statusTracker->markComponentActive(mRequestBufferStatusId);
5114 } else {
5115 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5116 }
5117 }
5118}
5119
5120bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5121 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5122 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005123 return true;
5124 }
5125 return false;
5126}
5127
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005128bool Camera3Device::startRequestBuffer() {
5129 return mRequestBufferSM.startRequestBuffer();
5130}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005131
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005132void Camera3Device::endRequestBuffer() {
5133 mRequestBufferSM.endRequestBuffer();
5134}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005135
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005136nsecs_t Camera3Device::getWaitDuration() {
5137 return kBaseGetBufferWait + getExpectedInFlightDuration();
5138}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005139
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005140void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5141 mInterface->getInflightBufferKeys(out);
5142}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005143
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005144void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5145 mInterface->getInflightRequestBufferKeys(out);
5146}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005147
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005148std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5149 std::vector<sp<Camera3StreamInterface>> ret;
5150 bool hasInputStream = mInputStream != nullptr;
5151 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5152 if (hasInputStream) {
5153 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005154 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005155 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5156 ret.push_back(mOutputStreams[i]);
5157 }
5158 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5159 ret.push_back(mDeletedStreams[i]);
5160 }
5161 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005162}
5163
Emilian Peevcc0b7952020-01-07 13:54:47 -08005164void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5165 ATRACE_CALL();
5166
5167 if (offlineStreamIds == nullptr) {
5168 return;
5169 }
5170
5171 Mutex::Autolock il(mInterfaceLock);
5172
5173 auto streamIds = mOutputStreams.getStreamIds();
5174 bool hasInputStream = mInputStream != nullptr;
5175 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5176 offlineStreamIds->push_back(mInputStream->getId());
5177 }
5178
5179 for (const auto & streamId : streamIds) {
5180 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5181 // Streams that use the camera buffer manager are currently not supported in
5182 // offline mode
5183 if (stream->getOfflineProcessingSupport() &&
5184 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5185 offlineStreamIds->push_back(streamId);
5186 }
5187 }
5188}
5189
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005190status_t Camera3Device::setRotateAndCropAutoBehavior(
5191 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5192 ATRACE_CALL();
5193 Mutex::Autolock il(mInterfaceLock);
5194 Mutex::Autolock l(mLock);
5195 if (mRequestThread == nullptr) {
5196 return INVALID_OPERATION;
5197 }
Emilian Peevb9f83812023-03-17 17:13:07 -07005198 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5199 return BAD_VALUE;
5200 }
5201 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005202 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5203}
5204
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005205bool Camera3Device::supportsCameraMute() {
5206 Mutex::Autolock il(mInterfaceLock);
5207 Mutex::Autolock l(mLock);
5208
5209 return mSupportCameraMute;
5210}
5211
5212status_t Camera3Device::setCameraMute(bool enabled) {
5213 ATRACE_CALL();
5214 Mutex::Autolock il(mInterfaceLock);
5215 Mutex::Autolock l(mLock);
5216
5217 if (mRequestThread == nullptr || !mSupportCameraMute) {
5218 return INVALID_OPERATION;
5219 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005220 int32_t muteMode =
5221 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5222 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5223 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5224 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005225}
5226
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005227status_t Camera3Device::injectCamera(const String8& injectedCamId,
5228 sp<CameraProviderManager> manager) {
5229 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5230 ATRACE_CALL();
5231 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005232 // When the camera device is active, injectCamera() and stopInjection() will call
5233 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5234 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5235 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5236 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5237 // waitUntilStateThenRelock().
5238 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005239
5240 status_t res = NO_ERROR;
5241 if (mInjectionMethods->isInjecting()) {
5242 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5243 return OK;
5244 } else {
5245 res = mInjectionMethods->stopInjection();
5246 if (res != OK) {
5247 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5248 __FUNCTION__, res);
5249 return res;
5250 }
5251 }
5252 }
5253
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005254 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005255 if (res != OK) {
5256 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5257 __FUNCTION__, res);
5258 return res;
5259 }
5260
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005261 // When the second display of android is cast to the remote device, and the opened camera is
5262 // also cast to the second display, in this case, because the camera has configured the streams
5263 // at this time, we can directly call injectCamera() to replace the internal camera with
5264 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005265 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5266 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5267
5268 camera3::camera_stream_configuration injectionConfig;
5269 std::vector<uint32_t> injectionBufferSizes;
5270 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5271 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5272 || injectionBufferSizes.size() <= 0) {
5273 ALOGE("Failed to inject camera due to abandoned configuration! "
5274 "mOperatingMode: %d injectionConfig.num_streams: %d "
5275 "injectionBufferSizes.size(): %zu", mOperatingMode,
5276 injectionConfig.num_streams, injectionBufferSizes.size());
5277 return DEAD_OBJECT;
5278 }
5279
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005280 res = mInjectionMethods->injectCamera(
5281 injectionConfig, injectionBufferSizes);
5282 if (res != OK) {
5283 ALOGE("Can't finish inject camera process!");
5284 return res;
5285 }
5286 }
5287
5288 return OK;
5289}
5290
5291status_t Camera3Device::stopInjection() {
5292 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5293 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005294 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005295 return mInjectionMethods->stopInjection();
5296}
5297
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005298void Camera3Device::overrideStreamUseCaseLocked() {
5299 if (mStreamUseCaseOverrides.size() == 0) {
5300 return;
5301 }
5302
5303 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5304 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5305 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5306 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5307 outputStreamsIndices[i] = i;
5308 }
5309
5310 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5311 [&](int a, int b) -> bool {
5312
5313 auto formatScore = [](int format) {
5314 switch (format) {
5315 case HAL_PIXEL_FORMAT_BLOB:
5316 return 4;
5317 case HAL_PIXEL_FORMAT_RAW16:
5318 case HAL_PIXEL_FORMAT_RAW10:
5319 case HAL_PIXEL_FORMAT_RAW12:
5320 return 3;
5321 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5322 return 2;
5323 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5324 return 1;
5325 default:
5326 return 0;
5327 }
5328 };
5329
5330 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5331 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5332 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5333 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5334 if (sizeA > sizeB ||
5335 (sizeA == sizeB && formatAScore >= formatBScore)) {
5336 return true;
5337 } else {
5338 return false;
5339 }
5340 });
5341
5342 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5343 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5344 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5345 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5346 }
5347}
5348
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005349}; // namespace android