blob: 74dbe27330e0a9c3e1c962c78b07f516bf6ba087 [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),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002933 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002934 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002935 mCurrentAfTriggerId(0),
2936 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002937 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002938 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002939 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002940 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002941 mRepeatingLastFrameNumber(
2942 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002943 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002944 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002945 mRequestLatency(kRequestLatencyBinSize),
2946 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002947 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002948 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002949 mSupportCameraMute(supportCameraMute),
2950 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002951 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002952}
2953
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954Camera3Device::RequestThread::~RequestThread() {}
2955
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002956void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002957 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002958 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959 Mutex::Autolock l(mRequestLock);
2960 mListener = listener;
2961}
2962
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002963void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002964 const CameraMetadata& sessionParams,
2965 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002966 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002967 Mutex::Autolock l(mRequestLock);
2968 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002969 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002970 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002971 // Prepare video stream for high speed recording.
2972 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002973 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974}
2975
Jianing Wei90e59c92014-03-12 18:29:36 -07002976status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002977 List<sp<CaptureRequest> > &requests,
2978 /*out*/
2979 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002980 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002981 Mutex::Autolock l(mRequestLock);
2982 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2983 ++it) {
2984 mRequestQueue.push_back(*it);
2985 }
2986
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002987 if (lastFrameNumber != NULL) {
2988 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2989 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2990 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2991 *lastFrameNumber);
2992 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002993
Jianing Wei90e59c92014-03-12 18:29:36 -07002994 unpauseForNewRequests();
2995
2996 return OK;
2997}
2998
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002999
3000status_t Camera3Device::RequestThread::queueTrigger(
3001 RequestTrigger trigger[],
3002 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003003 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003004 Mutex::Autolock l(mTriggerMutex);
3005 status_t ret;
3006
3007 for (size_t i = 0; i < count; ++i) {
3008 ret = queueTriggerLocked(trigger[i]);
3009
3010 if (ret != OK) {
3011 return ret;
3012 }
3013 }
3014
3015 return OK;
3016}
3017
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003018const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3019 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003020 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003021 if (d != nullptr) return d->mId;
3022 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023}
3024
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003025status_t Camera3Device::RequestThread::queueTriggerLocked(
3026 RequestTrigger trigger) {
3027
3028 uint32_t tag = trigger.metadataTag;
3029 ssize_t index = mTriggerMap.indexOfKey(tag);
3030
3031 switch (trigger.getTagType()) {
3032 case TYPE_BYTE:
3033 // fall-through
3034 case TYPE_INT32:
3035 break;
3036 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003037 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3038 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003039 return INVALID_OPERATION;
3040 }
3041
3042 /**
3043 * Collect only the latest trigger, since we only have 1 field
3044 * in the request settings per trigger tag, and can't send more than 1
3045 * trigger per request.
3046 */
3047 if (index != NAME_NOT_FOUND) {
3048 mTriggerMap.editValueAt(index) = trigger;
3049 } else {
3050 mTriggerMap.add(tag, trigger);
3051 }
3052
3053 return OK;
3054}
3055
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003056status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003057 const RequestList &requests,
3058 /*out*/
3059 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003061 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003062 if (lastFrameNumber != NULL) {
3063 *lastFrameNumber = mRepeatingLastFrameNumber;
3064 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003065 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003066 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003067 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3068 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003069
3070 unpauseForNewRequests();
3071
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003073 return OK;
3074}
3075
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003076bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003077 if (mRepeatingRequests.empty()) {
3078 return false;
3079 }
3080 int32_t requestId = requestIn->mResultExtras.requestId;
3081 const RequestList &repeatRequests = mRepeatingRequests;
3082 // All repeating requests are guaranteed to have same id so only check first quest
3083 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3084 return (firstRequest->mResultExtras.requestId == requestId);
3085}
3086
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003087status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003088 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003089 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003090 return clearRepeatingRequestsLocked(lastFrameNumber);
3091
3092}
3093
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003094status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3095 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003096 std::vector<int32_t> streamIds;
3097 for (const auto& request : mRepeatingRequests) {
3098 for (const auto& stream : request->mOutputStreams) {
3099 streamIds.push_back(stream->getId());
3100 }
3101 }
3102
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003103 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003104 if (lastFrameNumber != NULL) {
3105 *lastFrameNumber = mRepeatingLastFrameNumber;
3106 }
Emilian Peev2295df72021-11-12 18:14:10 -08003107
3108 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003111 return OK;
3112}
3113
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003114status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003115 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003116 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003117 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003118 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003120 // Send errors for all requests pending in the request queue, including
3121 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003122 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003123 if (listener != NULL) {
3124 for (RequestList::iterator it = mRequestQueue.begin();
3125 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003126 // Abort the input buffers for reprocess requests.
3127 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003128 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003129 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003130 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003131 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003132 if (res != OK) {
3133 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3134 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3135 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003136 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003137 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3138 if (res != OK) {
3139 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3140 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3141 }
3142 }
3143 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003144 // Set the frame number this request would have had, if it
3145 // had been submitted; this frame number will not be reused.
3146 // The requestId and burstId fields were set when the request was
3147 // submitted originally (in convertMetadataListToRequestListLocked)
3148 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003149 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003150 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003151 }
3152 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003153 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003154
3155 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003156 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003157 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003158 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003159 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003160 return OK;
3161}
3162
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003163status_t Camera3Device::RequestThread::flush() {
3164 ATRACE_CALL();
3165 Mutex::Autolock l(mFlushLock);
3166
Emilian Peev08dd2452017-04-06 16:55:14 +01003167 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003168}
3169
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003170void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003171 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003172 Mutex::Autolock l(mPauseLock);
3173 mDoPause = paused;
3174 mDoPauseSignal.signal();
3175}
3176
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003177status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3178 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003179 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003180 Mutex::Autolock l(mLatestRequestMutex);
3181 status_t res;
3182 while (mLatestRequestId != requestId) {
3183 nsecs_t startTime = systemTime();
3184
3185 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3186 if (res != OK) return res;
3187
3188 timeout -= (systemTime() - startTime);
3189 }
3190
3191 return OK;
3192}
3193
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003194void Camera3Device::RequestThread::requestExit() {
3195 // Call parent to set up shutdown
3196 Thread::requestExit();
3197 // The exit from any possible waits
3198 mDoPauseSignal.signal();
3199 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003200
3201 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3202 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003203}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003204
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003205void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003206 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003207 bool surfaceAbandoned = false;
3208 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003209 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003210 {
3211 Mutex::Autolock l(mRequestLock);
3212 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3213 // repeating requests.
3214 for (const auto& request : mRepeatingRequests) {
3215 for (const auto& s : request->mOutputStreams) {
3216 if (s->isAbandoned()) {
3217 surfaceAbandoned = true;
3218 clearRepeatingRequestsLocked(&lastFrameNumber);
3219 break;
3220 }
3221 }
3222 if (surfaceAbandoned) {
3223 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003224 }
3225 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003226 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003227 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003228
3229 if (listener != NULL && surfaceAbandoned) {
3230 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003231 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003232}
3233
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003234bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003235 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003236 status_t res;
3237 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003238 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003239 uint32_t numRequestProcessed = 0;
3240 for (size_t i = 0; i < batchSize; i++) {
3241 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003242 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003243 }
3244
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003245 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3246
3247 bool triggerRemoveFailed = false;
3248 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3249 for (size_t i = 0; i < numRequestProcessed; i++) {
3250 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3251 nextRequest.submitted = true;
3252
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003253 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003254
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003255 if (!triggerRemoveFailed) {
3256 // Remove any previously queued triggers (after unlock)
3257 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3258 if (removeTriggerRes != OK) {
3259 triggerRemoveFailed = true;
3260 triggerFailedRequest = nextRequest;
3261 }
3262 }
3263 }
3264
3265 if (triggerRemoveFailed) {
3266 SET_ERR("RequestThread: Unable to remove triggers "
3267 "(capture request %d, HAL device: %s (%d)",
3268 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3269 cleanUpFailedRequests(/*sendRequestError*/ false);
3270 return false;
3271 }
3272
3273 if (res != OK) {
3274 // Should only get a failure here for malformed requests or device-level
3275 // errors, so consider all errors fatal. Bad metadata failures should
3276 // come through notify.
3277 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3278 mNextRequests[numRequestProcessed].halRequest.frame_number,
3279 strerror(-res), res);
3280 cleanUpFailedRequests(/*sendRequestError*/ false);
3281 return false;
3282 }
3283 return true;
3284}
3285
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003286Camera3Device::RequestThread::ExpectedDurationInfo
3287 Camera3Device::RequestThread::calculateExpectedDurationRange(
3288 const camera_metadata_t *request) {
3289 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003290 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003291 InFlightRequest::kDefaultMaxExpectedDuration,
3292 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003293 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3294 find_camera_metadata_ro_entry(request,
3295 ANDROID_CONTROL_AE_MODE,
3296 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003297 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003298
3299 switch (e.data.u8[0]) {
3300 case ANDROID_CONTROL_AE_MODE_OFF:
3301 find_camera_metadata_ro_entry(request,
3302 ANDROID_SENSOR_EXPOSURE_TIME,
3303 &e);
3304 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003305 expectedDurationInfo.minDuration = e.data.i64[0];
3306 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003307 }
3308 find_camera_metadata_ro_entry(request,
3309 ANDROID_SENSOR_FRAME_DURATION,
3310 &e);
3311 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003312 expectedDurationInfo.minDuration =
3313 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3314 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003315 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003316 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003317 break;
3318 default:
3319 find_camera_metadata_ro_entry(request,
3320 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3321 &e);
3322 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003323 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3324 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003325 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003326 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003327 break;
3328 }
3329
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003330 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003331}
3332
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003333bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3334 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3335 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3336 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3337 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3338 return true;
3339 }
3340
3341 return false;
3342}
3343
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003344void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3345 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003346 camera_capture_request_t& halRequest = nextRequest.halRequest;
3347 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003348 Mutex::Autolock al(mLatestRequestMutex);
3349
Shuzhen Wang83bff122020-11-20 15:51:39 -08003350 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003351 mLatestRequest.acquire(cloned);
3352
3353 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003354 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3355 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3356 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003357 CameraMetadata(cloned));
3358 }
3359
3360 sp<Camera3Device> parent = mParent.promote();
3361 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003362 int32_t inputStreamId = -1;
3363 if (halRequest.input_buffer != nullptr) {
3364 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3365 }
3366
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003367 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003368 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003369 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3370 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003371 }
3372 }
3373
Shuzhen Wang83bff122020-11-20 15:51:39 -08003374 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003375 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003376 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003377 }
3378
Shuzhen Wang83bff122020-11-20 15:51:39 -08003379 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003380}
3381
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003382bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3383 ATRACE_CALL();
3384 bool updatesDetected = false;
3385
Emilian Peev4ec17882019-01-24 17:16:58 -08003386 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003387 for (auto tag : mSessionParamKeys) {
3388 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003389 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003390
3391 if (entry.count > 0) {
3392 bool isDifferent = false;
3393 if (lastEntry.count > 0) {
3394 // Have a last value, compare to see if changed
3395 if (lastEntry.type == entry.type &&
3396 lastEntry.count == entry.count) {
3397 // Same type and count, compare values
3398 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3399 size_t entryBytes = bytesPerValue * lastEntry.count;
3400 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3401 if (cmp != 0) {
3402 isDifferent = true;
3403 }
3404 } else {
3405 // Count or type has changed
3406 isDifferent = true;
3407 }
3408 } else {
3409 // No last entry, so always consider to be different
3410 isDifferent = true;
3411 }
3412
3413 if (isDifferent) {
3414 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003415 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3416 updatesDetected = true;
3417 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003418 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003419 }
3420 } else if (lastEntry.count > 0) {
3421 // Value has been removed
3422 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003423 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003424 updatesDetected = true;
3425 }
3426 }
3427
Emilian Peev4ec17882019-01-24 17:16:58 -08003428 bool reconfigureRequired;
3429 if (updatesDetected) {
3430 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3431 updatedParams);
3432 mLatestSessionParams = updatedParams;
3433 } else {
3434 reconfigureRequired = false;
3435 }
3436
3437 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003438}
3439
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003440bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003441 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003442 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003443 // Any function called from threadLoop() must not hold mInterfaceLock since
3444 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3445 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446
3447 // Handle paused state.
3448 if (waitIfPaused()) {
3449 return true;
3450 }
3451
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003452 // Wait for the next batch of requests.
3453 waitForNextRequestBatch();
3454 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003455 return true;
3456 }
3457
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003458 // Get the latest request ID, if any
3459 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003460 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003461 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003462 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003463 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003464 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003465 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3466 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003467 }
3468
Emilian Peevb9f83812023-03-17 17:13:07 -07003469 for (size_t i = 0; i < mNextRequests.size(); i++) {
3470 auto& nextRequest = mNextRequests.editItemAt(i);
3471 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3472 // Do not override rotate&crop for stream configurations that include
3473 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3474 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3475 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3476 overrideAutoRotateAndCrop(captureRequest);
3477 }
3478
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003479 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3480 // or a single request from streaming or burst. In either case the first element
3481 // should contain the latest camera settings that we need to check for any session
3482 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003483 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003484 res = OK;
3485
3486 //Input stream buffers are already acquired at this point so an input stream
3487 //will not be able to move to idle state unless we force it.
3488 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3489 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3490 if (res != OK) {
3491 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3492 cleanUpFailedRequests(/*sendRequestError*/ false);
3493 return false;
3494 }
3495 }
3496
3497 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003498 sp<Camera3Device> parent = mParent.promote();
3499 if (parent != nullptr) {
3500 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003501 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003502 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003503
3504 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3505 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3506 if (res != OK) {
3507 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3508 cleanUpFailedRequests(/*sendRequestError*/ false);
3509 return false;
3510 }
3511 }
3512 }
3513 }
3514
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003515 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003516 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003517 if (res == TIMED_OUT) {
3518 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003519 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003520 // Check if any stream is abandoned.
3521 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003522 return true;
3523 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003524 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003525 return false;
3526 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003527
Zhijun Hecc27e112013-10-03 16:12:43 -07003528 // Inform waitUntilRequestProcessed thread of a new request ID
3529 {
3530 Mutex::Autolock al(mLatestRequestMutex);
3531
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003532 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003533 mLatestRequestSignal.signal();
3534 }
3535
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003536 // Submit a batch of requests to HAL.
3537 // Use flush lock only when submitting multilple requests in a batch.
3538 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3539 // which may take a long time to finish so synchronizing flush() and
3540 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3541 // For now, only synchronize for high speed recording and we should figure something out for
3542 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003543 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003544
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003545 if (useFlushLock) {
3546 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003547 }
3548
Zhijun Hef0645c12016-08-02 00:58:11 -07003549 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003550 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003551
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003552 sp<Camera3Device> parent = mParent.promote();
3553 if (parent != nullptr) {
3554 parent->mRequestBufferSM.onSubmittingRequest();
3555 }
3556
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003557 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003558 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003559 submitRequestSuccess = sendRequestsBatch();
3560
Shuzhen Wang686f6442017-06-20 16:16:04 -07003561 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3562 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003563
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003564 if (useFlushLock) {
3565 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003566 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003567
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003568 // Unset as current request
3569 {
3570 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003571 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003572 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003573 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003574
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003575 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003576}
3577
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003578status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3579 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3580 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3581 ANDROID_SCALER_CROP_REGION_SET};
3582 if (request == nullptr) {
3583 ALOGE("%s request metadata nullptr", __FUNCTION__);
3584 return BAD_VALUE;
3585 }
3586 status_t res = OK;
3587 for (const auto &key : kFwkOnlyRegionKeys) {
3588 if (request->exists(key)) {
3589 res = request->erase(key);
3590 if (res != OK) {
3591 return res;
3592 }
3593 }
3594 }
3595 return OK;
3596}
3597
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003598status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003599 ATRACE_CALL();
3600
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003601 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003602 for (size_t i = 0; i < mNextRequests.size(); i++) {
3603 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003604 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003605 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3606 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003607
3608 // Prepare a request to HAL
3609 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3610
3611 // Insert any queued triggers (before metadata is locked)
3612 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003613 if (res < 0) {
3614 SET_ERR("RequestThread: Unable to insert triggers "
3615 "(capture request %d, HAL device: %s (%d)",
3616 halRequest->frame_number, strerror(-res), res);
3617 return INVALID_OPERATION;
3618 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003619
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003620 int triggerCount = res;
3621 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3622 mPrevTriggers = triggerCount;
3623
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003624 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003625
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003626 // If the request is the same as last, or we had triggers now or last time or
3627 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003628 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003629 (mPrevRequest != captureRequest || triggersMixedIn ||
Emilian Peevb9f83812023-03-17 17:13:07 -07003630 captureRequest->mRotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003631 // Request settings are all the same within one batch, so only treat the first
3632 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003633 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003634 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003635 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003636 /**
3637 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003638 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003639 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003640 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003641 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003642 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 "(capture request %d, HAL device: %s (%d)",
3644 halRequest->frame_number, strerror(-res), res);
3645 return INVALID_OPERATION;
3646 }
3647
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003648 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003649 sp<Camera3Device> parent = mParent.promote();
3650 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003651 List<PhysicalCameraSettings>::iterator it;
3652 for (it = captureRequest->mSettingsList.begin();
3653 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003654 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3655 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003656 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3657 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3658 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3659 res);
3660 return INVALID_OPERATION;
3661 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003662 continue;
3663 }
3664
3665 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3666 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3667 updateCaptureRequest(&(it->metadata));
3668 if (res != OK) {
3669 SET_ERR("RequestThread: Unable to correct capture requests "
3670 "for scaler crop region and metering regions for request "
3671 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3672 res);
3673 return INVALID_OPERATION;
3674 }
3675 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003676 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3677 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3678 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3679 res);
3680 return INVALID_OPERATION;
3681 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003682 }
3683 }
3684
3685 // Correct metadata regions for distortion correction if enabled
3686 for (it = captureRequest->mSettingsList.begin();
3687 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003688 if (parent->mDistortionMappers.find(it->cameraId) ==
3689 parent->mDistortionMappers.end()) {
3690 continue;
3691 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003692
3693 if (!captureRequest->mDistortionCorrectionUpdated) {
3694 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3695 &(it->metadata));
3696 if (res != OK) {
3697 SET_ERR("RequestThread: Unable to correct capture requests "
3698 "for lens distortion for request %d: %s (%d)",
3699 halRequest->frame_number, strerror(-res), res);
3700 return INVALID_OPERATION;
3701 }
3702 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003703 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003704 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003705
3706 for (it = captureRequest->mSettingsList.begin();
3707 it != captureRequest->mSettingsList.end(); it++) {
3708 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3709 parent->mZoomRatioMappers.end()) {
3710 continue;
3711 }
3712
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003713 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003714 cameraIdsWithZoom.insert(it->cameraId);
3715 }
3716
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003717 if (!captureRequest->mZoomRatioUpdated) {
3718 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3719 &(it->metadata));
3720 if (res != OK) {
3721 SET_ERR("RequestThread: Unable to correct capture requests "
3722 "for zoom ratio for request %d: %s (%d)",
3723 halRequest->frame_number, strerror(-res), res);
3724 return INVALID_OPERATION;
3725 }
3726 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003727 }
3728 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003729 if (captureRequest->mRotateAndCropAuto &&
3730 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003731 for (it = captureRequest->mSettingsList.begin();
3732 it != captureRequest->mSettingsList.end(); it++) {
3733 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3734 if (mapper != parent->mRotateAndCropMappers.end()) {
3735 res = mapper->second.updateCaptureRequest(&(it->metadata));
3736 if (res != OK) {
3737 SET_ERR("RequestThread: Unable to correct capture requests "
3738 "for rotate-and-crop for request %d: %s (%d)",
3739 halRequest->frame_number, strerror(-res), res);
3740 return INVALID_OPERATION;
3741 }
3742 }
3743 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003744 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003745 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003746 }
3747 }
3748
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003749 /**
3750 * The request should be presorted so accesses in HAL
3751 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3752 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003753 captureRequest->mSettingsList.begin()->metadata.sort();
3754 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003755 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003756 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003757 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3758
3759 IF_ALOGV() {
3760 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3761 find_camera_metadata_ro_entry(
3762 halRequest->settings,
3763 ANDROID_CONTROL_AF_TRIGGER,
3764 &e
3765 );
3766 if (e.count > 0) {
3767 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3768 __FUNCTION__,
3769 halRequest->frame_number,
3770 e.data.u8[0]);
3771 }
3772 }
3773 } else {
3774 // leave request.settings NULL to indicate 'reuse latest given'
3775 ALOGVV("%s: Request settings are REUSED",
3776 __FUNCTION__);
3777 }
3778
Emilian Peevaebbe412018-01-15 13:53:24 +00003779 if (captureRequest->mSettingsList.size() > 1) {
3780 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3781 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003782 if (newRequest) {
3783 halRequest->physcam_settings =
3784 new const camera_metadata* [halRequest->num_physcam_settings];
3785 } else {
3786 halRequest->physcam_settings = nullptr;
3787 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003788 auto it = ++captureRequest->mSettingsList.begin();
3789 size_t i = 0;
3790 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3791 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003792 if (newRequest) {
3793 it->metadata.sort();
3794 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3795 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003796 }
3797 }
3798
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003799 uint32_t totalNumBuffers = 0;
3800
3801 // Fill in buffers
3802 if (captureRequest->mInputStream != NULL) {
3803 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003804
3805 halRequest->input_width = captureRequest->mInputBufferSize.width;
3806 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003807 totalNumBuffers += 1;
3808 } else {
3809 halRequest->input_buffer = NULL;
3810 }
3811
Emilian Peevf4816702020-04-03 15:44:51 -07003812 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003813 captureRequest->mOutputStreams.size());
3814 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003815 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003816
3817 sp<Camera3Device> parent = mParent.promote();
3818 if (parent == NULL) {
3819 // Should not happen, and nowhere to send errors to, so just log it
3820 CLOGE("RequestThread: Parent is gone");
3821 return INVALID_OPERATION;
3822 }
3823 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3824
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003825 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003826 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003827 sp<Camera3OutputStreamInterface> outputStream =
3828 captureRequest->mOutputStreams.editItemAt(j);
3829 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003830
3831 // Prepare video buffers for high speed recording on the first video request.
3832 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3833 // Only try to prepare video stream on the first video request.
3834 mPrepareVideoStream = false;
3835
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003836 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3837 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003838 while (res == NOT_ENOUGH_DATA) {
3839 res = outputStream->prepareNextBuffer();
3840 }
3841 if (res != OK) {
3842 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3843 __FUNCTION__, strerror(-res), res);
3844 outputStream->cancelPrepare();
3845 }
3846 }
3847
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003848 std::vector<size_t> uniqueSurfaceIds;
3849 res = outputStream->getUniqueSurfaceIds(
3850 captureRequest->mOutputSurfaces[streamId],
3851 &uniqueSurfaceIds);
3852 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3853 if (res != OK && res != INVALID_OPERATION) {
3854 ALOGE("%s: failed to query stream %d unique surface IDs",
3855 __FUNCTION__, streamId);
3856 return res;
3857 }
3858 if (res == OK) {
3859 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3860 }
3861
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003862 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003863 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003864 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003865 return TIMED_OUT;
3866 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003867 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003868 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003869 buffer.stream = outputStream->asHalStream();
3870 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003871 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003872 buffer.acquire_fence = -1;
3873 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003874 // Mark the output stream as unpreparable to block clients from calling
3875 // 'prepare' after this request reaches CameraHal and before the respective
3876 // buffers are requested.
3877 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003878 } else {
3879 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3880 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003881 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003882 if (res != OK) {
3883 // Can't get output buffer from gralloc queue - this could be due to
3884 // abandoned queue or other consumer misbehavior, so not a fatal
3885 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003886 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003887 " %s (%d)", strerror(-res), res);
3888
3889 return TIMED_OUT;
3890 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003892
3893 {
3894 sp<Camera3Device> parent = mParent.promote();
3895 if (parent != nullptr) {
3896 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3897 for (const auto& settings : captureRequest->mSettingsList) {
3898 if ((streamCameraId.isEmpty() &&
3899 parent->getId() == settings.cameraId.c_str()) ||
3900 streamCameraId == settings.cameraId.c_str()) {
3901 outputStream->fireBufferRequestForFrameNumber(
3902 captureRequest->mResultExtras.frameNumber,
3903 settings.metadata);
3904 }
3905 }
3906 }
3907 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003908
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003909 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003910 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3911 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3912 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3913 } else if (!physicalCameraId.isEmpty()) {
3914 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003915 }
3916 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003917 }
3918 totalNumBuffers += halRequest->num_output_buffers;
3919
3920 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003921 // If this request list is for constrained high speed recording (not
3922 // preview), and the current request is not the last one in the batch,
3923 // do not send callback to the app.
3924 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003925 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003926 hasCallback = false;
3927 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003928 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003929 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003930 const camera_metadata_t* settings = halRequest->settings;
3931 bool shouldUnlockSettings = false;
3932 if (settings == nullptr) {
3933 shouldUnlockSettings = true;
3934 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3935 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003936 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3937 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003938 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003939 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3940 isStillCapture = true;
3941 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3942 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003943
Emilian Peevaf8416e2021-02-04 17:52:43 -08003944 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003945 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003946 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3947 isZslCapture = true;
3948 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003949 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003950 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003951 res = parent->registerInFlight(halRequest->frame_number,
3952 totalNumBuffers, captureRequest->mResultExtras,
3953 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003954 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003955 expectedDurationInfo.minDuration,
3956 expectedDurationInfo.maxDuration,
3957 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003958 requestedPhysicalCameras, isStillCapture, isZslCapture,
3959 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003960 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003961 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003962 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3963 ", burstId = %" PRId32 ".",
3964 __FUNCTION__,
3965 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3966 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003967
3968 if (shouldUnlockSettings) {
3969 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3970 }
3971
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003972 if (res != OK) {
3973 SET_ERR("RequestThread: Unable to register new in-flight request:"
3974 " %s (%d)", strerror(-res), res);
3975 return INVALID_OPERATION;
3976 }
3977 }
3978
3979 return OK;
3980}
3981
Igor Murashkin1e479c02013-09-06 16:55:14 -07003982CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003983 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003984 Mutex::Autolock al(mLatestRequestMutex);
3985
3986 ALOGV("RequestThread::%s", __FUNCTION__);
3987
3988 return mLatestRequest;
3989}
3990
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003991bool Camera3Device::RequestThread::isStreamPending(
3992 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003993 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003994 Mutex::Autolock l(mRequestLock);
3995
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003996 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003997 if (!nextRequest.submitted) {
3998 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3999 if (stream == s) return true;
4000 }
4001 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004002 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004003 }
4004
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004005 for (const auto& request : mRequestQueue) {
4006 for (const auto& s : request->mOutputStreams) {
4007 if (stream == s) return true;
4008 }
4009 if (stream == request->mInputStream) return true;
4010 }
4011
4012 for (const auto& request : mRepeatingRequests) {
4013 for (const auto& s : request->mOutputStreams) {
4014 if (stream == s) return true;
4015 }
4016 if (stream == request->mInputStream) return true;
4017 }
4018
4019 return false;
4020}
Jianing Weicb0652e2014-03-12 18:29:36 -07004021
Emilian Peev40ead602017-09-26 15:46:36 +01004022bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4023 ATRACE_CALL();
4024 Mutex::Autolock l(mRequestLock);
4025
4026 for (const auto& nextRequest : mNextRequests) {
4027 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4028 if (s.first == streamId) {
4029 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4030 if (it != s.second.end()) {
4031 return true;
4032 }
4033 }
4034 }
4035 }
4036
4037 for (const auto& request : mRequestQueue) {
4038 for (const auto& s : request->mOutputSurfaces) {
4039 if (s.first == streamId) {
4040 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4041 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004042 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004043 }
4044 }
4045 }
4046 }
4047
4048 for (const auto& request : mRepeatingRequests) {
4049 for (const auto& s : request->mOutputSurfaces) {
4050 if (s.first == streamId) {
4051 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4052 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004053 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004054 }
4055 }
4056 }
4057 }
4058
4059 return false;
4060}
4061
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004062void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4063 if (!mUseHalBufManager) {
4064 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4065 return;
4066 }
4067
4068 Mutex::Autolock pl(mPauseLock);
4069 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004070 mInterface->signalPipelineDrain(streamIds);
4071 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004072 }
4073 // If request thread is still busy, wait until paused then notify HAL
4074 mNotifyPipelineDrain = true;
4075 mStreamIdsToBeDrained = streamIds;
4076}
4077
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004078void Camera3Device::RequestThread::resetPipelineDrain() {
4079 Mutex::Autolock pl(mPauseLock);
4080 mNotifyPipelineDrain = false;
4081 mStreamIdsToBeDrained.clear();
4082}
4083
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004084void Camera3Device::RequestThread::clearPreviousRequest() {
4085 Mutex::Autolock l(mRequestLock);
4086 mPrevRequest.clear();
4087}
4088
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004089status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4090 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4091 ATRACE_CALL();
4092 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004093 mRotateAndCropOverride = rotateAndCropValue;
4094 return OK;
4095}
4096
Emilian Peeve23f1d92021-09-20 14:56:01 -07004097status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4098 ATRACE_CALL();
4099 Mutex::Autolock l(mTriggerMutex);
4100 mComposerOutput = composerSurfacePresent;
4101 return OK;
4102}
4103
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004104status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004105 ATRACE_CALL();
4106 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004107 if (muteMode != mCameraMute) {
4108 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004109 mCameraMuteChanged = true;
4110 }
4111 return OK;
4112}
4113
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004114nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004115 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004116 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004117 return mExpectedInflightDuration > kMinInflightDuration ?
4118 mExpectedInflightDuration : kMinInflightDuration;
4119}
4120
Emilian Peevaebbe412018-01-15 13:53:24 +00004121void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004122 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004123 if ((request == nullptr) || (halRequest == nullptr)) {
4124 ALOGE("%s: Invalid request!", __FUNCTION__);
4125 return;
4126 }
4127
4128 if (halRequest->num_physcam_settings > 0) {
4129 if (halRequest->physcam_id != nullptr) {
4130 delete [] halRequest->physcam_id;
4131 halRequest->physcam_id = nullptr;
4132 }
4133 if (halRequest->physcam_settings != nullptr) {
4134 auto it = ++(request->mSettingsList.begin());
4135 size_t i = 0;
4136 for (; it != request->mSettingsList.end(); it++, i++) {
4137 it->metadata.unlock(halRequest->physcam_settings[i]);
4138 }
4139 delete [] halRequest->physcam_settings;
4140 halRequest->physcam_settings = nullptr;
4141 }
4142 }
4143}
4144
Ravneet74cd3732022-03-30 05:33:03 +00004145status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4146 Mutex::Autolock il(mInterfaceLock);
4147 Mutex::Autolock l(mLock);
4148
4149 if (mCameraServiceWatchdog != NULL) {
4150 mCameraServiceWatchdog->setEnabled(enabled);
4151 }
4152
4153 return OK;
4154}
4155
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004156void Camera3Device::setStreamUseCaseOverrides(
4157 const std::vector<int64_t>& useCaseOverrides) {
4158 Mutex::Autolock il(mInterfaceLock);
4159 Mutex::Autolock l(mLock);
4160 mStreamUseCaseOverrides = useCaseOverrides;
4161}
4162
4163void Camera3Device::clearStreamUseCaseOverrides() {
4164 Mutex::Autolock il(mInterfaceLock);
4165 Mutex::Autolock l(mLock);
4166 mStreamUseCaseOverrides.clear();
4167}
4168
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004169void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4170 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004171 return;
4172 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004173
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004174 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004175 // Skip the ones that have been submitted successfully.
4176 if (nextRequest.submitted) {
4177 continue;
4178 }
4179
4180 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004181 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4182 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004183
4184 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004185 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004186 }
4187
Emilian Peevaebbe412018-01-15 13:53:24 +00004188 cleanupPhysicalSettings(captureRequest, halRequest);
4189
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004190 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004191 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004192 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4193 }
4194
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004195 // No output buffer can be returned when using HAL buffer manager
4196 if (!mUseHalBufManager) {
4197 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4198 //Buffers that failed processing could still have
4199 //valid acquire fence.
4200 int acquireFence = (*outputBuffers)[i].acquire_fence;
4201 if (0 <= acquireFence) {
4202 close(acquireFence);
4203 outputBuffers->editItemAt(i).acquire_fence = -1;
4204 }
Emilian Peevf4816702020-04-03 15:44:51 -07004205 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004206 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4207 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004208 /*timestampIncreasing*/true, std::vector<size_t> (),
4209 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004210 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004211 }
4212
4213 if (sendRequestError) {
4214 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004215 sp<NotificationListener> listener = mListener.promote();
4216 if (listener != NULL) {
4217 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004218 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004219 captureRequest->mResultExtras);
4220 }
4221 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004222
4223 // Remove yet-to-be submitted inflight request from inflightMap
4224 {
4225 sp<Camera3Device> parent = mParent.promote();
4226 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004227 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004228 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4229 if (idx >= 0) {
4230 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4231 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4232 parent->removeInFlightMapEntryLocked(idx);
4233 }
4234 }
4235 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004236 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004237
4238 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004239 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004240}
4241
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004242void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004243 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004244 // Optimized a bit for the simple steady-state case (single repeating
4245 // request), to avoid putting that request in the queue temporarily.
4246 Mutex::Autolock l(mRequestLock);
4247
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004248 assert(mNextRequests.empty());
4249
4250 NextRequest nextRequest;
4251 nextRequest.captureRequest = waitForNextRequestLocked();
4252 if (nextRequest.captureRequest == nullptr) {
4253 return;
4254 }
4255
Emilian Peevf4816702020-04-03 15:44:51 -07004256 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004257 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004258 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004259
4260 // Wait for additional requests
4261 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4262
4263 for (size_t i = 1; i < batchSize; i++) {
4264 NextRequest additionalRequest;
4265 additionalRequest.captureRequest = waitForNextRequestLocked();
4266 if (additionalRequest.captureRequest == nullptr) {
4267 break;
4268 }
4269
Emilian Peevf4816702020-04-03 15:44:51 -07004270 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004272 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004273 }
4274
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004275 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004276 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004277 mNextRequests.size(), batchSize);
4278 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004279 }
4280
4281 return;
4282}
4283
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004284void Camera3Device::RequestThread::setRequestClearing() {
4285 Mutex::Autolock l(mRequestLock);
4286 mRequestClearing = true;
4287}
4288
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004289sp<Camera3Device::CaptureRequest>
4290 Camera3Device::RequestThread::waitForNextRequestLocked() {
4291 status_t res;
4292 sp<CaptureRequest> nextRequest;
4293
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294 while (mRequestQueue.empty()) {
4295 if (!mRepeatingRequests.empty()) {
4296 // Always atomically enqueue all requests in a repeating request
4297 // list. Guarantees a complete in-sequence set of captures to
4298 // application.
4299 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004300 if (mFirstRepeating) {
4301 mFirstRepeating = false;
4302 } else {
4303 for (auto& request : requests) {
4304 // For repeating requests, override timestamp request using
4305 // the time a request is inserted into the request queue,
4306 // because the original repeating request will have an old
4307 // fixed timestamp.
4308 request->mRequestTimeNs = systemTime();
4309 }
4310 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 RequestList::const_iterator firstRequest =
4312 requests.begin();
4313 nextRequest = *firstRequest;
4314 mRequestQueue.insert(mRequestQueue.end(),
4315 ++firstRequest,
4316 requests.end());
4317 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004318
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004319 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004320
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321 break;
4322 }
4323
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004324 if (!mRequestClearing) {
4325 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004327
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4329 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004330 Mutex::Autolock pl(mPauseLock);
4331 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004332 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004334 if (mNotifyPipelineDrain) {
4335 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4336 mNotifyPipelineDrain = false;
4337 mStreamIdsToBeDrained.clear();
4338 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004339 // Let the tracker know
4340 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4341 if (statusTracker != 0) {
4342 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4343 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004344 sp<Camera3Device> parent = mParent.promote();
4345 if (parent != nullptr) {
4346 parent->mRequestBufferSM.onRequestThreadPaused();
4347 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004349 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004350 // Stop waiting for now and let thread management happen
4351 return NULL;
4352 }
4353 }
4354
4355 if (nextRequest == NULL) {
4356 // Don't have a repeating request already in hand, so queue
4357 // must have an entry now.
4358 RequestList::iterator firstRequest =
4359 mRequestQueue.begin();
4360 nextRequest = *firstRequest;
4361 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004362 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4363 sp<NotificationListener> listener = mListener.promote();
4364 if (listener != NULL) {
4365 listener->notifyRequestQueueEmpty();
4366 }
4367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004368 }
4369
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004370 // In case we've been unpaused by setPaused clearing mDoPause, need to
4371 // update internal pause state (capture/setRepeatingRequest unpause
4372 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004373 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004374 if (mPaused) {
4375 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4376 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4377 if (statusTracker != 0) {
4378 statusTracker->markComponentActive(mStatusId);
4379 }
4380 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004381 mPaused = false;
4382
4383 // Check if we've reconfigured since last time, and reset the preview
4384 // request if so. Can't use 'NULL request == repeat' across configure calls.
4385 if (mReconfigured) {
4386 mPrevRequest.clear();
4387 mReconfigured = false;
4388 }
4389
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004390 if (nextRequest != NULL) {
4391 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004392 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4393 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004394
4395 // Since RequestThread::clear() removes buffers from the input stream,
4396 // get the right buffer here before unlocking mRequestLock
4397 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004398 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4399 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004400 if (res != OK) {
4401 // Can't get input buffer from gralloc queue - this could be due to
4402 // disconnected queue or other producer misbehavior, so not a fatal
4403 // error
4404 ALOGE("%s: Can't get input buffer, skipping request:"
4405 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004406
4407 sp<NotificationListener> listener = mListener.promote();
4408 if (listener != NULL) {
4409 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004410 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004411 nextRequest->mResultExtras);
4412 }
4413 return NULL;
4414 }
4415 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004416 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004417
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 return nextRequest;
4419}
4420
4421bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004422 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004423 status_t res;
4424 Mutex::Autolock l(mPauseLock);
4425 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004426 if (mPaused == false) {
4427 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004428 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004429 if (mNotifyPipelineDrain) {
4430 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4431 mNotifyPipelineDrain = false;
4432 mStreamIdsToBeDrained.clear();
4433 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004434 // Let the tracker know
4435 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4436 if (statusTracker != 0) {
4437 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4438 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004439 sp<Camera3Device> parent = mParent.promote();
4440 if (parent != nullptr) {
4441 parent->mRequestBufferSM.onRequestThreadPaused();
4442 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004443 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004444
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004445 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004446 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004447 return true;
4448 }
4449 }
4450 // We don't set mPaused to false here, because waitForNextRequest needs
4451 // to further manage the paused state in case of starvation.
4452 return false;
4453}
4454
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004455void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004456 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004457 // With work to do, mark thread as unpaused.
4458 // If paused by request (setPaused), don't resume, to avoid
4459 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004460 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004461 Mutex::Autolock p(mPauseLock);
4462 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004463 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4464 if (mPaused) {
4465 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4466 if (statusTracker != 0) {
4467 statusTracker->markComponentActive(mStatusId);
4468 }
4469 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004470 mPaused = false;
4471 }
4472}
4473
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004474void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4475 sp<Camera3Device> parent = mParent.promote();
4476 if (parent != NULL) {
4477 va_list args;
4478 va_start(args, fmt);
4479
4480 parent->setErrorStateV(fmt, args);
4481
4482 va_end(args);
4483 }
4484}
4485
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004486status_t Camera3Device::RequestThread::insertTriggers(
4487 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004488 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004489 Mutex::Autolock al(mTriggerMutex);
4490
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004491 sp<Camera3Device> parent = mParent.promote();
4492 if (parent == NULL) {
4493 CLOGE("RequestThread: Parent is gone");
4494 return DEAD_OBJECT;
4495 }
4496
Emilian Peevaebbe412018-01-15 13:53:24 +00004497 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004498 size_t count = mTriggerMap.size();
4499
4500 for (size_t i = 0; i < count; ++i) {
4501 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004502 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004503
4504 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4505 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4506 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004507 if (isAeTrigger) {
4508 request->mResultExtras.precaptureTriggerId = triggerId;
4509 mCurrentPreCaptureTriggerId = triggerId;
4510 } else {
4511 request->mResultExtras.afTriggerId = triggerId;
4512 mCurrentAfTriggerId = triggerId;
4513 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004514 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004515 }
4516
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004517 camera_metadata_entry entry = metadata.find(tag);
4518
4519 if (entry.count > 0) {
4520 /**
4521 * Already has an entry for this trigger in the request.
4522 * Rewrite it with our requested trigger value.
4523 */
4524 RequestTrigger oldTrigger = trigger;
4525
4526 oldTrigger.entryValue = entry.data.u8[0];
4527
4528 mTriggerReplacedMap.add(tag, oldTrigger);
4529 } else {
4530 /**
4531 * More typical, no trigger entry, so we just add it
4532 */
4533 mTriggerRemovedMap.add(tag, trigger);
4534 }
4535
4536 status_t res;
4537
4538 switch (trigger.getTagType()) {
4539 case TYPE_BYTE: {
4540 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4541 res = metadata.update(tag,
4542 &entryValue,
4543 /*count*/1);
4544 break;
4545 }
4546 case TYPE_INT32:
4547 res = metadata.update(tag,
4548 &trigger.entryValue,
4549 /*count*/1);
4550 break;
4551 default:
4552 ALOGE("%s: Type not supported: 0x%x",
4553 __FUNCTION__,
4554 trigger.getTagType());
4555 return INVALID_OPERATION;
4556 }
4557
4558 if (res != OK) {
4559 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4560 ", value %d", __FUNCTION__, trigger.getTagName(),
4561 trigger.entryValue);
4562 return res;
4563 }
4564
4565 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4566 trigger.getTagName(),
4567 trigger.entryValue);
4568 }
4569
4570 mTriggerMap.clear();
4571
4572 return count;
4573}
4574
4575status_t Camera3Device::RequestThread::removeTriggers(
4576 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004577 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004578 Mutex::Autolock al(mTriggerMutex);
4579
Emilian Peevaebbe412018-01-15 13:53:24 +00004580 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004581
4582 /**
4583 * Replace all old entries with their old values.
4584 */
4585 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4586 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4587
4588 status_t res;
4589
4590 uint32_t tag = trigger.metadataTag;
4591 switch (trigger.getTagType()) {
4592 case TYPE_BYTE: {
4593 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4594 res = metadata.update(tag,
4595 &entryValue,
4596 /*count*/1);
4597 break;
4598 }
4599 case TYPE_INT32:
4600 res = metadata.update(tag,
4601 &trigger.entryValue,
4602 /*count*/1);
4603 break;
4604 default:
4605 ALOGE("%s: Type not supported: 0x%x",
4606 __FUNCTION__,
4607 trigger.getTagType());
4608 return INVALID_OPERATION;
4609 }
4610
4611 if (res != OK) {
4612 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4613 ", trigger value %d", __FUNCTION__,
4614 trigger.getTagName(), trigger.entryValue);
4615 return res;
4616 }
4617 }
4618 mTriggerReplacedMap.clear();
4619
4620 /**
4621 * Remove all new entries.
4622 */
4623 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4624 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4625 status_t res = metadata.erase(trigger.metadataTag);
4626
4627 if (res != OK) {
4628 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4629 ", trigger value %d", __FUNCTION__,
4630 trigger.getTagName(), trigger.entryValue);
4631 return res;
4632 }
4633 }
4634 mTriggerRemovedMap.clear();
4635
4636 return OK;
4637}
4638
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004639status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004640 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004641 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004642 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004643 status_t res;
4644
Emilian Peevaebbe412018-01-15 13:53:24 +00004645 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004646
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004647 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004648 // exists
4649 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4650 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4651 if (afTrigger.count > 0 &&
4652 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4653 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004654 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004655 if (res != OK) return res;
4656 }
4657
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004658 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004659 // if none already exists
4660 camera_metadata_entry pcTrigger =
4661 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4662 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4663 if (pcTrigger.count > 0 &&
4664 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4665 pcId.count == 0) {
4666 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004667 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004668 if (res != OK) return res;
4669 }
4670
4671 return OK;
4672}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004673
Emilian Peevb9f83812023-03-17 17:13:07 -07004674bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4675 ATRACE_CALL();
4676 Mutex::Autolock l(mTriggerMutex);
4677 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4678 this->mRotateAndCropOverride);
4679}
4680
4681bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4682 bool overrideToPortrait,
4683 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004684 ATRACE_CALL();
4685
Emilian Peevb9f83812023-03-17 17:13:07 -07004686 if (overrideToPortrait) {
4687 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger3560b7e2022-10-27 12:20:29 -07004688 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4689 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4690 &rotateAndCrop_u8, 1);
4691 return true;
4692 }
4693
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004694 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004695 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4696
4697 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4698 if (rotateAndCropEntry.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07004699 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004700 return false;
4701 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004702 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004703 return true;
4704 }
4705 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004706 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4707 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004708 return true;
4709 }
4710 }
Emilian Peevb9f83812023-03-17 17:13:07 -07004711
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004712 return false;
4713}
4714
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004715bool Camera3Device::RequestThread::overrideTestPattern(
4716 const sp<CaptureRequest> &request) {
4717 ATRACE_CALL();
4718
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004719 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004720
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004721 Mutex::Autolock l(mTriggerMutex);
4722
4723 bool changed = false;
4724
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004725 // For a multi-camera, the physical cameras support the same set of
4726 // test pattern modes as the logical camera.
4727 for (auto& settings : request->mSettingsList) {
4728 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004729
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004730 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4731 int32_t testPatternData[4] = {
4732 settings.mOriginalTestPatternData[0],
4733 settings.mOriginalTestPatternData[1],
4734 settings.mOriginalTestPatternData[2],
4735 settings.mOriginalTestPatternData[3]
4736 };
4737 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4738 testPatternMode = mCameraMute;
4739 testPatternData[0] = 0;
4740 testPatternData[1] = 0;
4741 testPatternData[2] = 0;
4742 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004743 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004744
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004745 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4746 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4747 if (testPatternEntry.count > 0) {
4748 if (testPatternEntry.data.i32[0] != testPatternMode) {
4749 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004750 changed = true;
4751 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004752 } else if (supportTestPatternModeKey) {
4753 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4754 &testPatternMode, 1);
4755 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004756 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004757
4758 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4759 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4760 if (testPatternColor.count >= 4) {
4761 for (size_t i = 0; i < 4; i++) {
4762 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4763 testPatternColor.data.i32[i] = testPatternData[i];
4764 changed = true;
4765 }
4766 }
4767 } else if (supportTestPatternDataKey) {
4768 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4769 testPatternData, 4);
4770 changed = true;
4771 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004772 }
4773
4774 return changed;
4775}
4776
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004777status_t Camera3Device::RequestThread::setHalInterface(
4778 sp<HalInterface> newHalInterface) {
4779 if (newHalInterface.get() == nullptr) {
4780 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4781 return DEAD_OBJECT;
4782 }
4783
4784 mInterface = newHalInterface;
4785
4786 return OK;
4787}
4788
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004789/**
4790 * PreparerThread inner class methods
4791 */
4792
4793Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004794 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004795 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004796}
4797
4798Camera3Device::PreparerThread::~PreparerThread() {
4799 Thread::requestExitAndWait();
4800 if (mCurrentStream != nullptr) {
4801 mCurrentStream->cancelPrepare();
4802 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4803 mCurrentStream.clear();
4804 }
4805 clear();
4806}
4807
Ruben Brunkc78ac262015-08-13 17:58:46 -07004808status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004809 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004810 status_t res;
4811
4812 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004813 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004814
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004815 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004816 if (res == OK) {
4817 // No preparation needed, fire listener right off
4818 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004819 if (listener != NULL) {
4820 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004821 }
4822 return OK;
4823 } else if (res != NOT_ENOUGH_DATA) {
4824 return res;
4825 }
4826
4827 // Need to prepare, start up thread if necessary
4828 if (!mActive) {
4829 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4830 // isn't running
4831 Thread::requestExitAndWait();
4832 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4833 if (res != OK) {
4834 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004835 if (listener != NULL) {
4836 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004837 }
4838 return res;
4839 }
4840 mCancelNow = false;
4841 mActive = true;
4842 ALOGV("%s: Preparer stream started", __FUNCTION__);
4843 }
4844
4845 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004846 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004847 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4848
4849 return OK;
4850}
4851
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004852void Camera3Device::PreparerThread::pause() {
4853 ATRACE_CALL();
4854
4855 Mutex::Autolock l(mLock);
4856
4857 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4858 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4859 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4860 int currentMaxCount = mCurrentMaxCount;
4861 mPendingStreams.clear();
4862 mCancelNow = true;
4863 while (mActive) {
4864 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4865 if (res == TIMED_OUT) {
4866 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4867 return;
4868 } else if (res != OK) {
4869 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4870 return;
4871 }
4872 }
4873
4874 //Check whether the prepare thread was able to complete the current
4875 //stream. In case work is still pending emplace it along with the rest
4876 //of the streams in the pending list.
4877 if (currentStream != nullptr) {
4878 if (!mCurrentPrepareComplete) {
4879 pendingStreams.emplace(currentMaxCount, currentStream);
4880 }
4881 }
4882
4883 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4884 for (const auto& it : mPendingStreams) {
4885 it.second->cancelPrepare();
4886 }
4887}
4888
4889status_t Camera3Device::PreparerThread::resume() {
4890 ATRACE_CALL();
4891 status_t res;
4892
4893 Mutex::Autolock l(mLock);
4894 sp<NotificationListener> listener = mListener.promote();
4895
4896 if (mActive) {
4897 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4898 return NO_INIT;
4899 }
4900
4901 auto it = mPendingStreams.begin();
4902 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004903 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004904 if (res == OK) {
4905 if (listener != NULL) {
4906 listener->notifyPrepared(it->second->getId());
4907 }
4908 it = mPendingStreams.erase(it);
4909 } else if (res != NOT_ENOUGH_DATA) {
4910 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4911 res, strerror(-res));
4912 it = mPendingStreams.erase(it);
4913 } else {
4914 it++;
4915 }
4916 }
4917
4918 if (mPendingStreams.empty()) {
4919 return OK;
4920 }
4921
4922 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4923 if (res != OK) {
4924 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4925 __FUNCTION__, res, strerror(-res));
4926 return res;
4927 }
4928 mCancelNow = false;
4929 mActive = true;
4930 ALOGV("%s: Preparer stream started", __FUNCTION__);
4931
4932 return OK;
4933}
4934
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004935status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004936 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004937 Mutex::Autolock l(mLock);
4938
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004939 for (const auto& it : mPendingStreams) {
4940 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004941 }
4942 mPendingStreams.clear();
4943 mCancelNow = true;
4944
4945 return OK;
4946}
4947
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004948void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004949 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004950 Mutex::Autolock l(mLock);
4951 mListener = listener;
4952}
4953
4954bool Camera3Device::PreparerThread::threadLoop() {
4955 status_t res;
4956 {
4957 Mutex::Autolock l(mLock);
4958 if (mCurrentStream == nullptr) {
4959 // End thread if done with work
4960 if (mPendingStreams.empty()) {
4961 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4962 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4963 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4964 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004965 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004966 return false;
4967 }
4968
4969 // Get next stream to prepare
4970 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004971 mCurrentStream = it->second;
4972 mCurrentMaxCount = it->first;
4973 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004974 mPendingStreams.erase(it);
4975 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4976 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4977 } else if (mCancelNow) {
4978 mCurrentStream->cancelPrepare();
4979 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4980 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4981 mCurrentStream.clear();
4982 mCancelNow = false;
4983 return true;
4984 }
4985 }
4986
4987 res = mCurrentStream->prepareNextBuffer();
4988 if (res == NOT_ENOUGH_DATA) return true;
4989 if (res != OK) {
4990 // Something bad happened; try to recover by cancelling prepare and
4991 // signalling listener anyway
4992 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4993 mCurrentStream->getId(), res, strerror(-res));
4994 mCurrentStream->cancelPrepare();
4995 }
4996
4997 // This stream has finished, notify listener
4998 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004999 sp<NotificationListener> listener = mListener.promote();
5000 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005001 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5002 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005003 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004 }
5005
5006 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5007 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005008 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005009
5010 return true;
5011}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005012
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005013status_t Camera3Device::RequestBufferStateMachine::initialize(
5014 sp<camera3::StatusTracker> statusTracker) {
5015 if (statusTracker == nullptr) {
5016 ALOGE("%s: statusTracker is null", __FUNCTION__);
5017 return BAD_VALUE;
5018 }
5019
5020 std::lock_guard<std::mutex> lock(mLock);
5021 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005022 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005023 return OK;
5024}
5025
5026bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5027 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005028 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005029 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005030 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005031 return true;
5032 }
5033 return false;
5034}
5035
5036void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5037 std::lock_guard<std::mutex> lock(mLock);
5038 if (!mRequestBufferOngoing) {
5039 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5040 return;
5041 }
5042 mRequestBufferOngoing = false;
5043 if (mStatus == RB_STATUS_PENDING_STOP) {
5044 checkSwitchToStopLocked();
5045 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005046 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005047}
5048
5049void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5050 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005051 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005052 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005053 return;
5054}
5055
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005056void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005057 std::lock_guard<std::mutex> lock(mLock);
5058 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005059 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5060 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005061 mInflightMapEmpty = false;
5062 if (mStatus == RB_STATUS_STOPPED) {
5063 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005064 }
5065 return;
5066}
5067
5068void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5069 std::lock_guard<std::mutex> lock(mLock);
5070 mRequestThreadPaused = true;
5071 if (mStatus == RB_STATUS_PENDING_STOP) {
5072 checkSwitchToStopLocked();
5073 }
5074 return;
5075}
5076
5077void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5078 std::lock_guard<std::mutex> lock(mLock);
5079 mInflightMapEmpty = true;
5080 if (mStatus == RB_STATUS_PENDING_STOP) {
5081 checkSwitchToStopLocked();
5082 }
5083 return;
5084}
5085
5086void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5087 std::lock_guard<std::mutex> lock(mLock);
5088 if (!checkSwitchToStopLocked()) {
5089 mStatus = RB_STATUS_PENDING_STOP;
5090 }
5091 return;
5092}
5093
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005094bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5095 std::lock_guard<std::mutex> lock(mLock);
5096 if (mRequestBufferOngoing) {
5097 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5098 __FUNCTION__);
5099 return false;
5100 }
5101 mSwitchedToOffline = true;
5102 mInflightMapEmpty = true;
5103 mRequestThreadPaused = true;
5104 mStatus = RB_STATUS_STOPPED;
5105 return true;
5106}
5107
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005108void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5109 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5110 if (statusTracker != nullptr) {
5111 if (active) {
5112 statusTracker->markComponentActive(mRequestBufferStatusId);
5113 } else {
5114 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5115 }
5116 }
5117}
5118
5119bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5120 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5121 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005122 return true;
5123 }
5124 return false;
5125}
5126
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005127bool Camera3Device::startRequestBuffer() {
5128 return mRequestBufferSM.startRequestBuffer();
5129}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005130
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005131void Camera3Device::endRequestBuffer() {
5132 mRequestBufferSM.endRequestBuffer();
5133}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005134
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005135nsecs_t Camera3Device::getWaitDuration() {
5136 return kBaseGetBufferWait + getExpectedInFlightDuration();
5137}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005138
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005139void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5140 mInterface->getInflightBufferKeys(out);
5141}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005143void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5144 mInterface->getInflightRequestBufferKeys(out);
5145}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005146
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005147std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5148 std::vector<sp<Camera3StreamInterface>> ret;
5149 bool hasInputStream = mInputStream != nullptr;
5150 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5151 if (hasInputStream) {
5152 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005153 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005154 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5155 ret.push_back(mOutputStreams[i]);
5156 }
5157 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5158 ret.push_back(mDeletedStreams[i]);
5159 }
5160 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005161}
5162
Emilian Peevcc0b7952020-01-07 13:54:47 -08005163void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5164 ATRACE_CALL();
5165
5166 if (offlineStreamIds == nullptr) {
5167 return;
5168 }
5169
5170 Mutex::Autolock il(mInterfaceLock);
5171
5172 auto streamIds = mOutputStreams.getStreamIds();
5173 bool hasInputStream = mInputStream != nullptr;
5174 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5175 offlineStreamIds->push_back(mInputStream->getId());
5176 }
5177
5178 for (const auto & streamId : streamIds) {
5179 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5180 // Streams that use the camera buffer manager are currently not supported in
5181 // offline mode
5182 if (stream->getOfflineProcessingSupport() &&
5183 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5184 offlineStreamIds->push_back(streamId);
5185 }
5186 }
5187}
5188
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005189status_t Camera3Device::setRotateAndCropAutoBehavior(
5190 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5191 ATRACE_CALL();
5192 Mutex::Autolock il(mInterfaceLock);
5193 Mutex::Autolock l(mLock);
5194 if (mRequestThread == nullptr) {
5195 return INVALID_OPERATION;
5196 }
Emilian Peevb9f83812023-03-17 17:13:07 -07005197 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5198 return BAD_VALUE;
5199 }
5200 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005201 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5202}
5203
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005204bool Camera3Device::supportsCameraMute() {
5205 Mutex::Autolock il(mInterfaceLock);
5206 Mutex::Autolock l(mLock);
5207
5208 return mSupportCameraMute;
5209}
5210
5211status_t Camera3Device::setCameraMute(bool enabled) {
5212 ATRACE_CALL();
5213 Mutex::Autolock il(mInterfaceLock);
5214 Mutex::Autolock l(mLock);
5215
5216 if (mRequestThread == nullptr || !mSupportCameraMute) {
5217 return INVALID_OPERATION;
5218 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005219 int32_t muteMode =
5220 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5221 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5222 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5223 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005224}
5225
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005226status_t Camera3Device::injectCamera(const String8& injectedCamId,
5227 sp<CameraProviderManager> manager) {
5228 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5229 ATRACE_CALL();
5230 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005231 // When the camera device is active, injectCamera() and stopInjection() will call
5232 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5233 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5234 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5235 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5236 // waitUntilStateThenRelock().
5237 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005238
5239 status_t res = NO_ERROR;
5240 if (mInjectionMethods->isInjecting()) {
5241 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5242 return OK;
5243 } else {
5244 res = mInjectionMethods->stopInjection();
5245 if (res != OK) {
5246 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5247 __FUNCTION__, res);
5248 return res;
5249 }
5250 }
5251 }
5252
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005253 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005254 if (res != OK) {
5255 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5256 __FUNCTION__, res);
5257 return res;
5258 }
5259
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005260 // When the second display of android is cast to the remote device, and the opened camera is
5261 // also cast to the second display, in this case, because the camera has configured the streams
5262 // at this time, we can directly call injectCamera() to replace the internal camera with
5263 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005264 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5265 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5266
5267 camera3::camera_stream_configuration injectionConfig;
5268 std::vector<uint32_t> injectionBufferSizes;
5269 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5270 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5271 || injectionBufferSizes.size() <= 0) {
5272 ALOGE("Failed to inject camera due to abandoned configuration! "
5273 "mOperatingMode: %d injectionConfig.num_streams: %d "
5274 "injectionBufferSizes.size(): %zu", mOperatingMode,
5275 injectionConfig.num_streams, injectionBufferSizes.size());
5276 return DEAD_OBJECT;
5277 }
5278
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005279 res = mInjectionMethods->injectCamera(
5280 injectionConfig, injectionBufferSizes);
5281 if (res != OK) {
5282 ALOGE("Can't finish inject camera process!");
5283 return res;
5284 }
5285 }
5286
5287 return OK;
5288}
5289
5290status_t Camera3Device::stopInjection() {
5291 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5292 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005293 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005294 return mInjectionMethods->stopInjection();
5295}
5296
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005297void Camera3Device::overrideStreamUseCaseLocked() {
5298 if (mStreamUseCaseOverrides.size() == 0) {
5299 return;
5300 }
5301
5302 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5303 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5304 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5305 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5306 outputStreamsIndices[i] = i;
5307 }
5308
5309 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5310 [&](int a, int b) -> bool {
5311
5312 auto formatScore = [](int format) {
5313 switch (format) {
5314 case HAL_PIXEL_FORMAT_BLOB:
5315 return 4;
5316 case HAL_PIXEL_FORMAT_RAW16:
5317 case HAL_PIXEL_FORMAT_RAW10:
5318 case HAL_PIXEL_FORMAT_RAW12:
5319 return 3;
5320 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5321 return 2;
5322 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5323 return 1;
5324 default:
5325 return 0;
5326 }
5327 };
5328
5329 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5330 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5331 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5332 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5333 if (sizeA > sizeB ||
5334 (sizeA == sizeB && formatAScore >= formatBScore)) {
5335 return true;
5336 } else {
5337 return false;
5338 }
5339 });
5340
5341 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5342 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5343 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5344 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5345 }
5346}
5347
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005348}; // namespace android