blob: 3f380ea3af3779ed37cbf0cd510a77e233ce6b1e [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
Austin Borger0fb3ad92023-06-01 16:51:35 -070029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.c_str(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Austin Borger0fb3ad92023-06-01 16:51:35 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.c_str(), __FUNCTION__, \
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070033 ##__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
Austin Borger0fb3ad92023-06-01 16:51:35 -070047#include <android-base/stringprintf.h>
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080048#include <utils/Log.h>
49#include <utils/Trace.h>
50#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070051#include <cutils/properties.h>
Austin Borger0fb3ad92023-06-01 16:51:35 -070052#include <camera/StringUtils.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053
Cliff Wuc2ad9c82021-04-21 00:58:58 +080054#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080055#include <android/hardware/camera2/ICameraDeviceUser.h>
56
Igor Murashkinff3e31d2013-10-23 16:40:06 -070057#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070058#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070059#include "device3/Camera3Device.h"
60#include "device3/Camera3OutputStream.h"
61#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040062#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070063#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070064#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070065#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080066#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070067#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070068#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080069
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080070#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080071#include <tuple>
72
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080073using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Austin Borger0fb3ad92023-06-01 16:51:35 -070078Camera3Device::Camera3Device(const std::string &id, bool overrideForPerfClass, bool overrideToPortrait,
Austin Borger3560b7e2022-10-27 12:20:29 -070079 bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080080 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070081 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080082 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070083 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070084 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070085 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070086 mUsePartialResult(false),
87 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080088 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080089 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070091 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070093 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070094 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070095 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000096 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010097 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070098 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070099 mNeedFixupMonochromeTags(false),
Austin Borger3560b7e2022-10-27 12:20:29 -0700100 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800101 mOverrideToPortrait(overrideToPortrait),
Emilian Peevb9f83812023-03-17 17:13:07 -0700102 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
103 mComposerOutput(false),
Austin Borgerc8099762023-01-12 17:08:46 -0800104 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800105{
106 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -0700107 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.c_str());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800108}
109
110Camera3Device::~Camera3Device()
111{
112 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -0700113 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.c_str());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700114 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800115}
116
Austin Borger0fb3ad92023-06-01 16:51:35 -0700117const std::string& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800118 return mId;
119}
120
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800121status_t Camera3Device::initializeCommonLocked() {
122
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700123 /** Start up status tracker thread */
124 mStatusTracker = new StatusTracker(this);
Austin Borger0fb3ad92023-06-01 16:51:35 -0700125 status_t res = mStatusTracker->run((std::string("C3Dev-") + mId + "-Status").c_str());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700126 if (res != OK) {
127 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
128 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700130 mStatusTracker.clear();
131 return res;
132 }
133
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700134 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700135 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700136
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700137 if (mUseHalBufManager) {
138 res = mRequestBufferSM.initialize(mStatusTracker);
139 if (res != OK) {
140 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
141 strerror(-res), res);
142 mInterface->close();
143 mStatusTracker.clear();
144 return res;
145 }
146 }
147
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800148 /** Create buffer manager */
149 mBufferManager = new Camera3BufferManager();
150
151 Vector<int32_t> sessionParamKeys;
152 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
153 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
154 if (sessionKeysEntry.count > 0) {
155 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
156 }
157
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700158 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
159 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
160 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
161 if (availableTestPatternModes.data.i32[i] ==
162 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
163 mSupportCameraMute = true;
164 mSupportTestPatternSolidColor = true;
165 break;
166 } else if (availableTestPatternModes.data.i32[i] ==
167 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
168 mSupportCameraMute = true;
169 mSupportTestPatternSolidColor = false;
170 }
171 }
172
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700173 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800174 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700175 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger3560b7e2022-10-27 12:20:29 -0700176 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Austin Borger0fb3ad92023-06-01 16:51:35 -0700177 res = mRequestThread->run((std::string("C3Dev-") + mId + "-ReqQueue").c_str());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800178 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700179 SET_ERR_L("Unable to start request queue thread: %s (%d)",
180 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800181 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800182 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800183 return res;
184 }
185
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700186 mPreparerThread = new PreparerThread();
187
Ruben Brunk183f0562015-08-12 12:55:02 -0700188 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800189 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400190 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700191 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700192 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800193 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800194
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800195 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800196 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 camera_metadata_entry timestampSource =
198 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
199 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
200 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800201 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800202 }
203
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700204 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100205 camera_metadata_entry partialResultsCount =
206 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
207 if (partialResultsCount.count > 0) {
208 mNumPartialResults = partialResultsCount.data.i32[0];
209 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700210 }
211
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800212 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
213 if (usePrecorrectArray) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700214 res = mDistortionMappers[mId].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700215 if (res != OK) {
216 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
217 return res;
218 }
219 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800220
Austin Borger0fb3ad92023-06-01 16:51:35 -0700221 mZoomRatioMappers[mId] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800222 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800223
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700224 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700225 mUHRCropAndMeteringRegionMappers[mId] =
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700226 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
227 }
228
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800229 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700230 mRotateAndCropMappers.emplace(mId, &mDeviceInfo);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800231 }
232
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800233 // Hidl/AidlCamera3DeviceInjectionMethods
234 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800235
Ravneet74cd3732022-03-30 05:33:03 +0000236 /** Start watchdog thread */
237 mCameraServiceWatchdog = new CameraServiceWatchdog();
238 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
239 if (res != OK) {
240 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
241 strerror(-res), res);
242 return res;
243 }
244
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800245 return OK;
246}
247
248status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700249 return disconnectImpl();
250}
251
252status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800253 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700254 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800255
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700256 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700257 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700258 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800259 Mutex::Autolock il(mInterfaceLock);
260 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
261 {
262 Mutex::Autolock l(mLock);
263 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000265 if (mRequestThread != NULL) {
266 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
267 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800268 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000269 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800270 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000271 } else {
272 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
273 if (res != OK) {
274 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
275 maxExpectedDuration);
276 // Continue to close device even in case of error
277 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800278 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000280 // Signal to request thread that we're not expecting any
281 // more requests. This will be true since once we're in
282 // disconnect and we've cleared off the request queue, the
283 // request thread can't receive any new requests through
284 // binder calls - since disconnect holds
285 // mBinderSerialization lock.
286 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700287 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800288
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800289 if (mStatus == STATUS_ERROR) {
290 CLOGE("Shutting down in an error state");
291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800293 if (mStatusTracker != NULL) {
294 mStatusTracker->requestExit();
295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800297 if (mRequestThread != NULL) {
298 mRequestThread->requestExit();
299 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800301 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
302 for (size_t i = 0; i < mOutputStreams.size(); i++) {
303 streams.push_back(mOutputStreams[i]);
304 }
305 if (mInputStream != nullptr) {
306 streams.push_back(mInputStream);
307 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800310 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
311 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
313 // HAL may be in a bad state, so waiting for request thread
314 // (which may be stuck in the HAL processCaptureRequest call)
315 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800316 // give up mInterfaceLock here and then lock it again. Could this lead
317 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 mRequestThread->join();
319 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 Mutex::Autolock il(mInterfaceLock);
322 if (mStatusTracker != NULL) {
323 mStatusTracker->join();
324 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800325
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800326 if (mInjectionMethods->isInjecting()) {
327 mInjectionMethods->stopInjection();
328 }
329
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800330 HalInterface* interface;
331 {
332 Mutex::Autolock l(mLock);
333 mRequestThread.clear();
334 Mutex::Autolock stLock(mTrackerLock);
335 mStatusTracker.clear();
336 interface = mInterface.get();
337 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700338
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800339 // Call close without internal mutex held, as the HAL close may need to
340 // wait on assorted callbacks,etc, to complete before it can return.
Ravneet98ffa752022-03-02 07:22:46 +0000341 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700342
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800343 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800344
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800345 {
346 Mutex::Autolock l(mLock);
347 mInterface->clear();
348 mOutputStreams.clear();
349 mInputStream.clear();
350 mDeletedStreams.clear();
351 mBufferManager.clear();
352 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
353 }
354
355 for (auto& weakStream : streams) {
356 sp<Camera3StreamInterface> stream = weakStream.promote();
357 if (stream != nullptr) {
358 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
359 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
360 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700361 }
362 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700363 ALOGI("%s: X", __FUNCTION__);
Ravneet98ffa752022-03-02 07:22:46 +0000364
365 if (mCameraServiceWatchdog != NULL) {
366 mCameraServiceWatchdog->requestExit();
367 mCameraServiceWatchdog.clear();
368 }
369
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700370 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800371}
372
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700373// For dumping/debugging only -
374// try to acquire a lock a few times, eventually give up to proceed with
375// debug/dump operations
376bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
377 bool gotLock = false;
378 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
379 if (lock.tryLock() == NO_ERROR) {
380 gotLock = true;
381 break;
382 } else {
383 usleep(kDumpSleepDuration);
384 }
385 }
386 return gotLock;
387}
388
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800389nsecs_t Camera3Device::getMonoToBoottimeOffset() {
390 // try three times to get the clock offset, choose the one
391 // with the minimum gap in measurements.
392 const int tries = 3;
393 nsecs_t bestGap, measured;
394 for (int i = 0; i < tries; ++i) {
395 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
396 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
397 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
398 const nsecs_t gap = tmono2 - tmono;
399 if (i == 0 || gap < bestGap) {
400 bestGap = gap;
401 measured = tbase - ((tmono + tmono2) >> 1);
402 }
403 }
404 return measured;
405}
406
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800407ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
408 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700409 // Get max jpeg size (area-wise) for default sensor pixel mode
410 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800411 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700412 /*isUltraHighResolutionSensor*/false);
413 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
414 // not ultra high res sensor
415 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800416 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700417 /*isUltraHighResolution*/true);
418 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800419 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700420 __FUNCTION__, mId.c_str());
Zhijun Hef7da0962014-04-24 13:27:56 -0700421 return BAD_VALUE;
422 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 bool useMaxSensorPixelModeThreshold = false;
424 if (uhrMaxJpegResolution.width != 0 &&
425 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
426 // Use the ultra high res max jpeg size and max jpeg buffer size
427 useMaxSensorPixelModeThreshold = true;
428 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700429
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 // Get max jpeg buffer size
431 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800432 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700433 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800434 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
Austin Borger0fb3ad92023-06-01 16:51:35 -0700435 mId.c_str());
Zhijun Hef7da0962014-04-24 13:27:56 -0700436 return BAD_VALUE;
437 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700438 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700439
440 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
441 if (useMaxSensorPixelModeThreshold) {
442 maxJpegBufferSize =
443 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
444 maxDefaultJpegResolution, maxJpegBufferSize);
445 chosenMaxJpegResolution = uhrMaxJpegResolution;
446 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800447 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700448
449 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700450 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700451 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800452 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
453 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700454 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800455 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
456 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700457 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700458 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700459 return jpegBufferSize;
460}
461
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800462ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700463 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800464 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700465 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800466 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700467 __FUNCTION__, mId.c_str());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700468 return BAD_VALUE;
469 }
470 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
471 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
472 return maxBytesForPointCloud;
473}
474
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800475ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
476 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800477 const int PER_CONFIGURATION_SIZE = 3;
478 const int WIDTH_OFFSET = 0;
479 const int HEIGHT_OFFSET = 1;
480 const int SIZE_OFFSET = 2;
481 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800482 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800483 camera3::SessionConfigurationUtils::getAppropriateModeTag(
484 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
485 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800486 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800487 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700489 __FUNCTION__, mId.c_str(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800490 return BAD_VALUE;
491 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700492
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800493 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
494 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
495 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
496 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
497 }
498 }
499
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700501 __FUNCTION__, mId.c_str(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800502 return BAD_VALUE;
503}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700504
Jing Mikec7f9b132023-03-12 11:12:04 +0800505status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800506 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700507
508 // Try to lock, but continue in case of failure (to avoid blocking in
509 // deadlocks)
510 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
511 bool gotLock = tryLockSpinRightRound(mLock);
512
513 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800514 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700515 mId.c_str(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700516 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800517 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700518 mId.c_str(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700519
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800520 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700521
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800522 String16 templatesOption("-t");
523 int n = args.size();
524 for (int i = 0; i < n; i++) {
525 if (args[i] == templatesOption) {
526 dumpTemplates = true;
527 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700528 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700529 if (i + 1 < n) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700530 std::string monitorTags = toStdString(args[i + 1]);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700531 if (monitorTags == "off") {
532 mTagMonitor.disableMonitoring();
533 } else {
534 mTagMonitor.parseTagsToMonitor(monitorTags);
535 }
536 } else {
537 mTagMonitor.disableMonitoring();
538 }
539 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800540 }
541
Austin Borger0fb3ad92023-06-01 16:51:35 -0700542 std::string lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800544 const char *status =
545 mStatus == STATUS_ERROR ? "ERROR" :
546 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700547 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
548 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800549 mStatus == STATUS_ACTIVE ? "ACTIVE" :
550 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700551
Austin Borger0fb3ad92023-06-01 16:51:35 -0700552 lines += fmt::sprintf(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700553 if (mStatus == STATUS_ERROR) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700554 lines += fmt::sprintf(" Error cause: %s\n", mErrorCause.c_str());
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700555 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700556 lines += " Stream configuration:\n";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800557 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000558 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
559 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
560 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Austin Borger0fb3ad92023-06-01 16:51:35 -0700561 lines += fmt::sprintf(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800562
563 if (mInputStream != NULL) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700564 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800565 mInputStream->dump(fd, args);
566 } else {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700567 lines += " No input stream.\n";
568 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800569 }
570 for (size_t i = 0; i < mOutputStreams.size(); i++) {
571 mOutputStreams[i]->dump(fd,args);
572 }
573
Zhijun He431503c2016-03-07 17:30:16 -0800574 if (mBufferManager != NULL) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700575 lines = " Camera3 Buffer Manager:\n";
576 write(fd, lines.c_str(), lines.size());
Zhijun He431503c2016-03-07 17:30:16 -0800577 mBufferManager->dump(fd, args);
578 }
Zhijun He125684a2015-12-26 15:07:30 -0800579
Austin Borger0fb3ad92023-06-01 16:51:35 -0700580 lines = " In-flight requests:\n";
Emilian Peeva6138c52021-06-24 12:52:38 -0700581 if (mInFlightLock.try_lock()) {
582 if (mInFlightMap.size() == 0) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700583 lines += " None\n";
Emilian Peeva6138c52021-06-24 12:52:38 -0700584 } else {
585 for (size_t i = 0; i < mInFlightMap.size(); i++) {
586 InFlightRequest r = mInFlightMap.valueAt(i);
Austin Borger0fb3ad92023-06-01 16:51:35 -0700587 lines += fmt::sprintf(" Frame %d | Timestamp: %" PRId64 ", metadata"
Emilian Peeva6138c52021-06-24 12:52:38 -0700588 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
589 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
590 r.numBuffersLeft);
591 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700592 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700593 mInFlightLock.unlock();
594 } else {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700595 lines += " Failed to acquire In-flight lock!\n";
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700596 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700597 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700598
Shuzhen Wang686f6442017-06-20 16:16:04 -0700599 if (mRequestThread != NULL) {
600 mRequestThread->dumpCaptureRequestLatency(fd,
601 " ProcessCaptureRequest latency histogram:");
602 }
603
Igor Murashkin1e479c02013-09-06 16:55:14 -0700604 {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700605 lines = " Last request sent:\n";
606 write(fd, lines.c_str(), lines.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -0700607
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700608 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700609 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
610 }
611
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700613 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800614 "TEMPLATE_PREVIEW",
615 "TEMPLATE_STILL_CAPTURE",
616 "TEMPLATE_VIDEO_RECORD",
617 "TEMPLATE_VIDEO_SNAPSHOT",
618 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800619 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800620 };
621
Emilian Peevf4816702020-04-03 15:44:51 -0700622 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800623 camera_metadata_t *templateRequest = nullptr;
624 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700625 (camera_request_template_t) i, &templateRequest);
Austin Borger0fb3ad92023-06-01 16:51:35 -0700626 lines = fmt::sprintf(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800627 if (templateRequest == nullptr) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700628 lines += " Not supported\n";
629 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800630 } else {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700631 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800632 dump_indented_camera_metadata(templateRequest,
633 fd, /*verbosity*/2, /*indentation*/8);
634 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800636 }
637 }
638
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700639 mTagMonitor.dumpMonitoredMetadata(fd);
640
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 if (mInterface->valid()) {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700642 lines = " HAL device dump:\n";
643 write(fd, lines.c_str(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800644 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800645 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800646
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700647 if (gotLock) mLock.unlock();
648 if (gotInterfaceLock) mInterfaceLock.unlock();
649
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800650 return OK;
651}
652
Austin Borger0fb3ad92023-06-01 16:51:35 -0700653status_t Camera3Device::startWatchingTags(const std::string &tags) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700654 mTagMonitor.parseTagsToMonitor(tags);
655 return OK;
656}
657
658status_t Camera3Device::stopWatchingTags() {
659 mTagMonitor.disableMonitoring();
660 return OK;
661}
662
663status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
664 mTagMonitor.getLatestMonitoredTagEvents(out);
665 return OK;
666}
667
Austin Borger0fb3ad92023-06-01 16:51:35 -0700668const CameraMetadata& Camera3Device::infoPhysical(const std::string& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800669 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800670 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
671 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700672 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800673 mStatus == STATUS_ERROR ?
674 "when in error state" : "before init");
675 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700676 if (physicalId.empty()) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700677 return mDeviceInfo;
678 } else {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700679 if (mPhysicalDeviceInfoMap.find(physicalId) != mPhysicalDeviceInfoMap.end()) {
680 return mPhysicalDeviceInfoMap.at(physicalId);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700681 } else {
682 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
683 return mDeviceInfo;
684 }
685 }
686}
687
688const CameraMetadata& Camera3Device::info() const {
Austin Borger0fb3ad92023-06-01 16:51:35 -0700689 return infoPhysical(/*physicalId*/ std::string());
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;
Austin Borger0fb3ad92023-06-01 16:51:35 -0700783 requestList.push_back({getId(), request});
Emilian Peevaebbe412018-01-15 13:53:24 +0000784 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 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700835 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.c_str(),
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 }
Austin Borger0fb3ad92023-06-01 16:51:35 -0700918 ALOGV("Camera %s: Clearing repeating request", mId.c_str());
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",
Austin Borger0fb3ad92023-06-01 16:51:35 -0700937 mId.c_str(), 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
Austin Borger0fb3ad92023-06-01 16:51:35 -0700995 ALOGV("Camera %s: Created input stream", mId.c_str());
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,
Austin Borger0fb3ad92023-06-01 16:51:35 -07001002 const std::string& 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,
Austin Borger0fb3ad92023-06-01 16:51:35 -07001038 const std::string& physicalCameraId,
1039 const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001040 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001041 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1042 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001043 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001044
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001045 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001046 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001048 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001049 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001050 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1051 " mirrorMode %d",
Austin Borger0fb3ad92023-06-01 16:51:35 -07001052 mId.c_str(), mNextStreamId, width, height, format, dataSpace, rotation,
1053 consumerUsage, isShared, physicalCameraId.c_str(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001054 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001055
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001056 status_t res;
1057 bool wasActive = false;
1058
1059 switch (mStatus) {
1060 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001061 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 return INVALID_OPERATION;
1063 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001064 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001065 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001066 case STATUS_UNCONFIGURED:
1067 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001068 // OK
1069 break;
1070 case STATUS_ACTIVE:
1071 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001072 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001074 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001075 return res;
1076 }
1077 wasActive = true;
1078 break;
1079 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001080 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001081 return INVALID_OPERATION;
1082 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001083 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001084
1085 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001086
Shuzhen Wang0129d522016-10-30 22:43:41 -07001087 if (consumers.size() == 0 && !hasDeferredConsumer) {
1088 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1089 return BAD_VALUE;
1090 }
Zhijun He5d677d12016-05-29 16:52:39 -07001091
Shuzhen Wang0129d522016-10-30 22:43:41 -07001092 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001093 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1094 return BAD_VALUE;
1095 }
1096
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001097 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1098 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1099 // be found in only one sensor pixel mode.
1100 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1101 return BAD_VALUE;
1102 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001103 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001105 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001106 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001107 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001108 if (blobBufferSize <= 0) {
1109 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1110 return BAD_VALUE;
1111 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001112 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1113 blobBufferSize = width * height;
1114 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001115 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001116 if (blobBufferSize <= 0) {
1117 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1118 return BAD_VALUE;
1119 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001120 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001121 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001122 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001123 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001124 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001125 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001126 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001127 bool maxResolution =
1128 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1129 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001130 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1131 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001132 if (rawOpaqueBufferSize <= 0) {
1133 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1134 return BAD_VALUE;
1135 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001136 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001137 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001138 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001139 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001140 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001141 } else if (isShared) {
1142 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1143 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001144 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001145 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001146 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001147 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001148 newStream = new Camera3OutputStream(mNextStreamId,
1149 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001150 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001151 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001152 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001154 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001155 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001156 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001157 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001158 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001159 }
Emilian Peev40ead602017-09-26 15:46:36 +01001160
1161 size_t consumerCount = consumers.size();
1162 for (size_t i = 0; i < consumerCount; i++) {
1163 int id = newStream->getSurfaceId(consumers[i]);
1164 if (id < 0) {
1165 SET_ERR_L("Invalid surface id");
1166 return BAD_VALUE;
1167 }
1168 if (surfaceIds != nullptr) {
1169 surfaceIds->push_back(id);
1170 }
1171 }
1172
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174
Emilian Peev08dd2452017-04-06 16:55:14 +01001175 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001176
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001177 newStream->setImageDumpMask(mImageDumpMask);
1178
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179 res = mOutputStreams.add(mNextStreamId, newStream);
1180 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001181 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182 return res;
1183 }
1184
Shuzhen Wang316781a2020-08-18 18:11:01 -07001185 mSessionStatsBuilder.addStream(mNextStreamId);
1186
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001188 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189
1190 // Continue captures if active at start
1191 if (wasActive) {
1192 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001193 // Reuse current operating mode and session parameters for new stream config
1194 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001196 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1197 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 return res;
1199 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 }
Austin Borger0fb3ad92023-06-01 16:51:35 -07001202 ALOGV("Camera %s: Created new stream", mId.c_str());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001204}
1205
Emilian Peev710c1422017-08-30 11:19:38 +01001206status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001208 if (nullptr == streamInfo) {
1209 return BAD_VALUE;
1210 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 switch (mStatus) {
1215 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001219 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 case STATUS_UNCONFIGURED:
1222 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 case STATUS_ACTIVE:
1224 // OK
1225 break;
1226 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001227 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 return INVALID_OPERATION;
1229 }
1230
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001231 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1232 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001234 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 }
1236
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001237 streamInfo->width = stream->getWidth();
1238 streamInfo->height = stream->getHeight();
1239 streamInfo->format = stream->getFormat();
1240 streamInfo->dataSpace = stream->getDataSpace();
1241 streamInfo->formatOverridden = stream->isFormatOverridden();
1242 streamInfo->originalFormat = stream->getOriginalFormat();
1243 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1244 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001245 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247}
1248
1249status_t Camera3Device::setStreamTransform(int id,
1250 int transform) {
1251 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 switch (mStatus) {
1256 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 case STATUS_UNCONFIGURED:
1263 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 case STATUS_ACTIVE:
1265 // OK
1266 break;
1267 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001268 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 return INVALID_OPERATION;
1270 }
1271
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001272 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1273 if (stream == nullptr) {
1274 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return BAD_VALUE;
1276 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001277 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
1280status_t Camera3Device::deleteStream(int id) {
1281 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 Mutex::Autolock l(mLock);
1284 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001285
Austin Borger0fb3ad92023-06-01 16:51:35 -07001286 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.c_str(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001287
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 // CameraDevice semantics require device to already be idle before
1289 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 if (mStatus == STATUS_ACTIVE) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07001291 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.c_str());
Igor Murashkin52827132013-05-13 14:53:44 -07001292 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 }
1294
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001295 if (mStatus == STATUS_ERROR) {
1296 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
Austin Borger0fb3ad92023-06-01 16:51:35 -07001297 __FUNCTION__, mId.c_str());
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001298 return -EBUSY;
1299 }
1300
Igor Murashkin2fba5842013-04-22 14:03:54 -07001301 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001302 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001303 if (mInputStream != NULL && id == mInputStream->getId()) {
1304 deletedStream = mInputStream;
1305 mInputStream.clear();
1306 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001307 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001308 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 return BAD_VALUE;
1310 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001311 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001312 }
1313
1314 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001315 if (stream != nullptr) {
1316 deletedStream = stream;
1317 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 }
1319
1320 // Free up the stream endpoint so that it can be used by some other stream
1321 res = deletedStream->disconnect();
1322 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001323 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001324 // fall through since we want to still list the stream as deleted.
1325 }
1326 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001327 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001328
1329 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001330}
1331
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001332status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001333 ATRACE_CALL();
1334 ALOGV("%s: E", __FUNCTION__);
1335
1336 Mutex::Autolock il(mInterfaceLock);
1337 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001338
Emilian Peev811d2952018-05-25 11:08:40 +01001339 // In case the client doesn't include any session parameter, try a
1340 // speculative configuration using the values from the last cached
1341 // default request.
1342 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001343 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001344 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1345 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1346 mLastTemplateId);
1347 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1348 operatingMode);
1349 }
1350
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001351 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1352}
1353
1354status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1355 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001356 //Filter out any incoming session parameters
1357 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001358 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1359 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001360 CameraMetadata filteredParams(availableSessionKeys.count);
1361 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1362 filteredParams.getAndLock());
1363 set_camera_metadata_vendor_id(meta, mVendorTagId);
1364 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001365 if (availableSessionKeys.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07001366 bool rotateAndCropSessionKey = false;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001367 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1368 camera_metadata_ro_entry entry = params.find(
1369 availableSessionKeys.data.i32[i]);
1370 if (entry.count > 0) {
1371 filteredParams.update(entry);
1372 }
Emilian Peevb9f83812023-03-17 17:13:07 -07001373 if (ANDROID_SCALER_ROTATE_AND_CROP == availableSessionKeys.data.i32[i]) {
1374 rotateAndCropSessionKey = true;
1375 }
1376 }
1377
1378 if (rotateAndCropSessionKey) {
1379 sp<CaptureRequest> request = new CaptureRequest();
1380 PhysicalCameraSettings settingsList;
1381 settingsList.metadata = filteredParams;
1382 request->mSettingsList.push_back(settingsList);
1383
1384 auto rotateAndCropEntry = filteredParams.find(ANDROID_SCALER_ROTATE_AND_CROP);
1385 if (rotateAndCropEntry.count > 0 &&
1386 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1387 request->mRotateAndCropAuto = true;
1388 } else {
1389 request->mRotateAndCropAuto = false;
1390 }
1391
1392 overrideAutoRotateAndCrop(request, mOverrideToPortrait, mRotateAndCropOverride);
1393 filteredParams = request->mSettingsList.begin()->metadata;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001394 }
1395 }
1396
1397 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001398}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001399
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001400status_t Camera3Device::getInputBufferProducer(
1401 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001402 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001403 Mutex::Autolock il(mInterfaceLock);
1404 Mutex::Autolock l(mLock);
1405
1406 if (producer == NULL) {
1407 return BAD_VALUE;
1408 } else if (mInputStream == NULL) {
1409 return INVALID_OPERATION;
1410 }
1411
1412 return mInputStream->getInputBufferProducer(producer);
1413}
1414
Emilian Peevf4816702020-04-03 15:44:51 -07001415status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001416 CameraMetadata *request) {
1417 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001418 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001419
Emilian Peevf4816702020-04-03 15:44:51 -07001420 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001421 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001422 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001423 return BAD_VALUE;
1424 }
1425
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001426 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001427
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001428 {
1429 Mutex::Autolock l(mLock);
1430 switch (mStatus) {
1431 case STATUS_ERROR:
1432 CLOGE("Device has encountered a serious error");
1433 return INVALID_OPERATION;
1434 case STATUS_UNINITIALIZED:
1435 CLOGE("Device is not initialized!");
1436 return INVALID_OPERATION;
1437 case STATUS_UNCONFIGURED:
1438 case STATUS_CONFIGURED:
1439 case STATUS_ACTIVE:
1440 // OK
1441 break;
1442 default:
1443 SET_ERR_L("Unexpected status: %d", mStatus);
1444 return INVALID_OPERATION;
1445 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001446
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001447 if (!mRequestTemplateCache[templateId].isEmpty()) {
1448 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001449 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001450 return OK;
1451 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001452 }
1453
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001454 camera_metadata_t *rawRequest;
1455 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001456 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001457
1458 {
1459 Mutex::Autolock l(mLock);
1460 if (res == BAD_VALUE) {
1461 ALOGI("%s: template %d is not supported on this camera device",
1462 __FUNCTION__, templateId);
1463 return res;
1464 } else if (res != OK) {
1465 CLOGE("Unable to construct request template %d: %s (%d)",
1466 templateId, strerror(-res), res);
1467 return res;
1468 }
1469
1470 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1471 mRequestTemplateCache[templateId].acquire(rawRequest);
1472
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001473 // Override the template request with zoomRatioMapper
Austin Borger0fb3ad92023-06-01 16:51:35 -07001474 res = mZoomRatioMappers[mId].initZoomRatioInTemplate(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001475 &mRequestTemplateCache[templateId]);
1476 if (res != OK) {
1477 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1478 templateId, strerror(-res), res);
1479 return res;
1480 }
1481
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001482 // Fill in JPEG_QUALITY if not available
1483 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1484 static const uint8_t kDefaultJpegQuality = 95;
1485 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1486 &kDefaultJpegQuality, 1);
1487 }
1488
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001490 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001491 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001492 return OK;
1493}
1494
1495status_t Camera3Device::waitUntilDrained() {
1496 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001498 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001500
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001501 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001502}
1503
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001504status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 switch (mStatus) {
1506 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001507 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 ALOGV("%s: Already idle", __FUNCTION__);
1509 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001510 case STATUS_CONFIGURED:
1511 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 case STATUS_ERROR:
1513 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 break;
1516 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001517 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 return INVALID_OPERATION;
1519 }
Austin Borger0fb3ad92023-06-01 16:51:35 -07001520 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.c_str(),
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001521 maxExpectedDuration);
1522 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001523 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001524 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001525 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1526 res);
1527 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 return res;
1529}
1530
Ruben Brunk183f0562015-08-12 12:55:02 -07001531void Camera3Device::internalUpdateStatusLocked(Status status) {
1532 mStatus = status;
1533 mRecentStatusUpdates.add(mStatus);
1534 mStatusChanged.broadcast();
1535}
1536
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001538status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001539 if (mRequestThread.get() != nullptr) {
1540 mRequestThread->setPaused(true);
1541 } else {
1542 return NO_INIT;
1543 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544
Austin Borger0fb3ad92023-06-01 16:51:35 -07001545 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.c_str(),
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001546 maxExpectedDuration);
1547 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001548 if (res != OK) {
1549 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001550 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 }
1552
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 return res;
1554}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556// Resume after internalPauseAndWaitLocked
1557status_t Camera3Device::internalResumeLocked() {
1558 status_t res;
1559
1560 mRequestThread->setPaused(false);
1561
Austin Borger0fb3ad92023-06-01 16:51:35 -07001562 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.c_str(),
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001563 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1565 if (res != OK) {
1566 SET_ERR_L("Can't transition to active in %f seconds!",
1567 kActiveTimeout/1e9);
1568 }
1569 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571}
1572
Ruben Brunk183f0562015-08-12 12:55:02 -07001573status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001575
1576 size_t startIndex = 0;
1577 if (mStatusWaiters == 0) {
1578 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1579 // this status list
1580 mRecentStatusUpdates.clear();
1581 } else {
1582 // If other threads are waiting on updates to this status list, set the position of the
1583 // first element that this list will check rather than clearing the list.
1584 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 }
1586
Ruben Brunk183f0562015-08-12 12:55:02 -07001587 mStatusWaiters++;
1588
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001589 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001590 if (!active && mUseHalBufManager) {
1591 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001592 if (mStatus == STATUS_ACTIVE) {
1593 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001594 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001595 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001596 mRequestBufferSM.onWaitUntilIdle();
1597 }
1598
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001599 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001600 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001601 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001602 if (active == (mStatus == STATUS_ACTIVE)) {
1603 // Desired state is current
1604 break;
1605 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001606
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001607 nsecs_t timeElapsed = systemTime() - startTime;
1608 nsecs_t timeToWait = timeout - timeElapsed;
1609 if (timeToWait <= 0) {
1610 // Thread woke up spuriously but has timed out since.
1611 // Force out of loop with TIMED_OUT result.
1612 res = TIMED_OUT;
1613 break;
1614 }
1615 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 if (res != OK) break;
1617
Ruben Brunk183f0562015-08-12 12:55:02 -07001618 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1619 // transitions.
1620 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1621 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1622 __FUNCTION__);
1623
1624 // Encountered desired state since we began waiting
1625 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001626 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1627 stateSeen = true;
1628 break;
1629 }
1630 }
1631 } while (!stateSeen);
1632
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001633 if (signalPipelineDrain) {
1634 mRequestThread->resetPipelineDrain();
1635 }
1636
Ruben Brunk183f0562015-08-12 12:55:02 -07001637 mStatusWaiters--;
1638
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 return res;
1640}
1641
1642
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001643status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001644 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001645 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001647 if (listener != NULL && mListener != NULL) {
1648 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1649 }
1650 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001651 mRequestThread->setNotificationListener(listener);
1652 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001653
1654 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001655}
1656
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001657bool Camera3Device::willNotify3A() {
1658 return false;
1659}
1660
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001662 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001663 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001665 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001666 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1667 if (st == std::cv_status::timeout) {
1668 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001669 }
1670 }
1671 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672}
1673
Jianing Weicb0652e2014-03-12 18:29:36 -07001674status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001676 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 if (mResultQueue.empty()) {
1679 return NOT_ENOUGH_DATA;
1680 }
1681
Jianing Weicb0652e2014-03-12 18:29:36 -07001682 if (frame == NULL) {
1683 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1684 return BAD_VALUE;
1685 }
1686
1687 CaptureResult &result = *(mResultQueue.begin());
1688 frame->mResultExtras = result.mResultExtras;
1689 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001690 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001691 mResultQueue.erase(mResultQueue.begin());
1692
1693 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694}
1695
1696status_t Camera3Device::triggerAutofocus(uint32_t id) {
1697 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001698 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001699
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001700 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1701 // Mix-in this trigger into the next request and only the next request.
1702 RequestTrigger trigger[] = {
1703 {
1704 ANDROID_CONTROL_AF_TRIGGER,
1705 ANDROID_CONTROL_AF_TRIGGER_START
1706 },
1707 {
1708 ANDROID_CONTROL_AF_TRIGGER_ID,
1709 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001710 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001711 };
1712
1713 return mRequestThread->queueTrigger(trigger,
1714 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001715}
1716
1717status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1718 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001719 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001721 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1722 // Mix-in this trigger into the next request and only the next request.
1723 RequestTrigger trigger[] = {
1724 {
1725 ANDROID_CONTROL_AF_TRIGGER,
1726 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1727 },
1728 {
1729 ANDROID_CONTROL_AF_TRIGGER_ID,
1730 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001731 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001732 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001734 return mRequestThread->queueTrigger(trigger,
1735 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001736}
1737
1738status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1739 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001740 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001742 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1743 // Mix-in this trigger into the next request and only the next request.
1744 RequestTrigger trigger[] = {
1745 {
1746 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1747 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1748 },
1749 {
1750 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1751 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001752 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001753 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001754
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001755 return mRequestThread->queueTrigger(trigger,
1756 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757}
1758
Jianing Weicb0652e2014-03-12 18:29:36 -07001759status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001760 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -07001761 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.c_str());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001762 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001763
Zhijun He7ef20392014-04-21 16:04:17 -07001764 {
1765 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001766
1767 // b/116514106 "disconnect()" can get called twice for the same device. The
1768 // camera device will not be initialized during the second run.
1769 if (mStatus == STATUS_UNINITIALIZED) {
1770 return OK;
1771 }
1772
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001773 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001774
1775 // Stop session and stream counter
1776 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001777 }
1778
Ravneet98ffa752022-03-02 07:22:46 +00001779 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal72c96652022-06-29 01:34:01 +00001780 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneet98ffa752022-03-02 07:22:46 +00001781 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1782 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1783
1784 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001785}
1786
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001787status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001788 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1789}
1790
1791status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001792 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -07001793 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.c_str(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001794 Mutex::Autolock il(mInterfaceLock);
1795 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001796
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001797 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1798 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001799 CLOGE("Stream %d does not exist", streamId);
1800 return BAD_VALUE;
1801 }
1802
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001803 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001804 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001805 return BAD_VALUE;
1806 }
1807
1808 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001809 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001810 return BAD_VALUE;
1811 }
1812
Ruben Brunkc78ac262015-08-13 17:58:46 -07001813 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001814}
1815
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001816status_t Camera3Device::tearDown(int streamId) {
1817 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -07001818 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.c_str(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001819 Mutex::Autolock il(mInterfaceLock);
1820 Mutex::Autolock l(mLock);
1821
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001822 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1823 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001824 CLOGE("Stream %d does not exist", streamId);
1825 return BAD_VALUE;
1826 }
1827
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001828 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1829 CLOGE("Stream %d is a target of a in-progress request", streamId);
1830 return BAD_VALUE;
1831 }
1832
1833 return stream->tearDown();
1834}
1835
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001836status_t Camera3Device::addBufferListenerForStream(int streamId,
1837 wp<Camera3StreamBufferListener> listener) {
1838 ATRACE_CALL();
Austin Borger0fb3ad92023-06-01 16:51:35 -07001839 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.c_str(),
1840 streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001841 Mutex::Autolock il(mInterfaceLock);
1842 Mutex::Autolock l(mLock);
1843
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001844 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1845 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001846 CLOGE("Stream %d does not exist", streamId);
1847 return BAD_VALUE;
1848 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001849 stream->addBufferListener(listener);
1850
1851 return OK;
1852}
1853
Austin Borger4a870a32022-02-25 01:48:41 +00001854float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1855 camera_metadata_entry minDurations =
1856 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1857 for (size_t i = 0; i < minDurations.count; i += 4) {
1858 if (minDurations.data.i64[i] == stream->getFormat()
1859 && minDurations.data.i64[i+1] == stream->getWidth()
1860 && minDurations.data.i64[i+2] == stream->getHeight()) {
1861 int64_t minFrameDuration = minDurations.data.i64[i+3];
1862 return 1e9f / minFrameDuration;
1863 }
1864 }
1865 return 0.0f;
1866}
1867
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 * Methods called by subclasses
1870 */
1871
1872void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001873 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001874 std::vector<int> streamIds;
1875 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001876 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 {
1879 // Need mLock to safely update state and synchronize to current
1880 // state of methods in flight.
1881 Mutex::Autolock l(mLock);
1882 // We can get various system-idle notices from the status tracker
1883 // while starting up. Only care about them if we've actually sent
1884 // in some requests recently.
1885 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1886 return;
1887 }
Austin Borger0fb3ad92023-06-01 16:51:35 -07001888 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.c_str(),
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001889 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001890 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891
1892 // Skip notifying listener if we're doing some user-transparent
1893 // state changes
1894 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001895
Austin Borger4a870a32022-02-25 01:48:41 +00001896 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1897 auto stream = mOutputStreams[i];
1898 if (stream.get() == nullptr) continue;
1899
1900 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1901 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1902
1903 // Populate stream statistics in case of Idle
1904 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001905 streamIds.push_back(stream->getId());
1906 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1907 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001908 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001909 if (camera3Stream != nullptr) {
1910 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001911 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001912 }
1913 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001914 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001915 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001916 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001917 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001918 }
1919 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001920 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001921
1922 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001923 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001924 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001925 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001927 status_t res = OK;
1928 if (listener != nullptr) {
1929 if (idle) {
1930 // Get session stats from the builder, and notify the listener.
1931 int64_t requestCount, resultErrorCount;
1932 bool deviceError;
1933 std::map<int, StreamStats> streamStatsMap;
1934 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1935 &deviceError, &streamStatsMap);
1936 for (size_t i = 0; i < streamIds.size(); i++) {
1937 int streamId = streamIds[i];
1938 auto stats = streamStatsMap.find(streamId);
1939 if (stats != streamStatsMap.end()) {
1940 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1941 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1942 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1943 streamStats[i].mHistogramType =
1944 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1945 streamStats[i].mHistogramBins.assign(
1946 stats->second.mCaptureLatencyBins.begin(),
1947 stats->second.mCaptureLatencyBins.end());
1948 streamStats[i].mHistogramCounts.assign(
1949 stats->second.mCaptureLatencyHistogram.begin(),
1950 stats->second.mCaptureLatencyHistogram.end());
1951 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001952 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001953 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1954 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001955 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001956 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001957 }
1958 if (res != OK) {
1959 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1960 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001961 }
1962}
1963
Shuzhen Wang758c2152017-01-10 18:26:18 -08001964status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001965 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001966 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001967 ALOGV("%s: Camera %s: set consumer surface for stream %d",
Austin Borger0fb3ad92023-06-01 16:51:35 -07001968 __FUNCTION__, mId.c_str(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001969
1970 if (surfaceIds == nullptr) {
1971 return BAD_VALUE;
1972 }
1973
Zhijun He5d677d12016-05-29 16:52:39 -07001974 Mutex::Autolock il(mInterfaceLock);
1975 Mutex::Autolock l(mLock);
1976
Shuzhen Wang758c2152017-01-10 18:26:18 -08001977 if (consumers.size() == 0) {
1978 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001979 return BAD_VALUE;
1980 }
1981
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001982 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1983 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001984 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001985 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001986 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001987
1988 // isConsumerConfigurationDeferred will be off after setConsumers
1989 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001990 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001991 if (res != OK) {
1992 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1993 return res;
1994 }
1995
Emilian Peev40ead602017-09-26 15:46:36 +01001996 for (auto &consumer : consumers) {
1997 int id = stream->getSurfaceId(consumer);
1998 if (id < 0) {
1999 CLOGE("Invalid surface id!");
2000 return BAD_VALUE;
2001 }
2002 surfaceIds->push_back(id);
2003 }
2004
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002005 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002006 if (!stream->isConfiguring()) {
2007 CLOGE("Stream %d was already fully configured.", streamId);
2008 return INVALID_OPERATION;
2009 }
Zhijun He5d677d12016-05-29 16:52:39 -07002010
Shuzhen Wang0129d522016-10-30 22:43:41 -07002011 res = stream->finishConfiguration();
2012 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002013 // If finishConfiguration fails due to abandoned surface, do not set
2014 // device to error state.
2015 bool isSurfaceAbandoned =
2016 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2017 if (!isSurfaceAbandoned) {
2018 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2019 stream->getId(), strerror(-res), res);
2020 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002021 return res;
2022 }
Zhijun He5d677d12016-05-29 16:52:39 -07002023 }
2024
2025 return OK;
2026}
2027
Emilian Peev40ead602017-09-26 15:46:36 +01002028status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2029 const std::vector<OutputStreamInfo> &outputInfo,
2030 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2031 Mutex::Autolock il(mInterfaceLock);
2032 Mutex::Autolock l(mLock);
2033
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002034 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2035 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002036 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002037 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002038 }
2039
2040 for (const auto &it : removedSurfaceIds) {
2041 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2042 CLOGE("Shared surface still part of a pending request!");
2043 return -EBUSY;
2044 }
2045 }
2046
Emilian Peev40ead602017-09-26 15:46:36 +01002047 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2048 if (res != OK) {
2049 CLOGE("Stream %d failed to update stream (error %d %s) ",
2050 streamId, res, strerror(-res));
2051 if (res == UNKNOWN_ERROR) {
2052 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2053 __FUNCTION__);
2054 }
2055 return res;
2056 }
2057
2058 return res;
2059}
2060
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002061status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2062 Mutex::Autolock il(mInterfaceLock);
2063 Mutex::Autolock l(mLock);
2064
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002065 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2066 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002067 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2068 return BAD_VALUE;
2069 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002070
2071 if (dropping) {
2072 mSessionStatsBuilder.stopCounter(streamId);
2073 } else {
2074 mSessionStatsBuilder.startCounter(streamId);
2075 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002076 return stream->dropBuffers(dropping);
2077}
2078
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002079/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 * Camera3Device private methods
2081 */
2082
2083sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002084 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002085 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002086
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002087 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002088 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002089
2090 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002091 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092 if (inputStreams.count > 0) {
2093 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002094 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002095 CLOGE("Request references unknown input stream %d",
2096 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097 return NULL;
2098 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002101 SET_ERR_L("%s: input stream %d is not configured!",
2102 __FUNCTION__, mInputStream->getId());
2103 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002105 // Check if stream prepare is blocking requests.
2106 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002107 CLOGE("Request references an input stream that's being prepared!");
2108 return NULL;
2109 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110
2111 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002112 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 }
2114
2115 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002116 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002118 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119 return NULL;
2120 }
2121
2122 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002123 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2124 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002125 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002126 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002127 return NULL;
2128 }
Zhijun He5d677d12016-05-29 16:52:39 -07002129 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002130 auto iter = surfaceMap.find(streams.data.i32[i]);
2131 if (iter != surfaceMap.end()) {
2132 const std::vector<size_t>& surfaces = iter->second;
2133 for (const auto& surface : surfaces) {
2134 if (stream->isConsumerConfigurationDeferred(surface)) {
2135 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2136 "due to deferred consumer", stream->getId(), surface);
2137 return NULL;
2138 }
2139 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002140 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002141 }
2142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002144 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2145 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002147 // Check if stream prepare is blocking requests.
2148 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002149 CLOGE("Request references an output stream that's being prepared!");
2150 return NULL;
2151 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002152
2153 newRequest->mOutputStreams.push(stream);
2154 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002155 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002156 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002157
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002158 auto rotateAndCropEntry =
2159 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2160 if (rotateAndCropEntry.count > 0 &&
2161 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2162 newRequest->mRotateAndCropAuto = true;
2163 } else {
2164 newRequest->mRotateAndCropAuto = false;
2165 }
2166
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002167 auto zoomRatioEntry =
2168 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2169 if (zoomRatioEntry.count > 0 &&
2170 zoomRatioEntry.data.f[0] == 1.0f) {
2171 newRequest->mZoomRatioIs1x = true;
2172 } else {
2173 newRequest->mZoomRatioIs1x = false;
2174 }
2175
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002176 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002177 for (auto& settings : newRequest->mSettingsList) {
2178 auto testPatternModeEntry =
2179 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2180 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2181 testPatternModeEntry.data.i32[0] :
2182 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002183
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002184 auto testPatternDataEntry =
2185 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2186 if (testPatternDataEntry.count >= 4) {
2187 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2188 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2189 } else {
2190 settings.mOriginalTestPatternData[0] = 0;
2191 settings.mOriginalTestPatternData[1] = 0;
2192 settings.mOriginalTestPatternData[2] = 0;
2193 settings.mOriginalTestPatternData[3] = 0;
2194 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002195 }
2196 }
2197
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002198 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002199}
2200
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002201void Camera3Device::cancelStreamsConfigurationLocked() {
2202 int res = OK;
2203 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2204 res = mInputStream->cancelConfiguration();
2205 if (res != OK) {
2206 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2207 mInputStream->getId(), strerror(-res), res);
2208 }
2209 }
2210
2211 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002212 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002213 if (outputStream->isConfiguring()) {
2214 res = outputStream->cancelConfiguration();
2215 if (res != OK) {
2216 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2217 outputStream->getId(), strerror(-res), res);
2218 }
2219 }
2220 }
2221
2222 // Return state to that at start of call, so that future configures
2223 // properly clean things up
2224 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2225 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002226
2227 res = mPreparerThread->resume();
2228 if (res != OK) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07002229 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.c_str());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002230 }
2231}
2232
Emilian Peev0d0191e2020-04-21 17:01:18 -07002233bool Camera3Device::checkAbandonedStreamsLocked() {
2234 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2235 return true;
2236 }
2237
2238 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2239 auto stream = mOutputStreams[i];
2240 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2241 return true;
2242 }
2243 }
2244
2245 return false;
2246}
2247
Emilian Peev3bead5f2020-05-28 17:29:08 -07002248bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002249 ATRACE_CALL();
2250 bool ret = false;
2251
Shuzhen Wang316781a2020-08-18 18:11:01 -07002252 nsecs_t startTime = systemTime();
2253
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002254 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002255 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2256
2257 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002258 if (checkAbandonedStreamsLocked()) {
2259 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2260 __FUNCTION__);
2261 return true;
2262 }
2263
Emilian Peev3bead5f2020-05-28 17:29:08 -07002264 status_t rc = NO_ERROR;
2265 bool markClientActive = false;
2266 if (mStatus == STATUS_ACTIVE) {
2267 markClientActive = true;
2268 mPauseStateNotify = true;
2269 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2270
2271 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2272 }
2273
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002274 if (rc == NO_ERROR) {
2275 mNeedConfig = true;
2276 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2277 if (rc == NO_ERROR) {
2278 ret = true;
2279 mPauseStateNotify = false;
2280 //Moving to active state while holding 'mLock' is important.
2281 //There could be pending calls to 'create-/deleteStream' which
2282 //will trigger another stream configuration while the already
2283 //present streams end up with outstanding buffers that will
2284 //not get drained.
2285 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002286 } else if (rc == DEAD_OBJECT) {
2287 // DEAD_OBJECT can be returned if either the consumer surface is
2288 // abandoned, or the HAL has died.
2289 // - If the HAL has died, configureStreamsLocked call will set
2290 // device to error state,
2291 // - If surface is abandoned, we should not set device to error
2292 // state.
2293 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002294 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002295 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002296 }
2297 } else {
2298 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2299 }
2300
Shuzhen Wang316781a2020-08-18 18:11:01 -07002301 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2302 ns2ms(systemTime() - startTime));
2303
Emilian Peev3bead5f2020-05-28 17:29:08 -07002304 if (markClientActive) {
2305 mStatusTracker->markComponentActive(clientStatusId);
2306 }
2307
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002308 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002309}
2310
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002311status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002312 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 ATRACE_CALL();
2314 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002315
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002316 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002317 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318 return INVALID_OPERATION;
2319 }
2320
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002321 if (operatingMode < 0) {
2322 CLOGE("Invalid operating mode: %d", operatingMode);
2323 return BAD_VALUE;
2324 }
2325
2326 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002327 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002328
2329 if (mOperatingMode != operatingMode) {
2330 mNeedConfig = true;
2331 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2332 mOperatingMode = operatingMode;
2333 }
2334
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002335 // Reset min expected duration when session is reconfigured.
2336 mMinExpectedDuration = 0;
2337
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002338 // In case called from configureStreams, abort queued input buffers not belonging to
2339 // any pending requests.
2340 if (mInputStream != NULL && notifyRequestThread) {
2341 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002342 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002343 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002344 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002345 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002346 if (res != OK) {
2347 // Exhausted acquiring all input buffers.
2348 break;
2349 }
2350
Emilian Peevf4816702020-04-03 15:44:51 -07002351 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002352 res = mInputStream->returnInputBuffer(inputBuffer);
2353 if (res != OK) {
2354 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2355 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2356 }
2357 }
2358 }
2359
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002360 if (!mNeedConfig) {
2361 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2362 return OK;
2363 }
2364
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002365 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002366 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002367 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2368 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002369 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002370 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002371 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002372 }
2373
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08002374 // Override stream use case based on "adb shell command"
2375 overrideStreamUseCaseLocked();
2376
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377 // Start configuring the streams
Austin Borger0fb3ad92023-06-01 16:51:35 -07002378 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.c_str());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002380 mPreparerThread->pause();
2381
Emilian Peevf4816702020-04-03 15:44:51 -07002382 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002383 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002385 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386
Emilian Peevf4816702020-04-03 15:44:51 -07002387 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002389 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391
2392 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002393 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 inputStream = mInputStream->startConfiguration();
2395 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002396 CLOGE("Can't start input stream configuration");
2397 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 return INVALID_OPERATION;
2399 }
2400 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002401
2402 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002403 }
2404
Shuzhen Wang99080502021-03-07 21:08:20 -08002405 mGroupIdPhysicalCameraMap.clear();
Emilian Peevb9f83812023-03-17 17:13:07 -07002406 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002408
2409 // Don't configure bidi streams twice, nor add them twice to the list
2410 if (mOutputStreams[i].get() ==
2411 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2412
2413 config.num_streams--;
2414 continue;
2415 }
2416
Emilian Peevf4816702020-04-03 15:44:51 -07002417 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002418 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002419 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002420 CLOGE("Can't start output stream configuration");
2421 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422 return INVALID_OPERATION;
2423 }
2424 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002425
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002426 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002427 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2428 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002429 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2430 bufferSizes[k] = static_cast<uint32_t>(
Austin Borger0fb3ad92023-06-01 16:51:35 -07002431 getJpegBufferSize(infoPhysical(outputStream->physical_camera_id),
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002432 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002433 } else if (outputStream->data_space ==
2434 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2435 bufferSizes[k] = outputStream->width * outputStream->height;
2436 } else {
2437 ALOGW("%s: Blob dataSpace %d not supported",
2438 __FUNCTION__, outputStream->data_space);
2439 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002440 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002441
2442 if (mOutputStreams[i]->isMultiResolution()) {
2443 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
Austin Borger0fb3ad92023-06-01 16:51:35 -07002444 const std::string &physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08002445 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2446 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002447
2448 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevb9f83812023-03-17 17:13:07 -07002449 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002450 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002451 }
2452
2453 config.streams = streams.editArray();
2454
2455 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002456 // max_buffers, usage, and priv fields, as well as data_space and format
2457 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002458
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002459 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002460 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002461 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002462
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002463 if (res == BAD_VALUE) {
2464 // HAL rejected this set of streams as unsupported, clean up config
2465 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002466 CLOGE("Set of requested inputs/outputs not supported by HAL");
2467 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002468 return BAD_VALUE;
2469 } else if (res != OK) {
2470 // Some other kind of error from configure_streams - this is not
2471 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002472 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2473 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002474 return res;
2475 }
2476
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002477 // Finish all stream configuration immediately.
2478 // TODO: Try to relax this later back to lazy completion, which should be
2479 // faster
2480
Igor Murashkin073f8572013-05-02 14:59:28 -07002481 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002482 bool streamReConfigured = false;
2483 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002484 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002485 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002486 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002487 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002488 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2489 return DEAD_OBJECT;
2490 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002491 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002492 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002493 if (streamReConfigured) {
2494 mInterface->onStreamReConfigured(mInputStream->getId());
2495 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002496 }
2497
2498 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002499 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002500 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002501 bool streamReConfigured = false;
2502 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002503 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002505 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002506 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002507 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2508 return DEAD_OBJECT;
2509 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002510 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002511 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002512 if (streamReConfigured) {
2513 mInterface->onStreamReConfigured(outputStream->getId());
2514 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002515 }
2516 }
2517
Emilian Peevb9f83812023-03-17 17:13:07 -07002518 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520 // Request thread needs to know to avoid using repeat-last-settings protocol
2521 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002522 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002523 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2524 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002525 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526
Zhijun He90f7c372016-08-16 16:19:43 -07002527 char value[PROPERTY_VALUE_MAX];
2528 property_get("camera.fifo.disable", value, "0");
2529 int32_t disableFifo = atoi(value);
2530 if (disableFifo != 1) {
2531 // Boost priority of request thread to SCHED_FIFO.
2532 pid_t requestThreadTid = mRequestThread->getTid();
2533 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002534 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002535 if (res != OK) {
2536 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2537 strerror(-res), res);
2538 } else {
2539 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2540 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002541 }
2542
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002543 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002544 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2545 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2546 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2547 sessionParams.unlock(newSessionParams);
2548 mSessionParams.unlock(currentSessionParams);
2549 if (updateSessionParams) {
2550 mSessionParams = sessionParams;
2551 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002553 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002554
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002556 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002557
Austin Borger0fb3ad92023-06-01 16:51:35 -07002558 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.c_str());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002559
Zhijun He0a210512014-07-24 13:45:15 -07002560 // tear down the deleted streams after configure streams.
2561 mDeletedStreams.clear();
2562
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002563 auto rc = mPreparerThread->resume();
2564 if (rc != OK) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07002565 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.c_str());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002566 return rc;
2567 }
2568
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002569 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002570 mRequestBufferSM.onStreamsConfigured();
2571 }
2572
Cliff Wu3b268182021-07-06 15:44:43 +08002573 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002574 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002575 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002576 // configure the injection streams.
2577 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002578 ALOGD("%s: Injection camera %s: Start to configure streams.",
Austin Borger0fb3ad92023-06-01 16:51:35 -07002579 __FUNCTION__, mInjectionMethods->getInjectedCamId().c_str());
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002580 res = mInjectionMethods->injectCamera(config, bufferSizes);
2581 if (res != OK) {
2582 ALOGE("Can't finish inject camera process!");
2583 return res;
2584 }
Cliff Wu3b268182021-07-06 15:44:43 +08002585 } else {
2586 // First run configureStreamsLocked() and then call injectCamera() case:
2587 // If the stream configuration has been completed and camera deive is active, but the
2588 // injection camera has not been injected yet, we need to store the stream configuration of
2589 // the internal camera (because the stream configuration of the injection camera is based
2590 // on the internal camera). When injecting occurs later, this configuration can be used by
2591 // the injection camera.
2592 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2593 " injection camera has not been injected yet.", __FUNCTION__);
2594 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002595 }
2596
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002598}
2599
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002600status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002601 ATRACE_CALL();
2602 status_t res;
2603
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002604 if (mFakeStreamId != NO_STREAM) {
2605 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002606 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002607 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Austin Borger0fb3ad92023-06-01 16:51:35 -07002608 __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002609 return INVALID_OPERATION;
2610 }
2611
Austin Borger0fb3ad92023-06-01 16:51:35 -07002612 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002613
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002614 sp<Camera3OutputStreamInterface> fakeStream =
2615 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002619 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002620 return res;
2621 }
2622
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002623 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 mNextStreamId++;
2625
2626 return OK;
2627}
2628
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002629status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002630 ATRACE_CALL();
2631 status_t res;
2632
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002633 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002634 if (mOutputStreams.size() == 1) return OK;
2635
Austin Borger0fb3ad92023-06-01 16:51:35 -07002636 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002637
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002638 // Ok, have a fake stream and there's at least one other output stream,
2639 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002640
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002642 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002643 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002644 return INVALID_OPERATION;
2645 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647
2648 // Free up the stream endpoint so that it can be used by some other stream
2649 res = deletedStream->disconnect();
2650 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 // fall through since we want to still list the stream as deleted.
2653 }
2654 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002655 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002656
2657 return res;
2658}
2659
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002660void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002661 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002662 Mutex::Autolock l(mLock);
2663 va_list args;
2664 va_start(args, fmt);
2665
2666 setErrorStateLockedV(fmt, args);
2667
2668 va_end(args);
2669}
2670
2671void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002672 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002673 Mutex::Autolock l(mLock);
2674 setErrorStateLockedV(fmt, args);
2675}
2676
2677void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2678 va_list args;
2679 va_start(args, fmt);
2680
2681 setErrorStateLockedV(fmt, args);
2682
2683 va_end(args);
2684}
2685
2686void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002687 // Print out all error messages to log
Austin Borger0fb3ad92023-06-01 16:51:35 -07002688 std::string errorCause;
2689 base::StringAppendV(&errorCause, fmt, args);
2690 ALOGE("Camera %s: %s", mId.c_str(), errorCause.c_str());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002691
2692 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002693 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002694
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002695 mErrorCause = errorCause;
2696
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002697 if (mRequestThread != nullptr) {
2698 mRequestThread->setPaused(true);
2699 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002700 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002701
2702 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002703 sp<NotificationListener> listener = mListener.promote();
2704 if (listener != NULL) {
2705 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002706 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002707 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002708 }
2709
2710 // Save stack trace. View by dumping it later.
2711 CameraTraces::saveTrace();
2712 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002713}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714
2715/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002716 * In-flight request management
2717 */
2718
Jianing Weicb0652e2014-03-12 18:29:36 -07002719status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002720 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002721 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Austin Borger0fb3ad92023-06-01 16:51:35 -07002722 bool isFixedFps, const std::set<std::set<std::string>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002723 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2724 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002725 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002726 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002727 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002728
2729 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002730 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002731 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002732 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2733 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002734 if (res < 0) return res;
2735
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002736 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002737 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2738 // avoid a deadlock during reprocess requests.
2739 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002740 if (mStatusTracker != nullptr) {
2741 mStatusTracker->markComponentActive(mInFlightStatusId);
2742 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002743 }
2744
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002745 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002746 return OK;
2747}
2748
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002749void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002750 // Indicate idle inFlightMap to the status tracker
2751 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002752 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002753 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2754 // avoid a deadlock during reprocess requests.
2755 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002756 if (mStatusTracker != nullptr) {
2757 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2758 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002759 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002760 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002761}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002762
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002763void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002764 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002765 // something has likely gone wrong. This might still be legit only if application send in
2766 // a long burst of long exposure requests.
2767 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2768 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2769 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2770 mInFlightMap.size(), mExpectedInflightDuration);
2771 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2772 kInFlightWarnLimitHighSpeed) {
2773 CLOGW("In-flight list too large for high speed configuration: %zu,"
2774 "total inflight duration %" PRIu64,
2775 mInFlightMap.size(), mExpectedInflightDuration);
2776 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002777 }
2778}
2779
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002780void Camera3Device::onInflightMapFlushedLocked() {
2781 mExpectedInflightDuration = 0;
2782}
2783
2784void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002785 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002786 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2787 mInFlightMap.removeItemsAt(idx, 1);
2788
2789 onInflightEntryRemovedLocked(duration);
2790}
2791
2792
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002793void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002794 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002795 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002796 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002797 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002798 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002799 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002800
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002801 FlushInflightReqStates states {
2802 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002803 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002804
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002805 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002806}
2807
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002808CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002809 ALOGV("%s", __FUNCTION__);
2810
Igor Murashkin1e479c02013-09-06 16:55:14 -07002811 CameraMetadata retVal;
2812
2813 if (mRequestThread != NULL) {
2814 retVal = mRequestThread->getLatestRequest();
2815 }
2816
Igor Murashkin1e479c02013-09-06 16:55:14 -07002817 return retVal;
2818}
2819
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002820void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002821 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002822 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002823 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2824 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002825
2826 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002827 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002828}
2829
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002830void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002831 std::vector<native_handle_t*> *handles, bool closeFd) {
2832 if (handles == nullptr) {
2833 return;
2834 }
2835 if (closeFd) {
2836 for (auto& handle : *handles) {
2837 native_handle_close(handle);
2838 }
2839 }
2840 for (auto& handle : *handles) {
2841 native_handle_delete(handle);
2842 }
2843 handles->clear();
2844 return;
2845}
2846
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002847/**
2848 * HalInterface inner class methods
2849 */
2850
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002851void Camera3Device::HalInterface::getInflightBufferKeys(
2852 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002853 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002854 return;
2855}
2856
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002857void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2858 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002859 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002860 return;
2861}
2862
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002863bool Camera3Device::HalInterface::verifyBufferIds(
2864 int32_t streamId, std::vector<uint64_t>& bufIds) {
2865 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002866}
2867
2868status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002869 int32_t frameNumber, int32_t streamId,
2870 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002871 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002872}
2873
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002874status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002875 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002876 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002877}
2878
2879// Find and pop a buffer_handle_t based on bufferId
2880status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002881 uint64_t bufferId,
2882 /*out*/ buffer_handle_t** buffer,
2883 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002884 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002885}
2886
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002887std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2888 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002889 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002890}
2891
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002892uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2893 const native_handle_t* handle) {
2894 return mBufferRecords.removeOneBufferCache(streamId, handle);
2895}
2896
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002897void Camera3Device::HalInterface::onBufferFreed(
2898 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002899 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2900 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2901 if (bufferId != BUFFER_ID_NO_BUFFER) {
2902 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002903 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002904}
2905
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002906void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002907 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2908 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2909 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002910 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2911 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002912}
2913
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002914/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002915 * RequestThread inner class methods
2916 */
2917
2918Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002919 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002920 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002921 bool useHalBufManager,
Austin Borger3560b7e2022-10-27 12:20:29 -07002922 bool supportCameraMute,
2923 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002924 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002925 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002926 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002927 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002928 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002929 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002930 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002931 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002932 mReconfigured(false),
2933 mDoPause(false),
2934 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002935 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002936 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002937 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002938 mCurrentAfTriggerId(0),
2939 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002940 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002941 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002942 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002943 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002944 mRepeatingLastFrameNumber(
2945 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002946 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002947 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002948 mRequestLatency(kRequestLatencyBinSize),
2949 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002950 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002951 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002952 mSupportCameraMute(supportCameraMute),
2953 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002954 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955}
2956
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002957Camera3Device::RequestThread::~RequestThread() {}
2958
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002959void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002960 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002961 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002962 Mutex::Autolock l(mRequestLock);
2963 mListener = listener;
2964}
2965
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002966void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002967 const CameraMetadata& sessionParams,
Austin Borger0fb3ad92023-06-01 16:51:35 -07002968 const std::map<int32_t, std::set<std::string>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002969 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002970 Mutex::Autolock l(mRequestLock);
2971 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002972 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002973 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002974 // Prepare video stream for high speed recording.
2975 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002976 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977}
2978
Jianing Wei90e59c92014-03-12 18:29:36 -07002979status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002980 List<sp<CaptureRequest> > &requests,
2981 /*out*/
2982 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002983 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002984 Mutex::Autolock l(mRequestLock);
2985 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2986 ++it) {
2987 mRequestQueue.push_back(*it);
2988 }
2989
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002990 if (lastFrameNumber != NULL) {
2991 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2992 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2993 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2994 *lastFrameNumber);
2995 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002996
Jianing Wei90e59c92014-03-12 18:29:36 -07002997 unpauseForNewRequests();
2998
2999 return OK;
3000}
3001
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003002
3003status_t Camera3Device::RequestThread::queueTrigger(
3004 RequestTrigger trigger[],
3005 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003006 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003007 Mutex::Autolock l(mTriggerMutex);
3008 status_t ret;
3009
3010 for (size_t i = 0; i < count; ++i) {
3011 ret = queueTriggerLocked(trigger[i]);
3012
3013 if (ret != OK) {
3014 return ret;
3015 }
3016 }
3017
3018 return OK;
3019}
3020
Austin Borger0fb3ad92023-06-01 16:51:35 -07003021const std::string& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3022 static std::string deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003024 if (d != nullptr) return d->mId;
3025 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003026}
3027
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003028status_t Camera3Device::RequestThread::queueTriggerLocked(
3029 RequestTrigger trigger) {
3030
3031 uint32_t tag = trigger.metadataTag;
3032 ssize_t index = mTriggerMap.indexOfKey(tag);
3033
3034 switch (trigger.getTagType()) {
3035 case TYPE_BYTE:
3036 // fall-through
3037 case TYPE_INT32:
3038 break;
3039 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003040 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3041 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003042 return INVALID_OPERATION;
3043 }
3044
3045 /**
3046 * Collect only the latest trigger, since we only have 1 field
3047 * in the request settings per trigger tag, and can't send more than 1
3048 * trigger per request.
3049 */
3050 if (index != NAME_NOT_FOUND) {
3051 mTriggerMap.editValueAt(index) = trigger;
3052 } else {
3053 mTriggerMap.add(tag, trigger);
3054 }
3055
3056 return OK;
3057}
3058
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003059status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003060 const RequestList &requests,
3061 /*out*/
3062 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003063 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003064 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003065 if (lastFrameNumber != NULL) {
3066 *lastFrameNumber = mRepeatingLastFrameNumber;
3067 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003068 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003069 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003070 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3071 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003072
3073 unpauseForNewRequests();
3074
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003075 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003076 return OK;
3077}
3078
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003079bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003080 if (mRepeatingRequests.empty()) {
3081 return false;
3082 }
3083 int32_t requestId = requestIn->mResultExtras.requestId;
3084 const RequestList &repeatRequests = mRepeatingRequests;
3085 // All repeating requests are guaranteed to have same id so only check first quest
3086 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3087 return (firstRequest->mResultExtras.requestId == requestId);
3088}
3089
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003090status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003091 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003092 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003093 return clearRepeatingRequestsLocked(lastFrameNumber);
3094
3095}
3096
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003097status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3098 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003099 std::vector<int32_t> streamIds;
3100 for (const auto& request : mRepeatingRequests) {
3101 for (const auto& stream : request->mOutputStreams) {
3102 streamIds.push_back(stream->getId());
3103 }
3104 }
3105
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003106 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003107 if (lastFrameNumber != NULL) {
3108 *lastFrameNumber = mRepeatingLastFrameNumber;
3109 }
Emilian Peev2295df72021-11-12 18:14:10 -08003110
3111 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003113 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003114 return OK;
3115}
3116
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003117status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003118 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003119 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003120 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003121 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003122
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003123 // Send errors for all requests pending in the request queue, including
3124 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003125 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003126 if (listener != NULL) {
3127 for (RequestList::iterator it = mRequestQueue.begin();
3128 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003129 // Abort the input buffers for reprocess requests.
3130 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003131 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003132 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003133 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003134 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003135 if (res != OK) {
3136 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3137 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3138 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003139 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003140 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3141 if (res != OK) {
3142 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3143 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3144 }
3145 }
3146 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003147 // Set the frame number this request would have had, if it
3148 // had been submitted; this frame number will not be reused.
3149 // The requestId and burstId fields were set when the request was
3150 // submitted originally (in convertMetadataListToRequestListLocked)
3151 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003153 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003154 }
3155 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003156 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003157
3158 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003159 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003160 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003161 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003162 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003163 return OK;
3164}
3165
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003166status_t Camera3Device::RequestThread::flush() {
3167 ATRACE_CALL();
3168 Mutex::Autolock l(mFlushLock);
3169
Emilian Peev08dd2452017-04-06 16:55:14 +01003170 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003171}
3172
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003173void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003174 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003175 Mutex::Autolock l(mPauseLock);
3176 mDoPause = paused;
3177 mDoPauseSignal.signal();
3178}
3179
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003180status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3181 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003182 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003183 Mutex::Autolock l(mLatestRequestMutex);
3184 status_t res;
3185 while (mLatestRequestId != requestId) {
3186 nsecs_t startTime = systemTime();
3187
3188 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3189 if (res != OK) return res;
3190
3191 timeout -= (systemTime() - startTime);
3192 }
3193
3194 return OK;
3195}
3196
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003197void Camera3Device::RequestThread::requestExit() {
3198 // Call parent to set up shutdown
3199 Thread::requestExit();
3200 // The exit from any possible waits
3201 mDoPauseSignal.signal();
3202 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003203
3204 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3205 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003206}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003207
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003208void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003209 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003210 bool surfaceAbandoned = false;
3211 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003212 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003213 {
3214 Mutex::Autolock l(mRequestLock);
3215 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3216 // repeating requests.
3217 for (const auto& request : mRepeatingRequests) {
3218 for (const auto& s : request->mOutputStreams) {
3219 if (s->isAbandoned()) {
3220 surfaceAbandoned = true;
3221 clearRepeatingRequestsLocked(&lastFrameNumber);
3222 break;
3223 }
3224 }
3225 if (surfaceAbandoned) {
3226 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003227 }
3228 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003229 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003230 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003231
3232 if (listener != NULL && surfaceAbandoned) {
3233 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003234 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003235}
3236
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003237bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003238 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003239 status_t res;
3240 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003241 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003242 uint32_t numRequestProcessed = 0;
3243 for (size_t i = 0; i < batchSize; i++) {
3244 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003245 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003246 }
3247
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003248 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3249
3250 bool triggerRemoveFailed = false;
3251 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3252 for (size_t i = 0; i < numRequestProcessed; i++) {
3253 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3254 nextRequest.submitted = true;
3255
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003256 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003257
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003258 if (!triggerRemoveFailed) {
3259 // Remove any previously queued triggers (after unlock)
3260 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3261 if (removeTriggerRes != OK) {
3262 triggerRemoveFailed = true;
3263 triggerFailedRequest = nextRequest;
3264 }
3265 }
3266 }
3267
3268 if (triggerRemoveFailed) {
3269 SET_ERR("RequestThread: Unable to remove triggers "
3270 "(capture request %d, HAL device: %s (%d)",
3271 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3272 cleanUpFailedRequests(/*sendRequestError*/ false);
3273 return false;
3274 }
3275
3276 if (res != OK) {
3277 // Should only get a failure here for malformed requests or device-level
3278 // errors, so consider all errors fatal. Bad metadata failures should
3279 // come through notify.
3280 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3281 mNextRequests[numRequestProcessed].halRequest.frame_number,
3282 strerror(-res), res);
3283 cleanUpFailedRequests(/*sendRequestError*/ false);
3284 return false;
3285 }
3286 return true;
3287}
3288
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003289Camera3Device::RequestThread::ExpectedDurationInfo
3290 Camera3Device::RequestThread::calculateExpectedDurationRange(
3291 const camera_metadata_t *request) {
3292 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003293 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003294 InFlightRequest::kDefaultMaxExpectedDuration,
3295 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003296 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3297 find_camera_metadata_ro_entry(request,
3298 ANDROID_CONTROL_AE_MODE,
3299 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003300 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003301
3302 switch (e.data.u8[0]) {
3303 case ANDROID_CONTROL_AE_MODE_OFF:
3304 find_camera_metadata_ro_entry(request,
3305 ANDROID_SENSOR_EXPOSURE_TIME,
3306 &e);
3307 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003308 expectedDurationInfo.minDuration = e.data.i64[0];
3309 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003310 }
3311 find_camera_metadata_ro_entry(request,
3312 ANDROID_SENSOR_FRAME_DURATION,
3313 &e);
3314 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003315 expectedDurationInfo.minDuration =
3316 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3317 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003318 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003319 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003320 break;
3321 default:
3322 find_camera_metadata_ro_entry(request,
3323 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3324 &e);
3325 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003326 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3327 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003328 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003329 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003330 break;
3331 }
3332
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003333 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003334}
3335
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003336bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3337 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3338 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3339 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3340 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3341 return true;
3342 }
3343
3344 return false;
3345}
3346
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003347void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3348 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003349 camera_capture_request_t& halRequest = nextRequest.halRequest;
3350 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003351 Mutex::Autolock al(mLatestRequestMutex);
3352
Shuzhen Wang83bff122020-11-20 15:51:39 -08003353 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003354 mLatestRequest.acquire(cloned);
3355
3356 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003357 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3358 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3359 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003360 CameraMetadata(cloned));
3361 }
3362
3363 sp<Camera3Device> parent = mParent.promote();
3364 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003365 int32_t inputStreamId = -1;
3366 if (halRequest.input_buffer != nullptr) {
3367 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3368 }
3369
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003370 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003371 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003372 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3373 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003374 }
3375 }
3376
Shuzhen Wang83bff122020-11-20 15:51:39 -08003377 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003378 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003379 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003380 }
3381
Shuzhen Wang83bff122020-11-20 15:51:39 -08003382 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003383}
3384
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003385bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3386 ATRACE_CALL();
3387 bool updatesDetected = false;
3388
Emilian Peev4ec17882019-01-24 17:16:58 -08003389 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003390 for (auto tag : mSessionParamKeys) {
3391 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003392 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003393
3394 if (entry.count > 0) {
3395 bool isDifferent = false;
3396 if (lastEntry.count > 0) {
3397 // Have a last value, compare to see if changed
3398 if (lastEntry.type == entry.type &&
3399 lastEntry.count == entry.count) {
3400 // Same type and count, compare values
3401 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3402 size_t entryBytes = bytesPerValue * lastEntry.count;
3403 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3404 if (cmp != 0) {
3405 isDifferent = true;
3406 }
3407 } else {
3408 // Count or type has changed
3409 isDifferent = true;
3410 }
3411 } else {
3412 // No last entry, so always consider to be different
3413 isDifferent = true;
3414 }
3415
3416 if (isDifferent) {
3417 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003418 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3419 updatesDetected = true;
3420 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003421 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003422 }
3423 } else if (lastEntry.count > 0) {
3424 // Value has been removed
3425 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003426 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003427 updatesDetected = true;
3428 }
3429 }
3430
Emilian Peev4ec17882019-01-24 17:16:58 -08003431 bool reconfigureRequired;
3432 if (updatesDetected) {
3433 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3434 updatedParams);
3435 mLatestSessionParams = updatedParams;
3436 } else {
3437 reconfigureRequired = false;
3438 }
3439
3440 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003441}
3442
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003443bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003444 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003445 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003446 // Any function called from threadLoop() must not hold mInterfaceLock since
3447 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3448 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003449
3450 // Handle paused state.
3451 if (waitIfPaused()) {
3452 return true;
3453 }
3454
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003455 // Wait for the next batch of requests.
3456 waitForNextRequestBatch();
3457 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003458 return true;
3459 }
3460
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003461 // Get the latest request ID, if any
3462 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003463 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003464 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003465 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003466 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003467 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003468 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3469 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003470 }
3471
Emilian Peevb9f83812023-03-17 17:13:07 -07003472 for (size_t i = 0; i < mNextRequests.size(); i++) {
3473 auto& nextRequest = mNextRequests.editItemAt(i);
3474 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3475 // Do not override rotate&crop for stream configurations that include
3476 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3477 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3478 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3479 overrideAutoRotateAndCrop(captureRequest);
3480 }
3481
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003482 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3483 // or a single request from streaming or burst. In either case the first element
3484 // should contain the latest camera settings that we need to check for any session
3485 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003486 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003487 res = OK;
3488
3489 //Input stream buffers are already acquired at this point so an input stream
3490 //will not be able to move to idle state unless we force it.
3491 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3492 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3493 if (res != OK) {
3494 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3495 cleanUpFailedRequests(/*sendRequestError*/ false);
3496 return false;
3497 }
3498 }
3499
3500 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003501 sp<Camera3Device> parent = mParent.promote();
3502 if (parent != nullptr) {
3503 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003504 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003505 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003506
3507 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3508 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3509 if (res != OK) {
3510 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3511 cleanUpFailedRequests(/*sendRequestError*/ false);
3512 return false;
3513 }
3514 }
3515 }
3516 }
3517
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003518 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003519 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003520 if (res == TIMED_OUT) {
3521 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003522 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003523 // Check if any stream is abandoned.
3524 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003525 return true;
3526 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003527 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003528 return false;
3529 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003530
Zhijun Hecc27e112013-10-03 16:12:43 -07003531 // Inform waitUntilRequestProcessed thread of a new request ID
3532 {
3533 Mutex::Autolock al(mLatestRequestMutex);
3534
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003535 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003536 mLatestRequestSignal.signal();
3537 }
3538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003539 // Submit a batch of requests to HAL.
3540 // Use flush lock only when submitting multilple requests in a batch.
3541 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3542 // which may take a long time to finish so synchronizing flush() and
3543 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3544 // For now, only synchronize for high speed recording and we should figure something out for
3545 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003546 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003547
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003548 if (useFlushLock) {
3549 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003550 }
3551
Zhijun Hef0645c12016-08-02 00:58:11 -07003552 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003553 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003554
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003555 sp<Camera3Device> parent = mParent.promote();
3556 if (parent != nullptr) {
3557 parent->mRequestBufferSM.onSubmittingRequest();
3558 }
3559
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003560 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003561 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003562 submitRequestSuccess = sendRequestsBatch();
3563
Shuzhen Wang686f6442017-06-20 16:16:04 -07003564 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3565 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003566
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003567 if (useFlushLock) {
3568 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003569 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003570
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003571 // Unset as current request
3572 {
3573 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003574 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003575 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003576 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003577
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003578 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003579}
3580
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003581status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3582 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3583 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3584 ANDROID_SCALER_CROP_REGION_SET};
3585 if (request == nullptr) {
3586 ALOGE("%s request metadata nullptr", __FUNCTION__);
3587 return BAD_VALUE;
3588 }
3589 status_t res = OK;
3590 for (const auto &key : kFwkOnlyRegionKeys) {
3591 if (request->exists(key)) {
3592 res = request->erase(key);
3593 if (res != OK) {
3594 return res;
3595 }
3596 }
3597 }
3598 return OK;
3599}
3600
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003601status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003602 ATRACE_CALL();
3603
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003604 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003605 for (size_t i = 0; i < mNextRequests.size(); i++) {
3606 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003607 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003608 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3609 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003610
3611 // Prepare a request to HAL
3612 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3613
3614 // Insert any queued triggers (before metadata is locked)
3615 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003616 if (res < 0) {
3617 SET_ERR("RequestThread: Unable to insert triggers "
3618 "(capture request %d, HAL device: %s (%d)",
3619 halRequest->frame_number, strerror(-res), res);
3620 return INVALID_OPERATION;
3621 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003622
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003623 int triggerCount = res;
3624 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3625 mPrevTriggers = triggerCount;
3626
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003627 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003628
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003629 // If the request is the same as last, or we had triggers now or last time or
3630 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003631 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003632 (mPrevRequest != captureRequest || triggersMixedIn ||
Emilian Peevb9f83812023-03-17 17:13:07 -07003633 captureRequest->mRotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003634 // Request settings are all the same within one batch, so only treat the first
3635 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003636 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003637 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003638 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003639 /**
3640 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003641 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003642 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003643 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003644 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003645 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003646 "(capture request %d, HAL device: %s (%d)",
3647 halRequest->frame_number, strerror(-res), res);
3648 return INVALID_OPERATION;
3649 }
3650
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003651 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003652 sp<Camera3Device> parent = mParent.promote();
3653 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003654 List<PhysicalCameraSettings>::iterator it;
3655 for (it = captureRequest->mSettingsList.begin();
3656 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003657 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3658 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003659 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3660 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3661 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3662 res);
3663 return INVALID_OPERATION;
3664 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003665 continue;
3666 }
3667
3668 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3669 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3670 updateCaptureRequest(&(it->metadata));
3671 if (res != OK) {
3672 SET_ERR("RequestThread: Unable to correct capture requests "
3673 "for scaler crop region and metering regions for request "
3674 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3675 res);
3676 return INVALID_OPERATION;
3677 }
3678 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003679 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3680 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3681 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3682 res);
3683 return INVALID_OPERATION;
3684 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003685 }
3686 }
3687
3688 // Correct metadata regions for distortion correction if enabled
3689 for (it = captureRequest->mSettingsList.begin();
3690 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003691 if (parent->mDistortionMappers.find(it->cameraId) ==
3692 parent->mDistortionMappers.end()) {
3693 continue;
3694 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003695
3696 if (!captureRequest->mDistortionCorrectionUpdated) {
3697 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3698 &(it->metadata));
3699 if (res != OK) {
3700 SET_ERR("RequestThread: Unable to correct capture requests "
3701 "for lens distortion for request %d: %s (%d)",
3702 halRequest->frame_number, strerror(-res), res);
3703 return INVALID_OPERATION;
3704 }
3705 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003706 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003707 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003708
3709 for (it = captureRequest->mSettingsList.begin();
3710 it != captureRequest->mSettingsList.end(); it++) {
3711 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3712 parent->mZoomRatioMappers.end()) {
3713 continue;
3714 }
3715
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003716 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003717 cameraIdsWithZoom.insert(it->cameraId);
3718 }
3719
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003720 if (!captureRequest->mZoomRatioUpdated) {
3721 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3722 &(it->metadata));
3723 if (res != OK) {
3724 SET_ERR("RequestThread: Unable to correct capture requests "
3725 "for zoom ratio for request %d: %s (%d)",
3726 halRequest->frame_number, strerror(-res), res);
3727 return INVALID_OPERATION;
3728 }
3729 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003730 }
3731 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003732 if (captureRequest->mRotateAndCropAuto &&
3733 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003734 for (it = captureRequest->mSettingsList.begin();
3735 it != captureRequest->mSettingsList.end(); it++) {
3736 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3737 if (mapper != parent->mRotateAndCropMappers.end()) {
3738 res = mapper->second.updateCaptureRequest(&(it->metadata));
3739 if (res != OK) {
3740 SET_ERR("RequestThread: Unable to correct capture requests "
3741 "for rotate-and-crop for request %d: %s (%d)",
3742 halRequest->frame_number, strerror(-res), res);
3743 return INVALID_OPERATION;
3744 }
3745 }
3746 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003747 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003748 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003749 }
3750 }
3751
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003752 /**
3753 * The request should be presorted so accesses in HAL
3754 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3755 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003756 captureRequest->mSettingsList.begin()->metadata.sort();
3757 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003758 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003759 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003760 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3761
3762 IF_ALOGV() {
3763 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3764 find_camera_metadata_ro_entry(
3765 halRequest->settings,
3766 ANDROID_CONTROL_AF_TRIGGER,
3767 &e
3768 );
3769 if (e.count > 0) {
3770 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3771 __FUNCTION__,
3772 halRequest->frame_number,
3773 e.data.u8[0]);
3774 }
3775 }
3776 } else {
3777 // leave request.settings NULL to indicate 'reuse latest given'
3778 ALOGVV("%s: Request settings are REUSED",
3779 __FUNCTION__);
3780 }
3781
Emilian Peevaebbe412018-01-15 13:53:24 +00003782 if (captureRequest->mSettingsList.size() > 1) {
3783 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3784 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003785 if (newRequest) {
3786 halRequest->physcam_settings =
3787 new const camera_metadata* [halRequest->num_physcam_settings];
3788 } else {
3789 halRequest->physcam_settings = nullptr;
3790 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003791 auto it = ++captureRequest->mSettingsList.begin();
3792 size_t i = 0;
3793 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3794 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003795 if (newRequest) {
3796 it->metadata.sort();
3797 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3798 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003799 }
3800 }
3801
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003802 uint32_t totalNumBuffers = 0;
3803
3804 // Fill in buffers
3805 if (captureRequest->mInputStream != NULL) {
3806 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003807
3808 halRequest->input_width = captureRequest->mInputBufferSize.width;
3809 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003810 totalNumBuffers += 1;
3811 } else {
3812 halRequest->input_buffer = NULL;
3813 }
3814
Emilian Peevf4816702020-04-03 15:44:51 -07003815 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003816 captureRequest->mOutputStreams.size());
3817 halRequest->output_buffers = outputBuffers->array();
Austin Borger0fb3ad92023-06-01 16:51:35 -07003818 std::set<std::set<std::string>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003819
3820 sp<Camera3Device> parent = mParent.promote();
3821 if (parent == NULL) {
3822 // Should not happen, and nowhere to send errors to, so just log it
3823 CLOGE("RequestThread: Parent is gone");
3824 return INVALID_OPERATION;
3825 }
3826 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3827
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003828 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003829 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003830 sp<Camera3OutputStreamInterface> outputStream =
3831 captureRequest->mOutputStreams.editItemAt(j);
3832 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003833
3834 // Prepare video buffers for high speed recording on the first video request.
3835 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3836 // Only try to prepare video stream on the first video request.
3837 mPrepareVideoStream = false;
3838
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003839 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3840 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003841 while (res == NOT_ENOUGH_DATA) {
3842 res = outputStream->prepareNextBuffer();
3843 }
3844 if (res != OK) {
3845 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3846 __FUNCTION__, strerror(-res), res);
3847 outputStream->cancelPrepare();
3848 }
3849 }
3850
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003851 std::vector<size_t> uniqueSurfaceIds;
3852 res = outputStream->getUniqueSurfaceIds(
3853 captureRequest->mOutputSurfaces[streamId],
3854 &uniqueSurfaceIds);
3855 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3856 if (res != OK && res != INVALID_OPERATION) {
3857 ALOGE("%s: failed to query stream %d unique surface IDs",
3858 __FUNCTION__, streamId);
3859 return res;
3860 }
3861 if (res == OK) {
3862 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3863 }
3864
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003865 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003866 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003867 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003868 return TIMED_OUT;
3869 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003870 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003871 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003872 buffer.stream = outputStream->asHalStream();
3873 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003874 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003875 buffer.acquire_fence = -1;
3876 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003877 // Mark the output stream as unpreparable to block clients from calling
3878 // 'prepare' after this request reaches CameraHal and before the respective
3879 // buffers are requested.
3880 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003881 } else {
3882 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3883 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003884 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003885 if (res != OK) {
3886 // Can't get output buffer from gralloc queue - this could be due to
3887 // abandoned queue or other consumer misbehavior, so not a fatal
3888 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003889 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003890 " %s (%d)", strerror(-res), res);
3891
3892 return TIMED_OUT;
3893 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003894 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003895
3896 {
3897 sp<Camera3Device> parent = mParent.promote();
3898 if (parent != nullptr) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07003899 const std::string& streamCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003900 for (const auto& settings : captureRequest->mSettingsList) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07003901 if ((streamCameraId.empty() &&
3902 parent->getId() == settings.cameraId) ||
3903 streamCameraId == settings.cameraId) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003904 outputStream->fireBufferRequestForFrameNumber(
3905 captureRequest->mResultExtras.frameNumber,
3906 settings.metadata);
3907 }
3908 }
3909 }
3910 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003911
Austin Borger0fb3ad92023-06-01 16:51:35 -07003912 const std::string &physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003913 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3914 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3915 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
Austin Borger0fb3ad92023-06-01 16:51:35 -07003916 } else if (!physicalCameraId.empty()) {
3917 requestedPhysicalCameras.insert(std::set<std::string>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003918 }
3919 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003920 }
3921 totalNumBuffers += halRequest->num_output_buffers;
3922
3923 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003924 // If this request list is for constrained high speed recording (not
3925 // preview), and the current request is not the last one in the batch,
3926 // do not send callback to the app.
3927 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003928 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003929 hasCallback = false;
3930 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003931 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003932 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003933 const camera_metadata_t* settings = halRequest->settings;
3934 bool shouldUnlockSettings = false;
3935 if (settings == nullptr) {
3936 shouldUnlockSettings = true;
3937 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3938 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003939 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3940 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003941 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003942 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3943 isStillCapture = true;
3944 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3945 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003946
Emilian Peevaf8416e2021-02-04 17:52:43 -08003947 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003948 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003949 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3950 isZslCapture = true;
3951 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003952 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003953 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003954 res = parent->registerInFlight(halRequest->frame_number,
3955 totalNumBuffers, captureRequest->mResultExtras,
3956 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003957 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003958 expectedDurationInfo.minDuration,
3959 expectedDurationInfo.maxDuration,
3960 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003961 requestedPhysicalCameras, isStillCapture, isZslCapture,
3962 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003963 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003964 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003965 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3966 ", burstId = %" PRId32 ".",
3967 __FUNCTION__,
3968 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3969 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003970
3971 if (shouldUnlockSettings) {
3972 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3973 }
3974
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003975 if (res != OK) {
3976 SET_ERR("RequestThread: Unable to register new in-flight request:"
3977 " %s (%d)", strerror(-res), res);
3978 return INVALID_OPERATION;
3979 }
3980 }
3981
3982 return OK;
3983}
3984
Igor Murashkin1e479c02013-09-06 16:55:14 -07003985CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003986 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003987 Mutex::Autolock al(mLatestRequestMutex);
3988
3989 ALOGV("RequestThread::%s", __FUNCTION__);
3990
3991 return mLatestRequest;
3992}
3993
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003994bool Camera3Device::RequestThread::isStreamPending(
3995 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003996 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003997 Mutex::Autolock l(mRequestLock);
3998
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003999 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004000 if (!nextRequest.submitted) {
4001 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4002 if (stream == s) return true;
4003 }
4004 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004005 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004006 }
4007
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004008 for (const auto& request : mRequestQueue) {
4009 for (const auto& s : request->mOutputStreams) {
4010 if (stream == s) return true;
4011 }
4012 if (stream == request->mInputStream) return true;
4013 }
4014
4015 for (const auto& request : mRepeatingRequests) {
4016 for (const auto& s : request->mOutputStreams) {
4017 if (stream == s) return true;
4018 }
4019 if (stream == request->mInputStream) return true;
4020 }
4021
4022 return false;
4023}
Jianing Weicb0652e2014-03-12 18:29:36 -07004024
Emilian Peev40ead602017-09-26 15:46:36 +01004025bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4026 ATRACE_CALL();
4027 Mutex::Autolock l(mRequestLock);
4028
4029 for (const auto& nextRequest : mNextRequests) {
4030 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4031 if (s.first == streamId) {
4032 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4033 if (it != s.second.end()) {
4034 return true;
4035 }
4036 }
4037 }
4038 }
4039
4040 for (const auto& request : mRequestQueue) {
4041 for (const auto& s : request->mOutputSurfaces) {
4042 if (s.first == streamId) {
4043 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4044 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004045 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004046 }
4047 }
4048 }
4049 }
4050
4051 for (const auto& request : mRepeatingRequests) {
4052 for (const auto& s : request->mOutputSurfaces) {
4053 if (s.first == streamId) {
4054 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4055 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004056 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004057 }
4058 }
4059 }
4060 }
4061
4062 return false;
4063}
4064
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004065void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4066 if (!mUseHalBufManager) {
4067 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4068 return;
4069 }
4070
4071 Mutex::Autolock pl(mPauseLock);
4072 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004073 mInterface->signalPipelineDrain(streamIds);
4074 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004075 }
4076 // If request thread is still busy, wait until paused then notify HAL
4077 mNotifyPipelineDrain = true;
4078 mStreamIdsToBeDrained = streamIds;
4079}
4080
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004081void Camera3Device::RequestThread::resetPipelineDrain() {
4082 Mutex::Autolock pl(mPauseLock);
4083 mNotifyPipelineDrain = false;
4084 mStreamIdsToBeDrained.clear();
4085}
4086
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004087void Camera3Device::RequestThread::clearPreviousRequest() {
4088 Mutex::Autolock l(mRequestLock);
4089 mPrevRequest.clear();
4090}
4091
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004092status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4093 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4094 ATRACE_CALL();
4095 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004096 mRotateAndCropOverride = rotateAndCropValue;
4097 return OK;
4098}
4099
Emilian Peeve23f1d92021-09-20 14:56:01 -07004100status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4101 ATRACE_CALL();
4102 Mutex::Autolock l(mTriggerMutex);
4103 mComposerOutput = composerSurfacePresent;
4104 return OK;
4105}
4106
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004107status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004108 ATRACE_CALL();
4109 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004110 if (muteMode != mCameraMute) {
4111 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004112 mCameraMuteChanged = true;
4113 }
4114 return OK;
4115}
4116
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004117nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004118 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004120 return mExpectedInflightDuration > kMinInflightDuration ?
4121 mExpectedInflightDuration : kMinInflightDuration;
4122}
4123
Emilian Peevaebbe412018-01-15 13:53:24 +00004124void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004125 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004126 if ((request == nullptr) || (halRequest == nullptr)) {
4127 ALOGE("%s: Invalid request!", __FUNCTION__);
4128 return;
4129 }
4130
4131 if (halRequest->num_physcam_settings > 0) {
4132 if (halRequest->physcam_id != nullptr) {
4133 delete [] halRequest->physcam_id;
4134 halRequest->physcam_id = nullptr;
4135 }
4136 if (halRequest->physcam_settings != nullptr) {
4137 auto it = ++(request->mSettingsList.begin());
4138 size_t i = 0;
4139 for (; it != request->mSettingsList.end(); it++, i++) {
4140 it->metadata.unlock(halRequest->physcam_settings[i]);
4141 }
4142 delete [] halRequest->physcam_settings;
4143 halRequest->physcam_settings = nullptr;
4144 }
4145 }
4146}
4147
Ravneet74cd3732022-03-30 05:33:03 +00004148status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4149 Mutex::Autolock il(mInterfaceLock);
4150 Mutex::Autolock l(mLock);
4151
4152 if (mCameraServiceWatchdog != NULL) {
4153 mCameraServiceWatchdog->setEnabled(enabled);
4154 }
4155
4156 return OK;
4157}
4158
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004159void Camera3Device::setStreamUseCaseOverrides(
4160 const std::vector<int64_t>& useCaseOverrides) {
4161 Mutex::Autolock il(mInterfaceLock);
4162 Mutex::Autolock l(mLock);
4163 mStreamUseCaseOverrides = useCaseOverrides;
4164}
4165
4166void Camera3Device::clearStreamUseCaseOverrides() {
4167 Mutex::Autolock il(mInterfaceLock);
4168 Mutex::Autolock l(mLock);
4169 mStreamUseCaseOverrides.clear();
4170}
4171
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004172void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4173 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004174 return;
4175 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004176
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004177 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004178 // Skip the ones that have been submitted successfully.
4179 if (nextRequest.submitted) {
4180 continue;
4181 }
4182
4183 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004184 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4185 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004186
4187 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004188 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004189 }
4190
Emilian Peevaebbe412018-01-15 13:53:24 +00004191 cleanupPhysicalSettings(captureRequest, halRequest);
4192
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004193 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004194 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004195 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4196 }
4197
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004198 // No output buffer can be returned when using HAL buffer manager
4199 if (!mUseHalBufManager) {
4200 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4201 //Buffers that failed processing could still have
4202 //valid acquire fence.
4203 int acquireFence = (*outputBuffers)[i].acquire_fence;
4204 if (0 <= acquireFence) {
4205 close(acquireFence);
4206 outputBuffers->editItemAt(i).acquire_fence = -1;
4207 }
Emilian Peevf4816702020-04-03 15:44:51 -07004208 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004209 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4210 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004211 /*timestampIncreasing*/true, std::vector<size_t> (),
4212 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004213 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004214 }
4215
4216 if (sendRequestError) {
4217 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004218 sp<NotificationListener> listener = mListener.promote();
4219 if (listener != NULL) {
4220 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004221 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 captureRequest->mResultExtras);
4223 }
4224 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004225
4226 // Remove yet-to-be submitted inflight request from inflightMap
4227 {
4228 sp<Camera3Device> parent = mParent.promote();
4229 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004230 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004231 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4232 if (idx >= 0) {
4233 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4234 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4235 parent->removeInFlightMapEntryLocked(idx);
4236 }
4237 }
4238 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004239 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004240
4241 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004242 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243}
4244
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004245void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004246 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004247 // Optimized a bit for the simple steady-state case (single repeating
4248 // request), to avoid putting that request in the queue temporarily.
4249 Mutex::Autolock l(mRequestLock);
4250
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004251 assert(mNextRequests.empty());
4252
4253 NextRequest nextRequest;
4254 nextRequest.captureRequest = waitForNextRequestLocked();
4255 if (nextRequest.captureRequest == nullptr) {
4256 return;
4257 }
4258
Emilian Peevf4816702020-04-03 15:44:51 -07004259 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004260 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004261 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004262
4263 // Wait for additional requests
4264 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4265
4266 for (size_t i = 1; i < batchSize; i++) {
4267 NextRequest additionalRequest;
4268 additionalRequest.captureRequest = waitForNextRequestLocked();
4269 if (additionalRequest.captureRequest == nullptr) {
4270 break;
4271 }
4272
Emilian Peevf4816702020-04-03 15:44:51 -07004273 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004274 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004275 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004276 }
4277
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004278 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004279 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004280 mNextRequests.size(), batchSize);
4281 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004282 }
4283
4284 return;
4285}
4286
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004287void Camera3Device::RequestThread::setRequestClearing() {
4288 Mutex::Autolock l(mRequestLock);
4289 mRequestClearing = true;
4290}
4291
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004292sp<Camera3Device::CaptureRequest>
4293 Camera3Device::RequestThread::waitForNextRequestLocked() {
4294 status_t res;
4295 sp<CaptureRequest> nextRequest;
4296
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004297 while (mRequestQueue.empty()) {
4298 if (!mRepeatingRequests.empty()) {
4299 // Always atomically enqueue all requests in a repeating request
4300 // list. Guarantees a complete in-sequence set of captures to
4301 // application.
4302 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004303 if (mFirstRepeating) {
4304 mFirstRepeating = false;
4305 } else {
4306 for (auto& request : requests) {
4307 // For repeating requests, override timestamp request using
4308 // the time a request is inserted into the request queue,
4309 // because the original repeating request will have an old
4310 // fixed timestamp.
4311 request->mRequestTimeNs = systemTime();
4312 }
4313 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 RequestList::const_iterator firstRequest =
4315 requests.begin();
4316 nextRequest = *firstRequest;
4317 mRequestQueue.insert(mRequestQueue.end(),
4318 ++firstRequest,
4319 requests.end());
4320 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004321
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004322 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004323
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004324 break;
4325 }
4326
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004327 if (!mRequestClearing) {
4328 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4329 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004330
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004331 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4332 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 Mutex::Autolock pl(mPauseLock);
4334 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004335 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004336 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004337 if (mNotifyPipelineDrain) {
4338 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4339 mNotifyPipelineDrain = false;
4340 mStreamIdsToBeDrained.clear();
4341 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004342 // Let the tracker know
4343 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4344 if (statusTracker != 0) {
4345 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4346 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004347 sp<Camera3Device> parent = mParent.promote();
4348 if (parent != nullptr) {
4349 parent->mRequestBufferSM.onRequestThreadPaused();
4350 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004351 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004352 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004353 // Stop waiting for now and let thread management happen
4354 return NULL;
4355 }
4356 }
4357
4358 if (nextRequest == NULL) {
4359 // Don't have a repeating request already in hand, so queue
4360 // must have an entry now.
4361 RequestList::iterator firstRequest =
4362 mRequestQueue.begin();
4363 nextRequest = *firstRequest;
4364 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004365 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4366 sp<NotificationListener> listener = mListener.promote();
4367 if (listener != NULL) {
4368 listener->notifyRequestQueueEmpty();
4369 }
4370 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004371 }
4372
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004373 // In case we've been unpaused by setPaused clearing mDoPause, need to
4374 // update internal pause state (capture/setRepeatingRequest unpause
4375 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004376 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004377 if (mPaused) {
4378 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4379 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4380 if (statusTracker != 0) {
4381 statusTracker->markComponentActive(mStatusId);
4382 }
4383 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004384 mPaused = false;
4385
4386 // Check if we've reconfigured since last time, and reset the preview
4387 // request if so. Can't use 'NULL request == repeat' across configure calls.
4388 if (mReconfigured) {
4389 mPrevRequest.clear();
4390 mReconfigured = false;
4391 }
4392
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004393 if (nextRequest != NULL) {
4394 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004395 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4396 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004397
4398 // Since RequestThread::clear() removes buffers from the input stream,
4399 // get the right buffer here before unlocking mRequestLock
4400 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004401 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4402 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004403 if (res != OK) {
4404 // Can't get input buffer from gralloc queue - this could be due to
4405 // disconnected queue or other producer misbehavior, so not a fatal
4406 // error
4407 ALOGE("%s: Can't get input buffer, skipping request:"
4408 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004409
4410 sp<NotificationListener> listener = mListener.promote();
4411 if (listener != NULL) {
4412 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004413 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004414 nextRequest->mResultExtras);
4415 }
4416 return NULL;
4417 }
4418 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004419 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004420
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004421 return nextRequest;
4422}
4423
4424bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004425 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004426 status_t res;
4427 Mutex::Autolock l(mPauseLock);
4428 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004429 if (mPaused == false) {
4430 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004431 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004432 if (mNotifyPipelineDrain) {
4433 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4434 mNotifyPipelineDrain = false;
4435 mStreamIdsToBeDrained.clear();
4436 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004437 // Let the tracker know
4438 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4439 if (statusTracker != 0) {
4440 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4441 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004442 sp<Camera3Device> parent = mParent.promote();
4443 if (parent != nullptr) {
4444 parent->mRequestBufferSM.onRequestThreadPaused();
4445 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004446 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004447
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004449 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 return true;
4451 }
4452 }
4453 // We don't set mPaused to false here, because waitForNextRequest needs
4454 // to further manage the paused state in case of starvation.
4455 return false;
4456}
4457
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004458void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004459 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004460 // With work to do, mark thread as unpaused.
4461 // If paused by request (setPaused), don't resume, to avoid
4462 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004463 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004464 Mutex::Autolock p(mPauseLock);
4465 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004466 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4467 if (mPaused) {
4468 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4469 if (statusTracker != 0) {
4470 statusTracker->markComponentActive(mStatusId);
4471 }
4472 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004473 mPaused = false;
4474 }
4475}
4476
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004477void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4478 sp<Camera3Device> parent = mParent.promote();
4479 if (parent != NULL) {
4480 va_list args;
4481 va_start(args, fmt);
4482
4483 parent->setErrorStateV(fmt, args);
4484
4485 va_end(args);
4486 }
4487}
4488
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004489status_t Camera3Device::RequestThread::insertTriggers(
4490 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004491 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004492 Mutex::Autolock al(mTriggerMutex);
4493
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004494 sp<Camera3Device> parent = mParent.promote();
4495 if (parent == NULL) {
4496 CLOGE("RequestThread: Parent is gone");
4497 return DEAD_OBJECT;
4498 }
4499
Emilian Peevaebbe412018-01-15 13:53:24 +00004500 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004501 size_t count = mTriggerMap.size();
4502
4503 for (size_t i = 0; i < count; ++i) {
4504 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004505 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004506
4507 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4508 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4509 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004510 if (isAeTrigger) {
4511 request->mResultExtras.precaptureTriggerId = triggerId;
4512 mCurrentPreCaptureTriggerId = triggerId;
4513 } else {
4514 request->mResultExtras.afTriggerId = triggerId;
4515 mCurrentAfTriggerId = triggerId;
4516 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004517 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004518 }
4519
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004520 camera_metadata_entry entry = metadata.find(tag);
4521
4522 if (entry.count > 0) {
4523 /**
4524 * Already has an entry for this trigger in the request.
4525 * Rewrite it with our requested trigger value.
4526 */
4527 RequestTrigger oldTrigger = trigger;
4528
4529 oldTrigger.entryValue = entry.data.u8[0];
4530
4531 mTriggerReplacedMap.add(tag, oldTrigger);
4532 } else {
4533 /**
4534 * More typical, no trigger entry, so we just add it
4535 */
4536 mTriggerRemovedMap.add(tag, trigger);
4537 }
4538
4539 status_t res;
4540
4541 switch (trigger.getTagType()) {
4542 case TYPE_BYTE: {
4543 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4544 res = metadata.update(tag,
4545 &entryValue,
4546 /*count*/1);
4547 break;
4548 }
4549 case TYPE_INT32:
4550 res = metadata.update(tag,
4551 &trigger.entryValue,
4552 /*count*/1);
4553 break;
4554 default:
4555 ALOGE("%s: Type not supported: 0x%x",
4556 __FUNCTION__,
4557 trigger.getTagType());
4558 return INVALID_OPERATION;
4559 }
4560
4561 if (res != OK) {
4562 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4563 ", value %d", __FUNCTION__, trigger.getTagName(),
4564 trigger.entryValue);
4565 return res;
4566 }
4567
4568 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4569 trigger.getTagName(),
4570 trigger.entryValue);
4571 }
4572
4573 mTriggerMap.clear();
4574
4575 return count;
4576}
4577
4578status_t Camera3Device::RequestThread::removeTriggers(
4579 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004580 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004581 Mutex::Autolock al(mTriggerMutex);
4582
Emilian Peevaebbe412018-01-15 13:53:24 +00004583 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004584
4585 /**
4586 * Replace all old entries with their old values.
4587 */
4588 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4589 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4590
4591 status_t res;
4592
4593 uint32_t tag = trigger.metadataTag;
4594 switch (trigger.getTagType()) {
4595 case TYPE_BYTE: {
4596 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4597 res = metadata.update(tag,
4598 &entryValue,
4599 /*count*/1);
4600 break;
4601 }
4602 case TYPE_INT32:
4603 res = metadata.update(tag,
4604 &trigger.entryValue,
4605 /*count*/1);
4606 break;
4607 default:
4608 ALOGE("%s: Type not supported: 0x%x",
4609 __FUNCTION__,
4610 trigger.getTagType());
4611 return INVALID_OPERATION;
4612 }
4613
4614 if (res != OK) {
4615 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4616 ", trigger value %d", __FUNCTION__,
4617 trigger.getTagName(), trigger.entryValue);
4618 return res;
4619 }
4620 }
4621 mTriggerReplacedMap.clear();
4622
4623 /**
4624 * Remove all new entries.
4625 */
4626 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4627 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4628 status_t res = metadata.erase(trigger.metadataTag);
4629
4630 if (res != OK) {
4631 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4632 ", trigger value %d", __FUNCTION__,
4633 trigger.getTagName(), trigger.entryValue);
4634 return res;
4635 }
4636 }
4637 mTriggerRemovedMap.clear();
4638
4639 return OK;
4640}
4641
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004642status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004643 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004644 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004645 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004646 status_t res;
4647
Emilian Peevaebbe412018-01-15 13:53:24 +00004648 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004649
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004650 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004651 // exists
4652 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4653 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4654 if (afTrigger.count > 0 &&
4655 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4656 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004657 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004658 if (res != OK) return res;
4659 }
4660
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004661 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004662 // if none already exists
4663 camera_metadata_entry pcTrigger =
4664 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4665 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4666 if (pcTrigger.count > 0 &&
4667 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4668 pcId.count == 0) {
4669 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004670 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004671 if (res != OK) return res;
4672 }
4673
4674 return OK;
4675}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004676
Emilian Peevb9f83812023-03-17 17:13:07 -07004677bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4678 ATRACE_CALL();
4679 Mutex::Autolock l(mTriggerMutex);
4680 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4681 this->mRotateAndCropOverride);
4682}
4683
4684bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4685 bool overrideToPortrait,
4686 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004687 ATRACE_CALL();
4688
Emilian Peevb9f83812023-03-17 17:13:07 -07004689 if (overrideToPortrait) {
4690 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger3560b7e2022-10-27 12:20:29 -07004691 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4692 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4693 &rotateAndCrop_u8, 1);
4694 return true;
4695 }
4696
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004697 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004698 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4699
4700 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4701 if (rotateAndCropEntry.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07004702 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004703 return false;
4704 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004705 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004706 return true;
4707 }
4708 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004709 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4710 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004711 return true;
4712 }
4713 }
Emilian Peevb9f83812023-03-17 17:13:07 -07004714
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004715 return false;
4716}
4717
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004718bool Camera3Device::RequestThread::overrideTestPattern(
4719 const sp<CaptureRequest> &request) {
4720 ATRACE_CALL();
4721
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004722 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004723
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004724 Mutex::Autolock l(mTriggerMutex);
4725
4726 bool changed = false;
4727
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004728 // For a multi-camera, the physical cameras support the same set of
4729 // test pattern modes as the logical camera.
4730 for (auto& settings : request->mSettingsList) {
4731 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004732
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004733 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4734 int32_t testPatternData[4] = {
4735 settings.mOriginalTestPatternData[0],
4736 settings.mOriginalTestPatternData[1],
4737 settings.mOriginalTestPatternData[2],
4738 settings.mOriginalTestPatternData[3]
4739 };
4740 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4741 testPatternMode = mCameraMute;
4742 testPatternData[0] = 0;
4743 testPatternData[1] = 0;
4744 testPatternData[2] = 0;
4745 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004746 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004747
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004748 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4749 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4750 if (testPatternEntry.count > 0) {
4751 if (testPatternEntry.data.i32[0] != testPatternMode) {
4752 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004753 changed = true;
4754 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004755 } else if (supportTestPatternModeKey) {
4756 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4757 &testPatternMode, 1);
4758 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004759 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004760
4761 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4762 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4763 if (testPatternColor.count >= 4) {
4764 for (size_t i = 0; i < 4; i++) {
4765 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4766 testPatternColor.data.i32[i] = testPatternData[i];
4767 changed = true;
4768 }
4769 }
4770 } else if (supportTestPatternDataKey) {
4771 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4772 testPatternData, 4);
4773 changed = true;
4774 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004775 }
4776
4777 return changed;
4778}
4779
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004780status_t Camera3Device::RequestThread::setHalInterface(
4781 sp<HalInterface> newHalInterface) {
4782 if (newHalInterface.get() == nullptr) {
4783 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4784 return DEAD_OBJECT;
4785 }
4786
4787 mInterface = newHalInterface;
4788
4789 return OK;
4790}
4791
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004792/**
4793 * PreparerThread inner class methods
4794 */
4795
4796Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004797 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004798 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004799}
4800
4801Camera3Device::PreparerThread::~PreparerThread() {
4802 Thread::requestExitAndWait();
4803 if (mCurrentStream != nullptr) {
4804 mCurrentStream->cancelPrepare();
4805 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4806 mCurrentStream.clear();
4807 }
4808 clear();
4809}
4810
Ruben Brunkc78ac262015-08-13 17:58:46 -07004811status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004812 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004813 status_t res;
4814
4815 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004816 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004818 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004819 if (res == OK) {
4820 // No preparation needed, fire listener right off
4821 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004822 if (listener != NULL) {
4823 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004824 }
4825 return OK;
4826 } else if (res != NOT_ENOUGH_DATA) {
4827 return res;
4828 }
4829
4830 // Need to prepare, start up thread if necessary
4831 if (!mActive) {
4832 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4833 // isn't running
4834 Thread::requestExitAndWait();
4835 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4836 if (res != OK) {
4837 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004838 if (listener != NULL) {
4839 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004840 }
4841 return res;
4842 }
4843 mCancelNow = false;
4844 mActive = true;
4845 ALOGV("%s: Preparer stream started", __FUNCTION__);
4846 }
4847
4848 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004849 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004850 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4851
4852 return OK;
4853}
4854
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004855void Camera3Device::PreparerThread::pause() {
4856 ATRACE_CALL();
4857
4858 Mutex::Autolock l(mLock);
4859
4860 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4861 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4862 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4863 int currentMaxCount = mCurrentMaxCount;
4864 mPendingStreams.clear();
4865 mCancelNow = true;
4866 while (mActive) {
4867 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4868 if (res == TIMED_OUT) {
4869 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4870 return;
4871 } else if (res != OK) {
4872 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4873 return;
4874 }
4875 }
4876
4877 //Check whether the prepare thread was able to complete the current
4878 //stream. In case work is still pending emplace it along with the rest
4879 //of the streams in the pending list.
4880 if (currentStream != nullptr) {
4881 if (!mCurrentPrepareComplete) {
4882 pendingStreams.emplace(currentMaxCount, currentStream);
4883 }
4884 }
4885
4886 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4887 for (const auto& it : mPendingStreams) {
4888 it.second->cancelPrepare();
4889 }
4890}
4891
4892status_t Camera3Device::PreparerThread::resume() {
4893 ATRACE_CALL();
4894 status_t res;
4895
4896 Mutex::Autolock l(mLock);
4897 sp<NotificationListener> listener = mListener.promote();
4898
4899 if (mActive) {
4900 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4901 return NO_INIT;
4902 }
4903
4904 auto it = mPendingStreams.begin();
4905 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004906 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004907 if (res == OK) {
4908 if (listener != NULL) {
4909 listener->notifyPrepared(it->second->getId());
4910 }
4911 it = mPendingStreams.erase(it);
4912 } else if (res != NOT_ENOUGH_DATA) {
4913 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4914 res, strerror(-res));
4915 it = mPendingStreams.erase(it);
4916 } else {
4917 it++;
4918 }
4919 }
4920
4921 if (mPendingStreams.empty()) {
4922 return OK;
4923 }
4924
4925 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4926 if (res != OK) {
4927 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4928 __FUNCTION__, res, strerror(-res));
4929 return res;
4930 }
4931 mCancelNow = false;
4932 mActive = true;
4933 ALOGV("%s: Preparer stream started", __FUNCTION__);
4934
4935 return OK;
4936}
4937
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004938status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004939 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004940 Mutex::Autolock l(mLock);
4941
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004942 for (const auto& it : mPendingStreams) {
4943 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004944 }
4945 mPendingStreams.clear();
4946 mCancelNow = true;
4947
4948 return OK;
4949}
4950
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004951void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004952 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004953 Mutex::Autolock l(mLock);
4954 mListener = listener;
4955}
4956
4957bool Camera3Device::PreparerThread::threadLoop() {
4958 status_t res;
4959 {
4960 Mutex::Autolock l(mLock);
4961 if (mCurrentStream == nullptr) {
4962 // End thread if done with work
4963 if (mPendingStreams.empty()) {
4964 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4965 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4966 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4967 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004968 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004969 return false;
4970 }
4971
4972 // Get next stream to prepare
4973 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004974 mCurrentStream = it->second;
4975 mCurrentMaxCount = it->first;
4976 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004977 mPendingStreams.erase(it);
4978 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4979 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4980 } else if (mCancelNow) {
4981 mCurrentStream->cancelPrepare();
4982 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4983 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4984 mCurrentStream.clear();
4985 mCancelNow = false;
4986 return true;
4987 }
4988 }
4989
4990 res = mCurrentStream->prepareNextBuffer();
4991 if (res == NOT_ENOUGH_DATA) return true;
4992 if (res != OK) {
4993 // Something bad happened; try to recover by cancelling prepare and
4994 // signalling listener anyway
4995 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4996 mCurrentStream->getId(), res, strerror(-res));
4997 mCurrentStream->cancelPrepare();
4998 }
4999
5000 // This stream has finished, notify listener
5001 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005002 sp<NotificationListener> listener = mListener.promote();
5003 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005004 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5005 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005006 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005007 }
5008
5009 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5010 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005011 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005012
5013 return true;
5014}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005015
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005016status_t Camera3Device::RequestBufferStateMachine::initialize(
5017 sp<camera3::StatusTracker> statusTracker) {
5018 if (statusTracker == nullptr) {
5019 ALOGE("%s: statusTracker is null", __FUNCTION__);
5020 return BAD_VALUE;
5021 }
5022
5023 std::lock_guard<std::mutex> lock(mLock);
5024 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005025 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005026 return OK;
5027}
5028
5029bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5030 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005031 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005032 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005033 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005034 return true;
5035 }
5036 return false;
5037}
5038
5039void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5040 std::lock_guard<std::mutex> lock(mLock);
5041 if (!mRequestBufferOngoing) {
5042 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5043 return;
5044 }
5045 mRequestBufferOngoing = false;
5046 if (mStatus == RB_STATUS_PENDING_STOP) {
5047 checkSwitchToStopLocked();
5048 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005049 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005050}
5051
5052void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5053 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005054 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005055 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005056 return;
5057}
5058
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005059void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005060 std::lock_guard<std::mutex> lock(mLock);
5061 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005062 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5063 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005064 mInflightMapEmpty = false;
5065 if (mStatus == RB_STATUS_STOPPED) {
5066 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005067 }
5068 return;
5069}
5070
5071void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5072 std::lock_guard<std::mutex> lock(mLock);
5073 mRequestThreadPaused = true;
5074 if (mStatus == RB_STATUS_PENDING_STOP) {
5075 checkSwitchToStopLocked();
5076 }
5077 return;
5078}
5079
5080void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5081 std::lock_guard<std::mutex> lock(mLock);
5082 mInflightMapEmpty = true;
5083 if (mStatus == RB_STATUS_PENDING_STOP) {
5084 checkSwitchToStopLocked();
5085 }
5086 return;
5087}
5088
5089void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5090 std::lock_guard<std::mutex> lock(mLock);
5091 if (!checkSwitchToStopLocked()) {
5092 mStatus = RB_STATUS_PENDING_STOP;
5093 }
5094 return;
5095}
5096
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005097bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5098 std::lock_guard<std::mutex> lock(mLock);
5099 if (mRequestBufferOngoing) {
5100 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5101 __FUNCTION__);
5102 return false;
5103 }
5104 mSwitchedToOffline = true;
5105 mInflightMapEmpty = true;
5106 mRequestThreadPaused = true;
5107 mStatus = RB_STATUS_STOPPED;
5108 return true;
5109}
5110
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005111void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5112 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5113 if (statusTracker != nullptr) {
5114 if (active) {
5115 statusTracker->markComponentActive(mRequestBufferStatusId);
5116 } else {
5117 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5118 }
5119 }
5120}
5121
5122bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5123 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5124 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005125 return true;
5126 }
5127 return false;
5128}
5129
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005130bool Camera3Device::startRequestBuffer() {
5131 return mRequestBufferSM.startRequestBuffer();
5132}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005133
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005134void Camera3Device::endRequestBuffer() {
5135 mRequestBufferSM.endRequestBuffer();
5136}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005137
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005138nsecs_t Camera3Device::getWaitDuration() {
5139 return kBaseGetBufferWait + getExpectedInFlightDuration();
5140}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005141
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005142void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5143 mInterface->getInflightBufferKeys(out);
5144}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005145
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005146void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5147 mInterface->getInflightRequestBufferKeys(out);
5148}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005149
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005150std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5151 std::vector<sp<Camera3StreamInterface>> ret;
5152 bool hasInputStream = mInputStream != nullptr;
5153 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5154 if (hasInputStream) {
5155 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005156 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005157 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5158 ret.push_back(mOutputStreams[i]);
5159 }
5160 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5161 ret.push_back(mDeletedStreams[i]);
5162 }
5163 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005164}
5165
Emilian Peevcc0b7952020-01-07 13:54:47 -08005166void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5167 ATRACE_CALL();
5168
5169 if (offlineStreamIds == nullptr) {
5170 return;
5171 }
5172
5173 Mutex::Autolock il(mInterfaceLock);
5174
5175 auto streamIds = mOutputStreams.getStreamIds();
5176 bool hasInputStream = mInputStream != nullptr;
5177 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5178 offlineStreamIds->push_back(mInputStream->getId());
5179 }
5180
5181 for (const auto & streamId : streamIds) {
5182 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5183 // Streams that use the camera buffer manager are currently not supported in
5184 // offline mode
5185 if (stream->getOfflineProcessingSupport() &&
5186 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5187 offlineStreamIds->push_back(streamId);
5188 }
5189 }
5190}
5191
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005192status_t Camera3Device::setRotateAndCropAutoBehavior(
5193 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5194 ATRACE_CALL();
5195 Mutex::Autolock il(mInterfaceLock);
5196 Mutex::Autolock l(mLock);
5197 if (mRequestThread == nullptr) {
5198 return INVALID_OPERATION;
5199 }
Emilian Peevb9f83812023-03-17 17:13:07 -07005200 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5201 return BAD_VALUE;
5202 }
5203 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005204 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5205}
5206
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005207bool Camera3Device::supportsCameraMute() {
5208 Mutex::Autolock il(mInterfaceLock);
5209 Mutex::Autolock l(mLock);
5210
5211 return mSupportCameraMute;
5212}
5213
5214status_t Camera3Device::setCameraMute(bool enabled) {
5215 ATRACE_CALL();
5216 Mutex::Autolock il(mInterfaceLock);
5217 Mutex::Autolock l(mLock);
5218
5219 if (mRequestThread == nullptr || !mSupportCameraMute) {
5220 return INVALID_OPERATION;
5221 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005222 int32_t muteMode =
5223 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5224 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5225 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5226 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005227}
5228
Austin Borger0fb3ad92023-06-01 16:51:35 -07005229status_t Camera3Device::injectCamera(const std::string& injectedCamId,
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005230 sp<CameraProviderManager> manager) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07005231 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.c_str());
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005232 ATRACE_CALL();
5233 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005234 // When the camera device is active, injectCamera() and stopInjection() will call
5235 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5236 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5237 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5238 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5239 // waitUntilStateThenRelock().
5240 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005241
5242 status_t res = NO_ERROR;
5243 if (mInjectionMethods->isInjecting()) {
5244 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5245 return OK;
5246 } else {
5247 res = mInjectionMethods->stopInjection();
5248 if (res != OK) {
5249 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5250 __FUNCTION__, res);
5251 return res;
5252 }
5253 }
5254 }
5255
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005256 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005257 if (res != OK) {
5258 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5259 __FUNCTION__, res);
5260 return res;
5261 }
5262
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005263 // When the second display of android is cast to the remote device, and the opened camera is
5264 // also cast to the second display, in this case, because the camera has configured the streams
5265 // at this time, we can directly call injectCamera() to replace the internal camera with
5266 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005267 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5268 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5269
5270 camera3::camera_stream_configuration injectionConfig;
5271 std::vector<uint32_t> injectionBufferSizes;
5272 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5273 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5274 || injectionBufferSizes.size() <= 0) {
5275 ALOGE("Failed to inject camera due to abandoned configuration! "
5276 "mOperatingMode: %d injectionConfig.num_streams: %d "
5277 "injectionBufferSizes.size(): %zu", mOperatingMode,
5278 injectionConfig.num_streams, injectionBufferSizes.size());
5279 return DEAD_OBJECT;
5280 }
5281
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005282 res = mInjectionMethods->injectCamera(
5283 injectionConfig, injectionBufferSizes);
5284 if (res != OK) {
5285 ALOGE("Can't finish inject camera process!");
5286 return res;
5287 }
5288 }
5289
5290 return OK;
5291}
5292
5293status_t Camera3Device::stopInjection() {
5294 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5295 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005296 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005297 return mInjectionMethods->stopInjection();
5298}
5299
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005300void Camera3Device::overrideStreamUseCaseLocked() {
5301 if (mStreamUseCaseOverrides.size() == 0) {
5302 return;
5303 }
5304
5305 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5306 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5307 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5308 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5309 outputStreamsIndices[i] = i;
5310 }
5311
5312 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5313 [&](int a, int b) -> bool {
5314
5315 auto formatScore = [](int format) {
5316 switch (format) {
5317 case HAL_PIXEL_FORMAT_BLOB:
5318 return 4;
5319 case HAL_PIXEL_FORMAT_RAW16:
5320 case HAL_PIXEL_FORMAT_RAW10:
5321 case HAL_PIXEL_FORMAT_RAW12:
5322 return 3;
5323 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5324 return 2;
5325 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5326 return 1;
5327 default:
5328 return 0;
5329 }
5330 };
5331
5332 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5333 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5334 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5335 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5336 if (sizeA > sizeB ||
5337 (sizeA == sizeB && formatAScore >= formatBScore)) {
5338 return true;
5339 } else {
5340 return false;
5341 }
5342 });
5343
5344 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5345 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5346 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5347 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5348 }
5349}
5350
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005351}; // namespace android