blob: 4935abfa48341027003faa4108c19a4645887dbe [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
Shuzhen Wangf85aa942023-08-21 15:07:24 -07002257 // Make sure status tracker is flushed
2258 mStatusTracker->flushPendingStates();
2259
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002260 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002261 if (checkAbandonedStreamsLocked()) {
2262 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2263 __FUNCTION__);
2264 return true;
2265 }
2266
Emilian Peev3bead5f2020-05-28 17:29:08 -07002267 status_t rc = NO_ERROR;
2268 bool markClientActive = false;
2269 if (mStatus == STATUS_ACTIVE) {
2270 markClientActive = true;
2271 mPauseStateNotify = true;
2272 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2273
2274 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2275 }
2276
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002277 if (rc == NO_ERROR) {
2278 mNeedConfig = true;
2279 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2280 if (rc == NO_ERROR) {
2281 ret = true;
2282 mPauseStateNotify = false;
2283 //Moving to active state while holding 'mLock' is important.
2284 //There could be pending calls to 'create-/deleteStream' which
2285 //will trigger another stream configuration while the already
2286 //present streams end up with outstanding buffers that will
2287 //not get drained.
2288 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002289 } else if (rc == DEAD_OBJECT) {
2290 // DEAD_OBJECT can be returned if either the consumer surface is
2291 // abandoned, or the HAL has died.
2292 // - If the HAL has died, configureStreamsLocked call will set
2293 // device to error state,
2294 // - If surface is abandoned, we should not set device to error
2295 // state.
2296 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002297 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002298 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002299 }
2300 } else {
2301 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2302 }
2303
Shuzhen Wang316781a2020-08-18 18:11:01 -07002304 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2305 ns2ms(systemTime() - startTime));
2306
Emilian Peev3bead5f2020-05-28 17:29:08 -07002307 if (markClientActive) {
2308 mStatusTracker->markComponentActive(clientStatusId);
2309 }
2310
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002311 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002312}
2313
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002314status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002315 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 ATRACE_CALL();
2317 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002318
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002319 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002320 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002321 return INVALID_OPERATION;
2322 }
2323
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002324 if (operatingMode < 0) {
2325 CLOGE("Invalid operating mode: %d", operatingMode);
2326 return BAD_VALUE;
2327 }
2328
2329 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002330 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002331
2332 if (mOperatingMode != operatingMode) {
2333 mNeedConfig = true;
2334 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2335 mOperatingMode = operatingMode;
2336 }
2337
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002338 // Reset min expected duration when session is reconfigured.
2339 mMinExpectedDuration = 0;
2340
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002341 // In case called from configureStreams, abort queued input buffers not belonging to
2342 // any pending requests.
2343 if (mInputStream != NULL && notifyRequestThread) {
2344 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002345 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002346 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002347 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002348 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002349 if (res != OK) {
2350 // Exhausted acquiring all input buffers.
2351 break;
2352 }
2353
Emilian Peevf4816702020-04-03 15:44:51 -07002354 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002355 res = mInputStream->returnInputBuffer(inputBuffer);
2356 if (res != OK) {
2357 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2358 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2359 }
2360 }
2361 }
2362
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002363 if (!mNeedConfig) {
2364 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2365 return OK;
2366 }
2367
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002368 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002369 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002370 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2371 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002372 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002373 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002374 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002375 }
2376
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08002377 // Override stream use case based on "adb shell command"
2378 overrideStreamUseCaseLocked();
2379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380 // Start configuring the streams
Austin Borger0fb3ad92023-06-01 16:51:35 -07002381 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.c_str());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002383 mPreparerThread->pause();
2384
Emilian Peevf4816702020-04-03 15:44:51 -07002385 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002386 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002387 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002388 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389
Emilian Peevf4816702020-04-03 15:44:51 -07002390 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002392 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002393
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394
2395 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002396 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 inputStream = mInputStream->startConfiguration();
2398 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002399 CLOGE("Can't start input stream configuration");
2400 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 return INVALID_OPERATION;
2402 }
2403 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002404
2405 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 }
2407
Shuzhen Wang99080502021-03-07 21:08:20 -08002408 mGroupIdPhysicalCameraMap.clear();
Emilian Peevb9f83812023-03-17 17:13:07 -07002409 mComposerOutput = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002410 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002411
2412 // Don't configure bidi streams twice, nor add them twice to the list
2413 if (mOutputStreams[i].get() ==
2414 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2415
2416 config.num_streams--;
2417 continue;
2418 }
2419
Emilian Peevf4816702020-04-03 15:44:51 -07002420 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002421 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002422 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002423 CLOGE("Can't start output stream configuration");
2424 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 return INVALID_OPERATION;
2426 }
2427 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002428
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002429 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002430 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2431 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002432 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2433 bufferSizes[k] = static_cast<uint32_t>(
Austin Borger0fb3ad92023-06-01 16:51:35 -07002434 getJpegBufferSize(infoPhysical(outputStream->physical_camera_id),
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002435 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002436 } else if (outputStream->data_space ==
2437 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2438 bufferSizes[k] = outputStream->width * outputStream->height;
2439 } else {
2440 ALOGW("%s: Blob dataSpace %d not supported",
2441 __FUNCTION__, outputStream->data_space);
2442 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002443 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002444
2445 if (mOutputStreams[i]->isMultiResolution()) {
2446 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
Austin Borger0fb3ad92023-06-01 16:51:35 -07002447 const std::string &physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08002448 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2449 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002450
2451 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
Emilian Peevb9f83812023-03-17 17:13:07 -07002452 mComposerOutput = true;
Emilian Peeve23f1d92021-09-20 14:56:01 -07002453 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002454 }
2455
2456 config.streams = streams.editArray();
2457
2458 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002459 // max_buffers, usage, and priv fields, as well as data_space and format
2460 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002461
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002462 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002463 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002464 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002465
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002466 if (res == BAD_VALUE) {
2467 // HAL rejected this set of streams as unsupported, clean up config
2468 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002469 CLOGE("Set of requested inputs/outputs not supported by HAL");
2470 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002471 return BAD_VALUE;
2472 } else if (res != OK) {
2473 // Some other kind of error from configure_streams - this is not
2474 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002475 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2476 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002477 return res;
2478 }
2479
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002480 // Finish all stream configuration immediately.
2481 // TODO: Try to relax this later back to lazy completion, which should be
2482 // faster
2483
Igor Murashkin073f8572013-05-02 14:59:28 -07002484 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002485 bool streamReConfigured = false;
2486 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002487 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002488 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002489 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002490 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002491 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2492 return DEAD_OBJECT;
2493 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002494 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002495 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002496 if (streamReConfigured) {
2497 mInterface->onStreamReConfigured(mInputStream->getId());
2498 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002499 }
2500
2501 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002502 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002503 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002504 bool streamReConfigured = false;
2505 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002506 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002507 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002508 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002509 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002510 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2511 return DEAD_OBJECT;
2512 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002513 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002514 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002515 if (streamReConfigured) {
2516 mInterface->onStreamReConfigured(outputStream->getId());
2517 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002518 }
2519 }
2520
Emilian Peevb9f83812023-03-17 17:13:07 -07002521 mRequestThread->setComposerSurface(mComposerOutput);
Emilian Peeve23f1d92021-09-20 14:56:01 -07002522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002523 // Request thread needs to know to avoid using repeat-last-settings protocol
2524 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002525 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002526 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2527 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529
Zhijun He90f7c372016-08-16 16:19:43 -07002530 char value[PROPERTY_VALUE_MAX];
2531 property_get("camera.fifo.disable", value, "0");
2532 int32_t disableFifo = atoi(value);
2533 if (disableFifo != 1) {
2534 // Boost priority of request thread to SCHED_FIFO.
2535 pid_t requestThreadTid = mRequestThread->getTid();
2536 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002537 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002538 if (res != OK) {
2539 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2540 strerror(-res), res);
2541 } else {
2542 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2543 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002544 }
2545
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002546 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002547 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2548 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2549 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2550 sessionParams.unlock(newSessionParams);
2551 mSessionParams.unlock(currentSessionParams);
2552 if (updateSessionParams) {
2553 mSessionParams = sessionParams;
2554 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002555
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002556 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002557
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002558 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002559 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002560
Austin Borger0fb3ad92023-06-01 16:51:35 -07002561 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.c_str());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002562
Zhijun He0a210512014-07-24 13:45:15 -07002563 // tear down the deleted streams after configure streams.
2564 mDeletedStreams.clear();
2565
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002566 auto rc = mPreparerThread->resume();
2567 if (rc != OK) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07002568 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.c_str());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002569 return rc;
2570 }
2571
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002572 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002573 mRequestBufferSM.onStreamsConfigured();
2574 }
2575
Cliff Wu3b268182021-07-06 15:44:43 +08002576 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002577 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002578 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002579 // configure the injection streams.
2580 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002581 ALOGD("%s: Injection camera %s: Start to configure streams.",
Austin Borger0fb3ad92023-06-01 16:51:35 -07002582 __FUNCTION__, mInjectionMethods->getInjectedCamId().c_str());
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002583 res = mInjectionMethods->injectCamera(config, bufferSizes);
2584 if (res != OK) {
2585 ALOGE("Can't finish inject camera process!");
2586 return res;
2587 }
Cliff Wu3b268182021-07-06 15:44:43 +08002588 } else {
2589 // First run configureStreamsLocked() and then call injectCamera() case:
2590 // If the stream configuration has been completed and camera deive is active, but the
2591 // injection camera has not been injected yet, we need to store the stream configuration of
2592 // the internal camera (because the stream configuration of the injection camera is based
2593 // on the internal camera). When injecting occurs later, this configuration can be used by
2594 // the injection camera.
2595 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2596 " injection camera has not been injected yet.", __FUNCTION__);
2597 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002598 }
2599
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002601}
2602
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002603status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002604 ATRACE_CALL();
2605 status_t res;
2606
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002607 if (mFakeStreamId != NO_STREAM) {
2608 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002609 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002610 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Austin Borger0fb3ad92023-06-01 16:51:35 -07002611 __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002612 return INVALID_OPERATION;
2613 }
2614
Austin Borger0fb3ad92023-06-01 16:51:35 -07002615 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 sp<Camera3OutputStreamInterface> fakeStream =
2618 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002620 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002621 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002622 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002623 return res;
2624 }
2625
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002626 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002627 mNextStreamId++;
2628
2629 return OK;
2630}
2631
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002632status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002633 ATRACE_CALL();
2634 status_t res;
2635
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002636 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002637 if (mOutputStreams.size() == 1) return OK;
2638
Austin Borger0fb3ad92023-06-01 16:51:35 -07002639 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.c_str());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002640
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 // Ok, have a fake stream and there's at least one other output stream,
2642 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002643
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002644 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002645 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 return INVALID_OPERATION;
2648 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650
2651 // Free up the stream endpoint so that it can be used by some other stream
2652 res = deletedStream->disconnect();
2653 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002654 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002655 // fall through since we want to still list the stream as deleted.
2656 }
2657 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002658 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002659
2660 return res;
2661}
2662
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002663void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002664 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002665 Mutex::Autolock l(mLock);
2666 va_list args;
2667 va_start(args, fmt);
2668
2669 setErrorStateLockedV(fmt, args);
2670
2671 va_end(args);
2672}
2673
2674void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002675 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002676 Mutex::Autolock l(mLock);
2677 setErrorStateLockedV(fmt, args);
2678}
2679
2680void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2681 va_list args;
2682 va_start(args, fmt);
2683
2684 setErrorStateLockedV(fmt, args);
2685
2686 va_end(args);
2687}
2688
2689void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002690 // Print out all error messages to log
Austin Borger0fb3ad92023-06-01 16:51:35 -07002691 std::string errorCause;
2692 base::StringAppendV(&errorCause, fmt, args);
2693 ALOGE("Camera %s: %s", mId.c_str(), errorCause.c_str());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002694
2695 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002696 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002697
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002698 mErrorCause = errorCause;
2699
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002700 if (mRequestThread != nullptr) {
2701 mRequestThread->setPaused(true);
2702 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002703 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002704
2705 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002706 sp<NotificationListener> listener = mListener.promote();
2707 if (listener != NULL) {
2708 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002709 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002710 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002711 }
2712
2713 // Save stack trace. View by dumping it later.
2714 CameraTraces::saveTrace();
2715 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002716}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717
2718/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002719 * In-flight request management
2720 */
2721
Jianing Weicb0652e2014-03-12 18:29:36 -07002722status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002723 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002724 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Austin Borger0fb3ad92023-06-01 16:51:35 -07002725 bool isFixedFps, const std::set<std::set<std::string>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002726 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2727 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002728 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002729 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002730 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002731
2732 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002733 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002734 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002735 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2736 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002737 if (res < 0) return res;
2738
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002739 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002740 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2741 // avoid a deadlock during reprocess requests.
2742 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002743 if (mStatusTracker != nullptr) {
2744 mStatusTracker->markComponentActive(mInFlightStatusId);
2745 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002746 }
2747
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002748 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002749 return OK;
2750}
2751
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002752void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002753 // Indicate idle inFlightMap to the status tracker
2754 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002755 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002756 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2757 // avoid a deadlock during reprocess requests.
2758 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002759 if (mStatusTracker != nullptr) {
2760 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2761 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002762 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002763 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002764}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002765
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002766void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002767 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002768 // something has likely gone wrong. This might still be legit only if application send in
2769 // a long burst of long exposure requests.
2770 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2771 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2772 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2773 mInFlightMap.size(), mExpectedInflightDuration);
2774 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2775 kInFlightWarnLimitHighSpeed) {
2776 CLOGW("In-flight list too large for high speed configuration: %zu,"
2777 "total inflight duration %" PRIu64,
2778 mInFlightMap.size(), mExpectedInflightDuration);
2779 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002780 }
2781}
2782
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002783void Camera3Device::onInflightMapFlushedLocked() {
2784 mExpectedInflightDuration = 0;
2785}
2786
2787void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002788 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002789 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2790 mInFlightMap.removeItemsAt(idx, 1);
2791
2792 onInflightEntryRemovedLocked(duration);
2793}
2794
2795
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002796void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002797 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002798 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002799 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002801 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002802 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002803
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002804 FlushInflightReqStates states {
2805 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002806 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002807
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002808 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002809}
2810
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002811CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002812 ALOGV("%s", __FUNCTION__);
2813
Igor Murashkin1e479c02013-09-06 16:55:14 -07002814 CameraMetadata retVal;
2815
2816 if (mRequestThread != NULL) {
2817 retVal = mRequestThread->getLatestRequest();
2818 }
2819
Igor Murashkin1e479c02013-09-06 16:55:14 -07002820 return retVal;
2821}
2822
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002823void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002824 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002825 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002826 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2827 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002828
2829 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002830 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002831}
2832
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002833void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002834 std::vector<native_handle_t*> *handles, bool closeFd) {
2835 if (handles == nullptr) {
2836 return;
2837 }
2838 if (closeFd) {
2839 for (auto& handle : *handles) {
2840 native_handle_close(handle);
2841 }
2842 }
2843 for (auto& handle : *handles) {
2844 native_handle_delete(handle);
2845 }
2846 handles->clear();
2847 return;
2848}
2849
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002850/**
2851 * HalInterface inner class methods
2852 */
2853
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002854void Camera3Device::HalInterface::getInflightBufferKeys(
2855 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002856 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002857 return;
2858}
2859
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002860void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2861 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002862 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002863 return;
2864}
2865
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002866bool Camera3Device::HalInterface::verifyBufferIds(
2867 int32_t streamId, std::vector<uint64_t>& bufIds) {
2868 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002869}
2870
2871status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002872 int32_t frameNumber, int32_t streamId,
2873 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002874 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002875}
2876
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002877status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002878 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002879 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002880}
2881
2882// Find and pop a buffer_handle_t based on bufferId
2883status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002884 uint64_t bufferId,
2885 /*out*/ buffer_handle_t** buffer,
2886 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002887 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002888}
2889
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002890std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2891 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002892 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002893}
2894
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002895uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2896 const native_handle_t* handle) {
2897 return mBufferRecords.removeOneBufferCache(streamId, handle);
2898}
2899
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002900void Camera3Device::HalInterface::onBufferFreed(
2901 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002902 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2903 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2904 if (bufferId != BUFFER_ID_NO_BUFFER) {
2905 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002906 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002907}
2908
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002909void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002910 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2911 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2912 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002913 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2914 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002915}
2916
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002917/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002918 * RequestThread inner class methods
2919 */
2920
2921Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002922 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002923 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002924 bool useHalBufManager,
Austin Borger3560b7e2022-10-27 12:20:29 -07002925 bool supportCameraMute,
2926 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002927 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002928 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002929 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002930 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002931 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002932 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002933 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002934 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002935 mReconfigured(false),
2936 mDoPause(false),
2937 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002938 mNotifyPipelineDrain(false),
Kwangkyu Park453a66a2023-09-04 18:53:06 +09002939 mPrevTriggers(0),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002940 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002941 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002942 mCurrentAfTriggerId(0),
2943 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002944 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002945 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002946 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002947 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002948 mRepeatingLastFrameNumber(
2949 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002950 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002951 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002952 mRequestLatency(kRequestLatencyBinSize),
2953 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002954 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002955 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002956 mSupportCameraMute(supportCameraMute),
2957 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002958 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002959}
2960
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002961Camera3Device::RequestThread::~RequestThread() {}
2962
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002963void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002964 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002965 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002966 Mutex::Autolock l(mRequestLock);
2967 mListener = listener;
2968}
2969
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002970void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002971 const CameraMetadata& sessionParams,
Austin Borger0fb3ad92023-06-01 16:51:35 -07002972 const std::map<int32_t, std::set<std::string>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002973 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974 Mutex::Autolock l(mRequestLock);
2975 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002976 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002977 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002978 // Prepare video stream for high speed recording.
2979 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002980 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002981}
2982
Jianing Wei90e59c92014-03-12 18:29:36 -07002983status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002984 List<sp<CaptureRequest> > &requests,
2985 /*out*/
2986 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002987 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002988 Mutex::Autolock l(mRequestLock);
2989 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2990 ++it) {
2991 mRequestQueue.push_back(*it);
2992 }
2993
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002994 if (lastFrameNumber != NULL) {
2995 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2996 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2997 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2998 *lastFrameNumber);
2999 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003000
Jianing Wei90e59c92014-03-12 18:29:36 -07003001 unpauseForNewRequests();
3002
3003 return OK;
3004}
3005
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003006
3007status_t Camera3Device::RequestThread::queueTrigger(
3008 RequestTrigger trigger[],
3009 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003010 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003011 Mutex::Autolock l(mTriggerMutex);
3012 status_t ret;
3013
3014 for (size_t i = 0; i < count; ++i) {
3015 ret = queueTriggerLocked(trigger[i]);
3016
3017 if (ret != OK) {
3018 return ret;
3019 }
3020 }
3021
3022 return OK;
3023}
3024
Austin Borger0fb3ad92023-06-01 16:51:35 -07003025const std::string& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3026 static std::string deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003027 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003028 if (d != nullptr) return d->mId;
3029 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003030}
3031
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003032status_t Camera3Device::RequestThread::queueTriggerLocked(
3033 RequestTrigger trigger) {
3034
3035 uint32_t tag = trigger.metadataTag;
3036 ssize_t index = mTriggerMap.indexOfKey(tag);
3037
3038 switch (trigger.getTagType()) {
3039 case TYPE_BYTE:
3040 // fall-through
3041 case TYPE_INT32:
3042 break;
3043 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003044 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3045 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003046 return INVALID_OPERATION;
3047 }
3048
3049 /**
3050 * Collect only the latest trigger, since we only have 1 field
3051 * in the request settings per trigger tag, and can't send more than 1
3052 * trigger per request.
3053 */
3054 if (index != NAME_NOT_FOUND) {
3055 mTriggerMap.editValueAt(index) = trigger;
3056 } else {
3057 mTriggerMap.add(tag, trigger);
3058 }
3059
3060 return OK;
3061}
3062
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003063status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003064 const RequestList &requests,
3065 /*out*/
3066 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003067 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003068 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003069 if (lastFrameNumber != NULL) {
3070 *lastFrameNumber = mRepeatingLastFrameNumber;
3071 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003072 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003073 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003074 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3075 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003076
3077 unpauseForNewRequests();
3078
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003079 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003080 return OK;
3081}
3082
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003083bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003084 if (mRepeatingRequests.empty()) {
3085 return false;
3086 }
3087 int32_t requestId = requestIn->mResultExtras.requestId;
3088 const RequestList &repeatRequests = mRepeatingRequests;
3089 // All repeating requests are guaranteed to have same id so only check first quest
3090 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3091 return (firstRequest->mResultExtras.requestId == requestId);
3092}
3093
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003094status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003095 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003096 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003097 return clearRepeatingRequestsLocked(lastFrameNumber);
3098
3099}
3100
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003101status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3102 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003103 std::vector<int32_t> streamIds;
3104 for (const auto& request : mRepeatingRequests) {
3105 for (const auto& stream : request->mOutputStreams) {
3106 streamIds.push_back(stream->getId());
3107 }
3108 }
3109
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003110 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003111 if (lastFrameNumber != NULL) {
3112 *lastFrameNumber = mRepeatingLastFrameNumber;
3113 }
Emilian Peev2295df72021-11-12 18:14:10 -08003114
3115 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3116
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003117 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003118 return OK;
3119}
3120
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003121status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003122 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003123 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003124 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003125 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003126
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003127 // Send errors for all requests pending in the request queue, including
3128 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003129 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003130 if (listener != NULL) {
3131 for (RequestList::iterator it = mRequestQueue.begin();
3132 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003133 // Abort the input buffers for reprocess requests.
3134 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003135 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003136 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003137 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003138 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003139 if (res != OK) {
3140 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3141 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3142 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003143 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003144 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3145 if (res != OK) {
3146 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3147 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3148 }
3149 }
3150 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003151 // Set the frame number this request would have had, if it
3152 // had been submitted; this frame number will not be reused.
3153 // The requestId and burstId fields were set when the request was
3154 // submitted originally (in convertMetadataListToRequestListLocked)
3155 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003156 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003157 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003158 }
3159 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003160 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003161
3162 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003163 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003164 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003165 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003166 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003167 return OK;
3168}
3169
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003170status_t Camera3Device::RequestThread::flush() {
3171 ATRACE_CALL();
3172 Mutex::Autolock l(mFlushLock);
3173
Emilian Peev08dd2452017-04-06 16:55:14 +01003174 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003175}
3176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003177void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003178 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003179 Mutex::Autolock l(mPauseLock);
3180 mDoPause = paused;
3181 mDoPauseSignal.signal();
3182}
3183
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003184status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3185 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003186 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003187 Mutex::Autolock l(mLatestRequestMutex);
3188 status_t res;
3189 while (mLatestRequestId != requestId) {
3190 nsecs_t startTime = systemTime();
3191
3192 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3193 if (res != OK) return res;
3194
3195 timeout -= (systemTime() - startTime);
3196 }
3197
3198 return OK;
3199}
3200
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003201void Camera3Device::RequestThread::requestExit() {
3202 // Call parent to set up shutdown
3203 Thread::requestExit();
3204 // The exit from any possible waits
3205 mDoPauseSignal.signal();
3206 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003207
3208 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3209 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003210}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003211
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003212void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003213 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003214 bool surfaceAbandoned = false;
3215 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003216 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003217 {
3218 Mutex::Autolock l(mRequestLock);
3219 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3220 // repeating requests.
3221 for (const auto& request : mRepeatingRequests) {
3222 for (const auto& s : request->mOutputStreams) {
3223 if (s->isAbandoned()) {
3224 surfaceAbandoned = true;
3225 clearRepeatingRequestsLocked(&lastFrameNumber);
3226 break;
3227 }
3228 }
3229 if (surfaceAbandoned) {
3230 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003231 }
3232 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003233 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003234 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003235
3236 if (listener != NULL && surfaceAbandoned) {
3237 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003238 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003239}
3240
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003241bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003242 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003243 status_t res;
3244 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003245 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003246 uint32_t numRequestProcessed = 0;
3247 for (size_t i = 0; i < batchSize; i++) {
3248 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003249 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003250 }
3251
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003252 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3253
3254 bool triggerRemoveFailed = false;
3255 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3256 for (size_t i = 0; i < numRequestProcessed; i++) {
3257 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3258 nextRequest.submitted = true;
3259
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003260 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003261
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003262 if (!triggerRemoveFailed) {
3263 // Remove any previously queued triggers (after unlock)
3264 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3265 if (removeTriggerRes != OK) {
3266 triggerRemoveFailed = true;
3267 triggerFailedRequest = nextRequest;
3268 }
3269 }
3270 }
3271
3272 if (triggerRemoveFailed) {
3273 SET_ERR("RequestThread: Unable to remove triggers "
3274 "(capture request %d, HAL device: %s (%d)",
3275 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3276 cleanUpFailedRequests(/*sendRequestError*/ false);
3277 return false;
3278 }
3279
3280 if (res != OK) {
3281 // Should only get a failure here for malformed requests or device-level
3282 // errors, so consider all errors fatal. Bad metadata failures should
3283 // come through notify.
3284 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3285 mNextRequests[numRequestProcessed].halRequest.frame_number,
3286 strerror(-res), res);
3287 cleanUpFailedRequests(/*sendRequestError*/ false);
3288 return false;
3289 }
3290 return true;
3291}
3292
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003293Camera3Device::RequestThread::ExpectedDurationInfo
3294 Camera3Device::RequestThread::calculateExpectedDurationRange(
3295 const camera_metadata_t *request) {
3296 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003297 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003298 InFlightRequest::kDefaultMaxExpectedDuration,
3299 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003300 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3301 find_camera_metadata_ro_entry(request,
3302 ANDROID_CONTROL_AE_MODE,
3303 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003304 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003305
3306 switch (e.data.u8[0]) {
3307 case ANDROID_CONTROL_AE_MODE_OFF:
3308 find_camera_metadata_ro_entry(request,
3309 ANDROID_SENSOR_EXPOSURE_TIME,
3310 &e);
3311 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003312 expectedDurationInfo.minDuration = e.data.i64[0];
3313 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003314 }
3315 find_camera_metadata_ro_entry(request,
3316 ANDROID_SENSOR_FRAME_DURATION,
3317 &e);
3318 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003319 expectedDurationInfo.minDuration =
3320 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3321 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003322 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003323 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003324 break;
3325 default:
3326 find_camera_metadata_ro_entry(request,
3327 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3328 &e);
3329 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003330 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3331 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003332 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003333 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003334 break;
3335 }
3336
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003337 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003338}
3339
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003340bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3341 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3342 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3343 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3344 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3345 return true;
3346 }
3347
3348 return false;
3349}
3350
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003351void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3352 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003353 camera_capture_request_t& halRequest = nextRequest.halRequest;
3354 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003355 Mutex::Autolock al(mLatestRequestMutex);
3356
Shuzhen Wang83bff122020-11-20 15:51:39 -08003357 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003358 mLatestRequest.acquire(cloned);
3359
3360 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003361 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3362 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3363 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003364 CameraMetadata(cloned));
3365 }
3366
3367 sp<Camera3Device> parent = mParent.promote();
3368 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003369 int32_t inputStreamId = -1;
3370 if (halRequest.input_buffer != nullptr) {
3371 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3372 }
3373
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003374 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003375 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003376 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3377 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003378 }
3379 }
3380
Shuzhen Wang83bff122020-11-20 15:51:39 -08003381 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003382 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003383 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003384 }
3385
Shuzhen Wang83bff122020-11-20 15:51:39 -08003386 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003387}
3388
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003389bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3390 ATRACE_CALL();
3391 bool updatesDetected = false;
3392
Emilian Peev4ec17882019-01-24 17:16:58 -08003393 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003394 for (auto tag : mSessionParamKeys) {
3395 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003396 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003397
3398 if (entry.count > 0) {
3399 bool isDifferent = false;
3400 if (lastEntry.count > 0) {
3401 // Have a last value, compare to see if changed
3402 if (lastEntry.type == entry.type &&
3403 lastEntry.count == entry.count) {
3404 // Same type and count, compare values
3405 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3406 size_t entryBytes = bytesPerValue * lastEntry.count;
3407 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3408 if (cmp != 0) {
3409 isDifferent = true;
3410 }
3411 } else {
3412 // Count or type has changed
3413 isDifferent = true;
3414 }
3415 } else {
3416 // No last entry, so always consider to be different
3417 isDifferent = true;
3418 }
3419
3420 if (isDifferent) {
3421 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003422 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3423 updatesDetected = true;
3424 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003425 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003426 }
3427 } else if (lastEntry.count > 0) {
3428 // Value has been removed
3429 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003430 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003431 updatesDetected = true;
3432 }
3433 }
3434
Emilian Peev4ec17882019-01-24 17:16:58 -08003435 bool reconfigureRequired;
3436 if (updatesDetected) {
3437 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3438 updatedParams);
3439 mLatestSessionParams = updatedParams;
3440 } else {
3441 reconfigureRequired = false;
3442 }
3443
3444 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003445}
3446
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003447bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003448 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003449 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003450 // Any function called from threadLoop() must not hold mInterfaceLock since
3451 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3452 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003453
3454 // Handle paused state.
3455 if (waitIfPaused()) {
3456 return true;
3457 }
3458
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003459 // Wait for the next batch of requests.
3460 waitForNextRequestBatch();
3461 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003462 return true;
3463 }
3464
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003465 // Get the latest request ID, if any
3466 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003467 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003468 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003469 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003470 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003471 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003472 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3473 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003474 }
3475
Emilian Peevb9f83812023-03-17 17:13:07 -07003476 for (size_t i = 0; i < mNextRequests.size(); i++) {
3477 auto& nextRequest = mNextRequests.editItemAt(i);
3478 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
3479 // Do not override rotate&crop for stream configurations that include
3480 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3481 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3482 captureRequest->mRotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
3483 overrideAutoRotateAndCrop(captureRequest);
3484 }
3485
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003486 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3487 // or a single request from streaming or burst. In either case the first element
3488 // should contain the latest camera settings that we need to check for any session
3489 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003490 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003491 res = OK;
3492
3493 //Input stream buffers are already acquired at this point so an input stream
3494 //will not be able to move to idle state unless we force it.
3495 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3496 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3497 if (res != OK) {
3498 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3499 cleanUpFailedRequests(/*sendRequestError*/ false);
3500 return false;
3501 }
3502 }
3503
3504 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003505 sp<Camera3Device> parent = mParent.promote();
3506 if (parent != nullptr) {
3507 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003508 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003509 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003510
3511 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3512 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3513 if (res != OK) {
3514 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3515 cleanUpFailedRequests(/*sendRequestError*/ false);
3516 return false;
3517 }
3518 }
3519 }
3520 }
3521
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003522 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003523 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003524 if (res == TIMED_OUT) {
3525 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003526 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003527 // Check if any stream is abandoned.
3528 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003529 return true;
3530 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003531 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003532 return false;
3533 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003534
Zhijun Hecc27e112013-10-03 16:12:43 -07003535 // Inform waitUntilRequestProcessed thread of a new request ID
3536 {
3537 Mutex::Autolock al(mLatestRequestMutex);
3538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003539 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003540 mLatestRequestSignal.signal();
3541 }
3542
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003543 // Submit a batch of requests to HAL.
3544 // Use flush lock only when submitting multilple requests in a batch.
3545 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3546 // which may take a long time to finish so synchronizing flush() and
3547 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3548 // For now, only synchronize for high speed recording and we should figure something out for
3549 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003550 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003551
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003552 if (useFlushLock) {
3553 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003554 }
3555
Zhijun Hef0645c12016-08-02 00:58:11 -07003556 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003557 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003558
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003559 sp<Camera3Device> parent = mParent.promote();
3560 if (parent != nullptr) {
3561 parent->mRequestBufferSM.onSubmittingRequest();
3562 }
3563
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003564 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003565 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003566 submitRequestSuccess = sendRequestsBatch();
3567
Shuzhen Wang686f6442017-06-20 16:16:04 -07003568 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3569 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003570
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003571 if (useFlushLock) {
3572 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003573 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003574
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003575 // Unset as current request
3576 {
3577 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003578 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003579 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003580 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003581
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003582 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003583}
3584
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003585status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3586 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3587 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3588 ANDROID_SCALER_CROP_REGION_SET};
3589 if (request == nullptr) {
3590 ALOGE("%s request metadata nullptr", __FUNCTION__);
3591 return BAD_VALUE;
3592 }
3593 status_t res = OK;
3594 for (const auto &key : kFwkOnlyRegionKeys) {
3595 if (request->exists(key)) {
3596 res = request->erase(key);
3597 if (res != OK) {
3598 return res;
3599 }
3600 }
3601 }
3602 return OK;
3603}
3604
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003605status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003606 ATRACE_CALL();
3607
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003608 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003609 for (size_t i = 0; i < mNextRequests.size(); i++) {
3610 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003611 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003612 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3613 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003614
3615 // Prepare a request to HAL
3616 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3617
3618 // Insert any queued triggers (before metadata is locked)
3619 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003620 if (res < 0) {
3621 SET_ERR("RequestThread: Unable to insert triggers "
3622 "(capture request %d, HAL device: %s (%d)",
3623 halRequest->frame_number, strerror(-res), res);
3624 return INVALID_OPERATION;
3625 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003626
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003627 int triggerCount = res;
3628 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3629 mPrevTriggers = triggerCount;
3630
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003631 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003632
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003633 // If the request is the same as last, or we had triggers now or last time or
3634 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003635 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003636 (mPrevRequest != captureRequest || triggersMixedIn ||
Emilian Peevb9f83812023-03-17 17:13:07 -07003637 captureRequest->mRotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003638 // Request settings are all the same within one batch, so only treat the first
3639 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003640 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003641 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003642 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 /**
3644 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003645 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003646 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003647 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003648 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003649 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003650 "(capture request %d, HAL device: %s (%d)",
3651 halRequest->frame_number, strerror(-res), res);
3652 return INVALID_OPERATION;
3653 }
3654
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003655 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003656 sp<Camera3Device> parent = mParent.promote();
3657 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003658 List<PhysicalCameraSettings>::iterator it;
3659 for (it = captureRequest->mSettingsList.begin();
3660 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003661 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3662 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003663 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3664 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3665 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3666 res);
3667 return INVALID_OPERATION;
3668 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003669 continue;
3670 }
3671
3672 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3673 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3674 updateCaptureRequest(&(it->metadata));
3675 if (res != OK) {
3676 SET_ERR("RequestThread: Unable to correct capture requests "
3677 "for scaler crop region and metering regions for request "
3678 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3679 res);
3680 return INVALID_OPERATION;
3681 }
3682 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003683 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3684 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3685 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3686 res);
3687 return INVALID_OPERATION;
3688 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003689 }
3690 }
3691
3692 // Correct metadata regions for distortion correction if enabled
3693 for (it = captureRequest->mSettingsList.begin();
3694 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003695 if (parent->mDistortionMappers.find(it->cameraId) ==
3696 parent->mDistortionMappers.end()) {
3697 continue;
3698 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003699
3700 if (!captureRequest->mDistortionCorrectionUpdated) {
3701 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3702 &(it->metadata));
3703 if (res != OK) {
3704 SET_ERR("RequestThread: Unable to correct capture requests "
3705 "for lens distortion for request %d: %s (%d)",
3706 halRequest->frame_number, strerror(-res), res);
3707 return INVALID_OPERATION;
3708 }
3709 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003710 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003711 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003712
3713 for (it = captureRequest->mSettingsList.begin();
3714 it != captureRequest->mSettingsList.end(); it++) {
3715 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3716 parent->mZoomRatioMappers.end()) {
3717 continue;
3718 }
3719
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003720 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003721 cameraIdsWithZoom.insert(it->cameraId);
3722 }
3723
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003724 if (!captureRequest->mZoomRatioUpdated) {
3725 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3726 &(it->metadata));
3727 if (res != OK) {
3728 SET_ERR("RequestThread: Unable to correct capture requests "
3729 "for zoom ratio for request %d: %s (%d)",
3730 halRequest->frame_number, strerror(-res), res);
3731 return INVALID_OPERATION;
3732 }
3733 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003734 }
3735 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003736 if (captureRequest->mRotateAndCropAuto &&
3737 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003738 for (it = captureRequest->mSettingsList.begin();
3739 it != captureRequest->mSettingsList.end(); it++) {
3740 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3741 if (mapper != parent->mRotateAndCropMappers.end()) {
3742 res = mapper->second.updateCaptureRequest(&(it->metadata));
3743 if (res != OK) {
3744 SET_ERR("RequestThread: Unable to correct capture requests "
3745 "for rotate-and-crop for request %d: %s (%d)",
3746 halRequest->frame_number, strerror(-res), res);
3747 return INVALID_OPERATION;
3748 }
3749 }
3750 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003751 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003752 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003753 }
3754 }
3755
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003756 /**
3757 * The request should be presorted so accesses in HAL
3758 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3759 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003760 captureRequest->mSettingsList.begin()->metadata.sort();
3761 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003762 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003763 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003764 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3765
3766 IF_ALOGV() {
3767 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3768 find_camera_metadata_ro_entry(
3769 halRequest->settings,
3770 ANDROID_CONTROL_AF_TRIGGER,
3771 &e
3772 );
3773 if (e.count > 0) {
3774 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3775 __FUNCTION__,
3776 halRequest->frame_number,
3777 e.data.u8[0]);
3778 }
3779 }
3780 } else {
3781 // leave request.settings NULL to indicate 'reuse latest given'
3782 ALOGVV("%s: Request settings are REUSED",
3783 __FUNCTION__);
3784 }
3785
Emilian Peevaebbe412018-01-15 13:53:24 +00003786 if (captureRequest->mSettingsList.size() > 1) {
3787 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3788 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003789 if (newRequest) {
3790 halRequest->physcam_settings =
3791 new const camera_metadata* [halRequest->num_physcam_settings];
3792 } else {
3793 halRequest->physcam_settings = nullptr;
3794 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003795 auto it = ++captureRequest->mSettingsList.begin();
3796 size_t i = 0;
3797 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3798 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003799 if (newRequest) {
3800 it->metadata.sort();
3801 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3802 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003803 }
3804 }
3805
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003806 uint32_t totalNumBuffers = 0;
3807
3808 // Fill in buffers
3809 if (captureRequest->mInputStream != NULL) {
3810 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003811
3812 halRequest->input_width = captureRequest->mInputBufferSize.width;
3813 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003814 totalNumBuffers += 1;
3815 } else {
3816 halRequest->input_buffer = NULL;
3817 }
3818
Emilian Peevf4816702020-04-03 15:44:51 -07003819 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003820 captureRequest->mOutputStreams.size());
3821 halRequest->output_buffers = outputBuffers->array();
Austin Borger0fb3ad92023-06-01 16:51:35 -07003822 std::set<std::set<std::string>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003823
3824 sp<Camera3Device> parent = mParent.promote();
3825 if (parent == NULL) {
3826 // Should not happen, and nowhere to send errors to, so just log it
3827 CLOGE("RequestThread: Parent is gone");
3828 return INVALID_OPERATION;
3829 }
3830 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3831
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003832 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003833 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003834 sp<Camera3OutputStreamInterface> outputStream =
3835 captureRequest->mOutputStreams.editItemAt(j);
3836 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003837
3838 // Prepare video buffers for high speed recording on the first video request.
3839 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3840 // Only try to prepare video stream on the first video request.
3841 mPrepareVideoStream = false;
3842
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003843 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3844 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003845 while (res == NOT_ENOUGH_DATA) {
3846 res = outputStream->prepareNextBuffer();
3847 }
3848 if (res != OK) {
3849 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3850 __FUNCTION__, strerror(-res), res);
3851 outputStream->cancelPrepare();
3852 }
3853 }
3854
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003855 std::vector<size_t> uniqueSurfaceIds;
3856 res = outputStream->getUniqueSurfaceIds(
3857 captureRequest->mOutputSurfaces[streamId],
3858 &uniqueSurfaceIds);
3859 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3860 if (res != OK && res != INVALID_OPERATION) {
3861 ALOGE("%s: failed to query stream %d unique surface IDs",
3862 __FUNCTION__, streamId);
3863 return res;
3864 }
3865 if (res == OK) {
3866 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3867 }
3868
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003869 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003870 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003871 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003872 return TIMED_OUT;
3873 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003874 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003875 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003876 buffer.stream = outputStream->asHalStream();
3877 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003878 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003879 buffer.acquire_fence = -1;
3880 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003881 // Mark the output stream as unpreparable to block clients from calling
3882 // 'prepare' after this request reaches CameraHal and before the respective
3883 // buffers are requested.
3884 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003885 } else {
3886 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3887 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003888 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003889 if (res != OK) {
3890 // Can't get output buffer from gralloc queue - this could be due to
3891 // abandoned queue or other consumer misbehavior, so not a fatal
3892 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003893 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003894 " %s (%d)", strerror(-res), res);
3895
3896 return TIMED_OUT;
3897 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003898 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003899
3900 {
3901 sp<Camera3Device> parent = mParent.promote();
3902 if (parent != nullptr) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07003903 const std::string& streamCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003904 for (const auto& settings : captureRequest->mSettingsList) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07003905 if ((streamCameraId.empty() &&
3906 parent->getId() == settings.cameraId) ||
3907 streamCameraId == settings.cameraId) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003908 outputStream->fireBufferRequestForFrameNumber(
3909 captureRequest->mResultExtras.frameNumber,
3910 settings.metadata);
3911 }
3912 }
3913 }
3914 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003915
Austin Borger0fb3ad92023-06-01 16:51:35 -07003916 const std::string &physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003917 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3918 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3919 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
Austin Borger0fb3ad92023-06-01 16:51:35 -07003920 } else if (!physicalCameraId.empty()) {
3921 requestedPhysicalCameras.insert(std::set<std::string>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003922 }
3923 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003924 }
3925 totalNumBuffers += halRequest->num_output_buffers;
3926
3927 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003928 // If this request list is for constrained high speed recording (not
3929 // preview), and the current request is not the last one in the batch,
3930 // do not send callback to the app.
3931 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003932 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003933 hasCallback = false;
3934 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003935 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003936 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003937 const camera_metadata_t* settings = halRequest->settings;
3938 bool shouldUnlockSettings = false;
3939 if (settings == nullptr) {
3940 shouldUnlockSettings = true;
3941 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3942 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003943 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3944 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003945 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003946 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3947 isStillCapture = true;
3948 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3949 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003950
Emilian Peevaf8416e2021-02-04 17:52:43 -08003951 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003952 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003953 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3954 isZslCapture = true;
3955 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003956 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003957 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003958 res = parent->registerInFlight(halRequest->frame_number,
3959 totalNumBuffers, captureRequest->mResultExtras,
3960 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003961 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003962 expectedDurationInfo.minDuration,
3963 expectedDurationInfo.maxDuration,
3964 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003965 requestedPhysicalCameras, isStillCapture, isZslCapture,
3966 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003967 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003968 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003969 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3970 ", burstId = %" PRId32 ".",
3971 __FUNCTION__,
3972 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3973 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003974
3975 if (shouldUnlockSettings) {
3976 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3977 }
3978
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003979 if (res != OK) {
3980 SET_ERR("RequestThread: Unable to register new in-flight request:"
3981 " %s (%d)", strerror(-res), res);
3982 return INVALID_OPERATION;
3983 }
3984 }
3985
3986 return OK;
3987}
3988
Igor Murashkin1e479c02013-09-06 16:55:14 -07003989CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003990 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003991 Mutex::Autolock al(mLatestRequestMutex);
3992
3993 ALOGV("RequestThread::%s", __FUNCTION__);
3994
3995 return mLatestRequest;
3996}
3997
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003998bool Camera3Device::RequestThread::isStreamPending(
3999 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004000 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004001 Mutex::Autolock l(mRequestLock);
4002
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004003 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004004 if (!nextRequest.submitted) {
4005 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4006 if (stream == s) return true;
4007 }
4008 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004009 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004010 }
4011
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004012 for (const auto& request : mRequestQueue) {
4013 for (const auto& s : request->mOutputStreams) {
4014 if (stream == s) return true;
4015 }
4016 if (stream == request->mInputStream) return true;
4017 }
4018
4019 for (const auto& request : mRepeatingRequests) {
4020 for (const auto& s : request->mOutputStreams) {
4021 if (stream == s) return true;
4022 }
4023 if (stream == request->mInputStream) return true;
4024 }
4025
4026 return false;
4027}
Jianing Weicb0652e2014-03-12 18:29:36 -07004028
Emilian Peev40ead602017-09-26 15:46:36 +01004029bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4030 ATRACE_CALL();
4031 Mutex::Autolock l(mRequestLock);
4032
4033 for (const auto& nextRequest : mNextRequests) {
4034 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4035 if (s.first == streamId) {
4036 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4037 if (it != s.second.end()) {
4038 return true;
4039 }
4040 }
4041 }
4042 }
4043
4044 for (const auto& request : mRequestQueue) {
4045 for (const auto& s : request->mOutputSurfaces) {
4046 if (s.first == streamId) {
4047 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4048 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004049 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004050 }
4051 }
4052 }
4053 }
4054
4055 for (const auto& request : mRepeatingRequests) {
4056 for (const auto& s : request->mOutputSurfaces) {
4057 if (s.first == streamId) {
4058 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4059 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004060 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004061 }
4062 }
4063 }
4064 }
4065
4066 return false;
4067}
4068
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004069void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4070 if (!mUseHalBufManager) {
4071 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4072 return;
4073 }
4074
4075 Mutex::Autolock pl(mPauseLock);
4076 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004077 mInterface->signalPipelineDrain(streamIds);
4078 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004079 }
4080 // If request thread is still busy, wait until paused then notify HAL
4081 mNotifyPipelineDrain = true;
4082 mStreamIdsToBeDrained = streamIds;
4083}
4084
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004085void Camera3Device::RequestThread::resetPipelineDrain() {
4086 Mutex::Autolock pl(mPauseLock);
4087 mNotifyPipelineDrain = false;
4088 mStreamIdsToBeDrained.clear();
4089}
4090
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004091void Camera3Device::RequestThread::clearPreviousRequest() {
4092 Mutex::Autolock l(mRequestLock);
4093 mPrevRequest.clear();
4094}
4095
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004096status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4097 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4098 ATRACE_CALL();
4099 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004100 mRotateAndCropOverride = rotateAndCropValue;
4101 return OK;
4102}
4103
Emilian Peeve23f1d92021-09-20 14:56:01 -07004104status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4105 ATRACE_CALL();
4106 Mutex::Autolock l(mTriggerMutex);
4107 mComposerOutput = composerSurfacePresent;
4108 return OK;
4109}
4110
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004111status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004112 ATRACE_CALL();
4113 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004114 if (muteMode != mCameraMute) {
4115 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004116 mCameraMuteChanged = true;
4117 }
4118 return OK;
4119}
4120
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004121nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004122 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004123 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004124 return mExpectedInflightDuration > kMinInflightDuration ?
4125 mExpectedInflightDuration : kMinInflightDuration;
4126}
4127
Emilian Peevaebbe412018-01-15 13:53:24 +00004128void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004129 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004130 if ((request == nullptr) || (halRequest == nullptr)) {
4131 ALOGE("%s: Invalid request!", __FUNCTION__);
4132 return;
4133 }
4134
4135 if (halRequest->num_physcam_settings > 0) {
4136 if (halRequest->physcam_id != nullptr) {
4137 delete [] halRequest->physcam_id;
4138 halRequest->physcam_id = nullptr;
4139 }
4140 if (halRequest->physcam_settings != nullptr) {
4141 auto it = ++(request->mSettingsList.begin());
4142 size_t i = 0;
4143 for (; it != request->mSettingsList.end(); it++, i++) {
4144 it->metadata.unlock(halRequest->physcam_settings[i]);
4145 }
4146 delete [] halRequest->physcam_settings;
4147 halRequest->physcam_settings = nullptr;
4148 }
4149 }
4150}
4151
Ravneet74cd3732022-03-30 05:33:03 +00004152status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4153 Mutex::Autolock il(mInterfaceLock);
4154 Mutex::Autolock l(mLock);
4155
4156 if (mCameraServiceWatchdog != NULL) {
4157 mCameraServiceWatchdog->setEnabled(enabled);
4158 }
4159
4160 return OK;
4161}
4162
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004163void Camera3Device::setStreamUseCaseOverrides(
4164 const std::vector<int64_t>& useCaseOverrides) {
4165 Mutex::Autolock il(mInterfaceLock);
4166 Mutex::Autolock l(mLock);
4167 mStreamUseCaseOverrides = useCaseOverrides;
4168}
4169
4170void Camera3Device::clearStreamUseCaseOverrides() {
4171 Mutex::Autolock il(mInterfaceLock);
4172 Mutex::Autolock l(mLock);
4173 mStreamUseCaseOverrides.clear();
4174}
4175
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004176void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4177 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004178 return;
4179 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004181 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004182 // Skip the ones that have been submitted successfully.
4183 if (nextRequest.submitted) {
4184 continue;
4185 }
4186
4187 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004188 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4189 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004190
4191 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004192 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004193 }
4194
Emilian Peevaebbe412018-01-15 13:53:24 +00004195 cleanupPhysicalSettings(captureRequest, halRequest);
4196
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004197 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004198 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004199 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4200 }
4201
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004202 // No output buffer can be returned when using HAL buffer manager
4203 if (!mUseHalBufManager) {
4204 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4205 //Buffers that failed processing could still have
4206 //valid acquire fence.
4207 int acquireFence = (*outputBuffers)[i].acquire_fence;
4208 if (0 <= acquireFence) {
4209 close(acquireFence);
4210 outputBuffers->editItemAt(i).acquire_fence = -1;
4211 }
Emilian Peevf4816702020-04-03 15:44:51 -07004212 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004213 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4214 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004215 /*timestampIncreasing*/true, std::vector<size_t> (),
4216 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004217 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004218 }
4219
4220 if (sendRequestError) {
4221 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004222 sp<NotificationListener> listener = mListener.promote();
4223 if (listener != NULL) {
4224 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004225 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004226 captureRequest->mResultExtras);
4227 }
4228 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004229
4230 // Remove yet-to-be submitted inflight request from inflightMap
4231 {
4232 sp<Camera3Device> parent = mParent.promote();
4233 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004234 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004235 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4236 if (idx >= 0) {
4237 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4238 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4239 parent->removeInFlightMapEntryLocked(idx);
4240 }
4241 }
4242 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004244
4245 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004246 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004247}
4248
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004249void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004250 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251 // Optimized a bit for the simple steady-state case (single repeating
4252 // request), to avoid putting that request in the queue temporarily.
4253 Mutex::Autolock l(mRequestLock);
4254
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004255 assert(mNextRequests.empty());
4256
4257 NextRequest nextRequest;
4258 nextRequest.captureRequest = waitForNextRequestLocked();
4259 if (nextRequest.captureRequest == nullptr) {
4260 return;
4261 }
4262
Emilian Peevf4816702020-04-03 15:44:51 -07004263 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004264 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004265 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004266
4267 // Wait for additional requests
4268 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4269
4270 for (size_t i = 1; i < batchSize; i++) {
4271 NextRequest additionalRequest;
4272 additionalRequest.captureRequest = waitForNextRequestLocked();
4273 if (additionalRequest.captureRequest == nullptr) {
4274 break;
4275 }
4276
Emilian Peevf4816702020-04-03 15:44:51 -07004277 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004278 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004279 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004280 }
4281
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004282 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004283 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004284 mNextRequests.size(), batchSize);
4285 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004286 }
4287
4288 return;
4289}
4290
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004291void Camera3Device::RequestThread::setRequestClearing() {
4292 Mutex::Autolock l(mRequestLock);
4293 mRequestClearing = true;
4294}
4295
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004296sp<Camera3Device::CaptureRequest>
4297 Camera3Device::RequestThread::waitForNextRequestLocked() {
4298 status_t res;
4299 sp<CaptureRequest> nextRequest;
4300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 while (mRequestQueue.empty()) {
4302 if (!mRepeatingRequests.empty()) {
4303 // Always atomically enqueue all requests in a repeating request
4304 // list. Guarantees a complete in-sequence set of captures to
4305 // application.
4306 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004307 if (mFirstRepeating) {
4308 mFirstRepeating = false;
4309 } else {
4310 for (auto& request : requests) {
4311 // For repeating requests, override timestamp request using
4312 // the time a request is inserted into the request queue,
4313 // because the original repeating request will have an old
4314 // fixed timestamp.
4315 request->mRequestTimeNs = systemTime();
4316 }
4317 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 RequestList::const_iterator firstRequest =
4319 requests.begin();
4320 nextRequest = *firstRequest;
4321 mRequestQueue.insert(mRequestQueue.end(),
4322 ++firstRequest,
4323 requests.end());
4324 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004325
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004326 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004327
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004328 break;
4329 }
4330
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004331 if (!mRequestClearing) {
4332 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004335 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4336 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337 Mutex::Autolock pl(mPauseLock);
4338 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004339 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004340 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004341 if (mNotifyPipelineDrain) {
4342 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4343 mNotifyPipelineDrain = false;
4344 mStreamIdsToBeDrained.clear();
4345 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004346 // Let the tracker know
4347 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4348 if (statusTracker != 0) {
4349 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4350 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004351 sp<Camera3Device> parent = mParent.promote();
4352 if (parent != nullptr) {
4353 parent->mRequestBufferSM.onRequestThreadPaused();
4354 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004355 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004356 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 // Stop waiting for now and let thread management happen
4358 return NULL;
4359 }
4360 }
4361
4362 if (nextRequest == NULL) {
4363 // Don't have a repeating request already in hand, so queue
4364 // must have an entry now.
4365 RequestList::iterator firstRequest =
4366 mRequestQueue.begin();
4367 nextRequest = *firstRequest;
4368 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004369 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4370 sp<NotificationListener> listener = mListener.promote();
4371 if (listener != NULL) {
4372 listener->notifyRequestQueueEmpty();
4373 }
4374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004375 }
4376
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004377 // In case we've been unpaused by setPaused clearing mDoPause, need to
4378 // update internal pause state (capture/setRepeatingRequest unpause
4379 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004381 if (mPaused) {
4382 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4383 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4384 if (statusTracker != 0) {
4385 statusTracker->markComponentActive(mStatusId);
4386 }
4387 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004388 mPaused = false;
4389
4390 // Check if we've reconfigured since last time, and reset the preview
4391 // request if so. Can't use 'NULL request == repeat' across configure calls.
4392 if (mReconfigured) {
4393 mPrevRequest.clear();
4394 mReconfigured = false;
4395 }
4396
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004397 if (nextRequest != NULL) {
4398 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004399 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4400 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004401
4402 // Since RequestThread::clear() removes buffers from the input stream,
4403 // get the right buffer here before unlocking mRequestLock
4404 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004405 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4406 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004407 if (res != OK) {
4408 // Can't get input buffer from gralloc queue - this could be due to
4409 // disconnected queue or other producer misbehavior, so not a fatal
4410 // error
4411 ALOGE("%s: Can't get input buffer, skipping request:"
4412 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004413
4414 sp<NotificationListener> listener = mListener.promote();
4415 if (listener != NULL) {
4416 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004417 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004418 nextRequest->mResultExtras);
4419 }
4420 return NULL;
4421 }
4422 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004423 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004424
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004425 return nextRequest;
4426}
4427
4428bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004429 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004430 status_t res;
4431 Mutex::Autolock l(mPauseLock);
4432 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004433 if (mPaused == false) {
4434 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004435 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004436 if (mNotifyPipelineDrain) {
4437 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4438 mNotifyPipelineDrain = false;
4439 mStreamIdsToBeDrained.clear();
4440 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004441 // Let the tracker know
4442 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4443 if (statusTracker != 0) {
4444 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4445 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004446 sp<Camera3Device> parent = mParent.promote();
4447 if (parent != nullptr) {
4448 parent->mRequestBufferSM.onRequestThreadPaused();
4449 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004452 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004453 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004454 return true;
4455 }
4456 }
4457 // We don't set mPaused to false here, because waitForNextRequest needs
4458 // to further manage the paused state in case of starvation.
4459 return false;
4460}
4461
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004462void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004463 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004464 // With work to do, mark thread as unpaused.
4465 // If paused by request (setPaused), don't resume, to avoid
4466 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004467 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004468 Mutex::Autolock p(mPauseLock);
4469 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004470 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4471 if (mPaused) {
4472 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4473 if (statusTracker != 0) {
4474 statusTracker->markComponentActive(mStatusId);
4475 }
4476 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004477 mPaused = false;
4478 }
4479}
4480
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004481void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4482 sp<Camera3Device> parent = mParent.promote();
4483 if (parent != NULL) {
4484 va_list args;
4485 va_start(args, fmt);
4486
4487 parent->setErrorStateV(fmt, args);
4488
4489 va_end(args);
4490 }
4491}
4492
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004493status_t Camera3Device::RequestThread::insertTriggers(
4494 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004495 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004496 Mutex::Autolock al(mTriggerMutex);
4497
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004498 sp<Camera3Device> parent = mParent.promote();
4499 if (parent == NULL) {
4500 CLOGE("RequestThread: Parent is gone");
4501 return DEAD_OBJECT;
4502 }
4503
Emilian Peevaebbe412018-01-15 13:53:24 +00004504 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004505 size_t count = mTriggerMap.size();
4506
4507 for (size_t i = 0; i < count; ++i) {
4508 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004509 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004510
4511 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4512 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4513 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004514 if (isAeTrigger) {
4515 request->mResultExtras.precaptureTriggerId = triggerId;
4516 mCurrentPreCaptureTriggerId = triggerId;
4517 } else {
4518 request->mResultExtras.afTriggerId = triggerId;
4519 mCurrentAfTriggerId = triggerId;
4520 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004521 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004522 }
4523
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004524 camera_metadata_entry entry = metadata.find(tag);
4525
4526 if (entry.count > 0) {
4527 /**
4528 * Already has an entry for this trigger in the request.
4529 * Rewrite it with our requested trigger value.
4530 */
4531 RequestTrigger oldTrigger = trigger;
4532
4533 oldTrigger.entryValue = entry.data.u8[0];
4534
4535 mTriggerReplacedMap.add(tag, oldTrigger);
4536 } else {
4537 /**
4538 * More typical, no trigger entry, so we just add it
4539 */
4540 mTriggerRemovedMap.add(tag, trigger);
4541 }
4542
4543 status_t res;
4544
4545 switch (trigger.getTagType()) {
4546 case TYPE_BYTE: {
4547 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4548 res = metadata.update(tag,
4549 &entryValue,
4550 /*count*/1);
4551 break;
4552 }
4553 case TYPE_INT32:
4554 res = metadata.update(tag,
4555 &trigger.entryValue,
4556 /*count*/1);
4557 break;
4558 default:
4559 ALOGE("%s: Type not supported: 0x%x",
4560 __FUNCTION__,
4561 trigger.getTagType());
4562 return INVALID_OPERATION;
4563 }
4564
4565 if (res != OK) {
4566 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4567 ", value %d", __FUNCTION__, trigger.getTagName(),
4568 trigger.entryValue);
4569 return res;
4570 }
4571
4572 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4573 trigger.getTagName(),
4574 trigger.entryValue);
4575 }
4576
4577 mTriggerMap.clear();
4578
4579 return count;
4580}
4581
4582status_t Camera3Device::RequestThread::removeTriggers(
4583 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004584 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004585 Mutex::Autolock al(mTriggerMutex);
4586
Emilian Peevaebbe412018-01-15 13:53:24 +00004587 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004588
4589 /**
4590 * Replace all old entries with their old values.
4591 */
4592 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4593 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4594
4595 status_t res;
4596
4597 uint32_t tag = trigger.metadataTag;
4598 switch (trigger.getTagType()) {
4599 case TYPE_BYTE: {
4600 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4601 res = metadata.update(tag,
4602 &entryValue,
4603 /*count*/1);
4604 break;
4605 }
4606 case TYPE_INT32:
4607 res = metadata.update(tag,
4608 &trigger.entryValue,
4609 /*count*/1);
4610 break;
4611 default:
4612 ALOGE("%s: Type not supported: 0x%x",
4613 __FUNCTION__,
4614 trigger.getTagType());
4615 return INVALID_OPERATION;
4616 }
4617
4618 if (res != OK) {
4619 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4620 ", trigger value %d", __FUNCTION__,
4621 trigger.getTagName(), trigger.entryValue);
4622 return res;
4623 }
4624 }
4625 mTriggerReplacedMap.clear();
4626
4627 /**
4628 * Remove all new entries.
4629 */
4630 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4631 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4632 status_t res = metadata.erase(trigger.metadataTag);
4633
4634 if (res != OK) {
4635 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4636 ", trigger value %d", __FUNCTION__,
4637 trigger.getTagName(), trigger.entryValue);
4638 return res;
4639 }
4640 }
4641 mTriggerRemovedMap.clear();
4642
4643 return OK;
4644}
4645
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004646status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004647 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004648 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004649 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004650 status_t res;
4651
Emilian Peevaebbe412018-01-15 13:53:24 +00004652 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004653
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004654 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004655 // exists
4656 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4657 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4658 if (afTrigger.count > 0 &&
4659 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4660 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004661 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004662 if (res != OK) return res;
4663 }
4664
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004665 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004666 // if none already exists
4667 camera_metadata_entry pcTrigger =
4668 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4669 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4670 if (pcTrigger.count > 0 &&
4671 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4672 pcId.count == 0) {
4673 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004674 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004675 if (res != OK) return res;
4676 }
4677
4678 return OK;
4679}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004680
Emilian Peevb9f83812023-03-17 17:13:07 -07004681bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request) {
4682 ATRACE_CALL();
4683 Mutex::Autolock l(mTriggerMutex);
4684 return Camera3Device::overrideAutoRotateAndCrop(request, this->mOverrideToPortrait,
4685 this->mRotateAndCropOverride);
4686}
4687
4688bool Camera3Device::overrideAutoRotateAndCrop(const sp<CaptureRequest> &request,
4689 bool overrideToPortrait,
4690 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004691 ATRACE_CALL();
4692
Emilian Peevb9f83812023-03-17 17:13:07 -07004693 if (overrideToPortrait) {
4694 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
Austin Borger3560b7e2022-10-27 12:20:29 -07004695 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4696 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4697 &rotateAndCrop_u8, 1);
4698 return true;
4699 }
4700
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004701 if (request->mRotateAndCropAuto) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004702 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4703
4704 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4705 if (rotateAndCropEntry.count > 0) {
Emilian Peevb9f83812023-03-17 17:13:07 -07004706 if (rotateAndCropEntry.data.u8[0] == rotateAndCropOverride) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004707 return false;
4708 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004709 rotateAndCropEntry.data.u8[0] = rotateAndCropOverride;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004710 return true;
4711 }
4712 } else {
Emilian Peevb9f83812023-03-17 17:13:07 -07004713 uint8_t rotateAndCrop_u8 = rotateAndCropOverride;
4714 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP, &rotateAndCrop_u8, 1);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004715 return true;
4716 }
4717 }
Emilian Peevb9f83812023-03-17 17:13:07 -07004718
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004719 return false;
4720}
4721
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004722bool Camera3Device::RequestThread::overrideTestPattern(
4723 const sp<CaptureRequest> &request) {
4724 ATRACE_CALL();
4725
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004726 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004727
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004728 Mutex::Autolock l(mTriggerMutex);
4729
4730 bool changed = false;
4731
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004732 // For a multi-camera, the physical cameras support the same set of
4733 // test pattern modes as the logical camera.
4734 for (auto& settings : request->mSettingsList) {
4735 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004736
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004737 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4738 int32_t testPatternData[4] = {
4739 settings.mOriginalTestPatternData[0],
4740 settings.mOriginalTestPatternData[1],
4741 settings.mOriginalTestPatternData[2],
4742 settings.mOriginalTestPatternData[3]
4743 };
4744 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4745 testPatternMode = mCameraMute;
4746 testPatternData[0] = 0;
4747 testPatternData[1] = 0;
4748 testPatternData[2] = 0;
4749 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004750 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004751
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004752 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4753 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4754 if (testPatternEntry.count > 0) {
4755 if (testPatternEntry.data.i32[0] != testPatternMode) {
4756 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004757 changed = true;
4758 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004759 } else if (supportTestPatternModeKey) {
4760 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4761 &testPatternMode, 1);
4762 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004763 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004764
4765 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4766 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4767 if (testPatternColor.count >= 4) {
4768 for (size_t i = 0; i < 4; i++) {
4769 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4770 testPatternColor.data.i32[i] = testPatternData[i];
4771 changed = true;
4772 }
4773 }
4774 } else if (supportTestPatternDataKey) {
4775 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4776 testPatternData, 4);
4777 changed = true;
4778 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004779 }
4780
4781 return changed;
4782}
4783
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004784status_t Camera3Device::RequestThread::setHalInterface(
4785 sp<HalInterface> newHalInterface) {
4786 if (newHalInterface.get() == nullptr) {
4787 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4788 return DEAD_OBJECT;
4789 }
4790
4791 mInterface = newHalInterface;
4792
4793 return OK;
4794}
4795
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004796/**
4797 * PreparerThread inner class methods
4798 */
4799
4800Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004801 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004802 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004803}
4804
4805Camera3Device::PreparerThread::~PreparerThread() {
4806 Thread::requestExitAndWait();
4807 if (mCurrentStream != nullptr) {
4808 mCurrentStream->cancelPrepare();
4809 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4810 mCurrentStream.clear();
4811 }
4812 clear();
4813}
4814
Ruben Brunkc78ac262015-08-13 17:58:46 -07004815status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004816 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817 status_t res;
4818
4819 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004820 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004821
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004822 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004823 if (res == OK) {
4824 // No preparation needed, fire listener right off
4825 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004826 if (listener != NULL) {
4827 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004828 }
4829 return OK;
4830 } else if (res != NOT_ENOUGH_DATA) {
4831 return res;
4832 }
4833
4834 // Need to prepare, start up thread if necessary
4835 if (!mActive) {
4836 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4837 // isn't running
4838 Thread::requestExitAndWait();
4839 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4840 if (res != OK) {
4841 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004842 if (listener != NULL) {
4843 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004844 }
4845 return res;
4846 }
4847 mCancelNow = false;
4848 mActive = true;
4849 ALOGV("%s: Preparer stream started", __FUNCTION__);
4850 }
4851
4852 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004853 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004854 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4855
4856 return OK;
4857}
4858
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004859void Camera3Device::PreparerThread::pause() {
4860 ATRACE_CALL();
4861
4862 Mutex::Autolock l(mLock);
4863
4864 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4865 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4866 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4867 int currentMaxCount = mCurrentMaxCount;
4868 mPendingStreams.clear();
4869 mCancelNow = true;
4870 while (mActive) {
4871 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4872 if (res == TIMED_OUT) {
4873 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4874 return;
4875 } else if (res != OK) {
4876 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4877 return;
4878 }
4879 }
4880
4881 //Check whether the prepare thread was able to complete the current
4882 //stream. In case work is still pending emplace it along with the rest
4883 //of the streams in the pending list.
4884 if (currentStream != nullptr) {
4885 if (!mCurrentPrepareComplete) {
4886 pendingStreams.emplace(currentMaxCount, currentStream);
4887 }
4888 }
4889
4890 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4891 for (const auto& it : mPendingStreams) {
4892 it.second->cancelPrepare();
4893 }
4894}
4895
4896status_t Camera3Device::PreparerThread::resume() {
4897 ATRACE_CALL();
4898 status_t res;
4899
4900 Mutex::Autolock l(mLock);
4901 sp<NotificationListener> listener = mListener.promote();
4902
4903 if (mActive) {
4904 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4905 return NO_INIT;
4906 }
4907
4908 auto it = mPendingStreams.begin();
4909 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004910 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004911 if (res == OK) {
4912 if (listener != NULL) {
4913 listener->notifyPrepared(it->second->getId());
4914 }
4915 it = mPendingStreams.erase(it);
4916 } else if (res != NOT_ENOUGH_DATA) {
4917 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4918 res, strerror(-res));
4919 it = mPendingStreams.erase(it);
4920 } else {
4921 it++;
4922 }
4923 }
4924
4925 if (mPendingStreams.empty()) {
4926 return OK;
4927 }
4928
4929 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4930 if (res != OK) {
4931 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4932 __FUNCTION__, res, strerror(-res));
4933 return res;
4934 }
4935 mCancelNow = false;
4936 mActive = true;
4937 ALOGV("%s: Preparer stream started", __FUNCTION__);
4938
4939 return OK;
4940}
4941
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004942status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004943 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004944 Mutex::Autolock l(mLock);
4945
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004946 for (const auto& it : mPendingStreams) {
4947 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004948 }
4949 mPendingStreams.clear();
4950 mCancelNow = true;
4951
4952 return OK;
4953}
4954
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004955void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004956 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004957 Mutex::Autolock l(mLock);
4958 mListener = listener;
4959}
4960
4961bool Camera3Device::PreparerThread::threadLoop() {
4962 status_t res;
4963 {
4964 Mutex::Autolock l(mLock);
4965 if (mCurrentStream == nullptr) {
4966 // End thread if done with work
4967 if (mPendingStreams.empty()) {
4968 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4969 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4970 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4971 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004972 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004973 return false;
4974 }
4975
4976 // Get next stream to prepare
4977 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004978 mCurrentStream = it->second;
4979 mCurrentMaxCount = it->first;
4980 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004981 mPendingStreams.erase(it);
4982 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4983 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4984 } else if (mCancelNow) {
4985 mCurrentStream->cancelPrepare();
4986 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4987 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4988 mCurrentStream.clear();
4989 mCancelNow = false;
4990 return true;
4991 }
4992 }
4993
4994 res = mCurrentStream->prepareNextBuffer();
4995 if (res == NOT_ENOUGH_DATA) return true;
4996 if (res != OK) {
4997 // Something bad happened; try to recover by cancelling prepare and
4998 // signalling listener anyway
4999 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5000 mCurrentStream->getId(), res, strerror(-res));
5001 mCurrentStream->cancelPrepare();
5002 }
5003
5004 // This stream has finished, notify listener
5005 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005006 sp<NotificationListener> listener = mListener.promote();
5007 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005008 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5009 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005010 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005011 }
5012
5013 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5014 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005015 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005016
5017 return true;
5018}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005019
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005020status_t Camera3Device::RequestBufferStateMachine::initialize(
5021 sp<camera3::StatusTracker> statusTracker) {
5022 if (statusTracker == nullptr) {
5023 ALOGE("%s: statusTracker is null", __FUNCTION__);
5024 return BAD_VALUE;
5025 }
5026
5027 std::lock_guard<std::mutex> lock(mLock);
5028 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005029 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005030 return OK;
5031}
5032
5033bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5034 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005035 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005036 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005037 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005038 return true;
5039 }
5040 return false;
5041}
5042
5043void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5044 std::lock_guard<std::mutex> lock(mLock);
5045 if (!mRequestBufferOngoing) {
5046 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5047 return;
5048 }
5049 mRequestBufferOngoing = false;
5050 if (mStatus == RB_STATUS_PENDING_STOP) {
5051 checkSwitchToStopLocked();
5052 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005053 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005054}
5055
5056void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5057 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005058 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005059 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005060 return;
5061}
5062
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005063void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005064 std::lock_guard<std::mutex> lock(mLock);
5065 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005066 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5067 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005068 mInflightMapEmpty = false;
5069 if (mStatus == RB_STATUS_STOPPED) {
5070 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005071 }
5072 return;
5073}
5074
5075void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5076 std::lock_guard<std::mutex> lock(mLock);
5077 mRequestThreadPaused = true;
5078 if (mStatus == RB_STATUS_PENDING_STOP) {
5079 checkSwitchToStopLocked();
5080 }
5081 return;
5082}
5083
5084void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5085 std::lock_guard<std::mutex> lock(mLock);
5086 mInflightMapEmpty = true;
5087 if (mStatus == RB_STATUS_PENDING_STOP) {
5088 checkSwitchToStopLocked();
5089 }
5090 return;
5091}
5092
5093void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5094 std::lock_guard<std::mutex> lock(mLock);
5095 if (!checkSwitchToStopLocked()) {
5096 mStatus = RB_STATUS_PENDING_STOP;
5097 }
5098 return;
5099}
5100
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005101bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5102 std::lock_guard<std::mutex> lock(mLock);
5103 if (mRequestBufferOngoing) {
5104 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5105 __FUNCTION__);
5106 return false;
5107 }
5108 mSwitchedToOffline = true;
5109 mInflightMapEmpty = true;
5110 mRequestThreadPaused = true;
5111 mStatus = RB_STATUS_STOPPED;
5112 return true;
5113}
5114
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005115void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5116 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5117 if (statusTracker != nullptr) {
5118 if (active) {
5119 statusTracker->markComponentActive(mRequestBufferStatusId);
5120 } else {
5121 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5122 }
5123 }
5124}
5125
5126bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5127 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5128 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005129 return true;
5130 }
5131 return false;
5132}
5133
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005134bool Camera3Device::startRequestBuffer() {
5135 return mRequestBufferSM.startRequestBuffer();
5136}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005137
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005138void Camera3Device::endRequestBuffer() {
5139 mRequestBufferSM.endRequestBuffer();
5140}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005141
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005142nsecs_t Camera3Device::getWaitDuration() {
5143 return kBaseGetBufferWait + getExpectedInFlightDuration();
5144}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005145
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005146void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5147 mInterface->getInflightBufferKeys(out);
5148}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005149
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005150void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5151 mInterface->getInflightRequestBufferKeys(out);
5152}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005153
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005154std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5155 std::vector<sp<Camera3StreamInterface>> ret;
5156 bool hasInputStream = mInputStream != nullptr;
5157 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5158 if (hasInputStream) {
5159 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005160 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005161 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5162 ret.push_back(mOutputStreams[i]);
5163 }
5164 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5165 ret.push_back(mDeletedStreams[i]);
5166 }
5167 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005168}
5169
Emilian Peevcc0b7952020-01-07 13:54:47 -08005170void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5171 ATRACE_CALL();
5172
5173 if (offlineStreamIds == nullptr) {
5174 return;
5175 }
5176
5177 Mutex::Autolock il(mInterfaceLock);
5178
5179 auto streamIds = mOutputStreams.getStreamIds();
5180 bool hasInputStream = mInputStream != nullptr;
5181 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5182 offlineStreamIds->push_back(mInputStream->getId());
5183 }
5184
5185 for (const auto & streamId : streamIds) {
5186 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5187 // Streams that use the camera buffer manager are currently not supported in
5188 // offline mode
5189 if (stream->getOfflineProcessingSupport() &&
5190 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5191 offlineStreamIds->push_back(streamId);
5192 }
5193 }
5194}
5195
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005196status_t Camera3Device::setRotateAndCropAutoBehavior(
5197 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5198 ATRACE_CALL();
5199 Mutex::Autolock il(mInterfaceLock);
5200 Mutex::Autolock l(mLock);
5201 if (mRequestThread == nullptr) {
5202 return INVALID_OPERATION;
5203 }
Emilian Peevb9f83812023-03-17 17:13:07 -07005204 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
5205 return BAD_VALUE;
5206 }
5207 mRotateAndCropOverride = rotateAndCropValue;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005208 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5209}
5210
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005211bool Camera3Device::supportsCameraMute() {
5212 Mutex::Autolock il(mInterfaceLock);
5213 Mutex::Autolock l(mLock);
5214
5215 return mSupportCameraMute;
5216}
5217
5218status_t Camera3Device::setCameraMute(bool enabled) {
5219 ATRACE_CALL();
5220 Mutex::Autolock il(mInterfaceLock);
5221 Mutex::Autolock l(mLock);
5222
5223 if (mRequestThread == nullptr || !mSupportCameraMute) {
5224 return INVALID_OPERATION;
5225 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005226 int32_t muteMode =
5227 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5228 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5229 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5230 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005231}
5232
Austin Borger0fb3ad92023-06-01 16:51:35 -07005233status_t Camera3Device::injectCamera(const std::string& injectedCamId,
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005234 sp<CameraProviderManager> manager) {
Austin Borger0fb3ad92023-06-01 16:51:35 -07005235 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.c_str());
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005236 ATRACE_CALL();
5237 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005238 // When the camera device is active, injectCamera() and stopInjection() will call
5239 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5240 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5241 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5242 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5243 // waitUntilStateThenRelock().
5244 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005245
5246 status_t res = NO_ERROR;
5247 if (mInjectionMethods->isInjecting()) {
5248 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5249 return OK;
5250 } else {
5251 res = mInjectionMethods->stopInjection();
5252 if (res != OK) {
5253 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5254 __FUNCTION__, res);
5255 return res;
5256 }
5257 }
5258 }
5259
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005260 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005261 if (res != OK) {
5262 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5263 __FUNCTION__, res);
5264 return res;
5265 }
5266
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005267 // When the second display of android is cast to the remote device, and the opened camera is
5268 // also cast to the second display, in this case, because the camera has configured the streams
5269 // at this time, we can directly call injectCamera() to replace the internal camera with
5270 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005271 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5272 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5273
5274 camera3::camera_stream_configuration injectionConfig;
5275 std::vector<uint32_t> injectionBufferSizes;
5276 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5277 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5278 || injectionBufferSizes.size() <= 0) {
5279 ALOGE("Failed to inject camera due to abandoned configuration! "
5280 "mOperatingMode: %d injectionConfig.num_streams: %d "
5281 "injectionBufferSizes.size(): %zu", mOperatingMode,
5282 injectionConfig.num_streams, injectionBufferSizes.size());
5283 return DEAD_OBJECT;
5284 }
5285
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005286 res = mInjectionMethods->injectCamera(
5287 injectionConfig, injectionBufferSizes);
5288 if (res != OK) {
5289 ALOGE("Can't finish inject camera process!");
5290 return res;
5291 }
5292 }
5293
5294 return OK;
5295}
5296
5297status_t Camera3Device::stopInjection() {
5298 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5299 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005300 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005301 return mInjectionMethods->stopInjection();
5302}
5303
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005304void Camera3Device::overrideStreamUseCaseLocked() {
5305 if (mStreamUseCaseOverrides.size() == 0) {
5306 return;
5307 }
5308
5309 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5310 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5311 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5312 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5313 outputStreamsIndices[i] = i;
5314 }
5315
5316 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5317 [&](int a, int b) -> bool {
5318
5319 auto formatScore = [](int format) {
5320 switch (format) {
5321 case HAL_PIXEL_FORMAT_BLOB:
5322 return 4;
5323 case HAL_PIXEL_FORMAT_RAW16:
5324 case HAL_PIXEL_FORMAT_RAW10:
5325 case HAL_PIXEL_FORMAT_RAW12:
5326 return 3;
5327 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5328 return 2;
5329 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5330 return 1;
5331 default:
5332 return 0;
5333 }
5334 };
5335
5336 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5337 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5338 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5339 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5340 if (sizeA > sizeB ||
5341 (sizeA == sizeB && formatAScore >= formatBScore)) {
5342 return true;
5343 } else {
5344 return false;
5345 }
5346 });
5347
5348 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5349 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5350 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5351 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5352 }
5353}
5354
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005355}; // namespace android