blob: 37a2c39efc7885660d080661a8bdce0ee6ec0013 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070055#include "CameraService.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080056#include "aidl/AidlUtils.h"
57#include "device3/Camera3Device.h"
58#include "device3/Camera3FakeStream.h"
59#include "device3/Camera3InputStream.h"
60#include "device3/Camera3OutputStream.h"
61#include "device3/Camera3SharedOutputStream.h"
62#include "mediautils/SchedulingPolicyService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080064#include "utils/CameraTraces.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080065#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070066#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080073
74namespace android {
75
Austin Borger74fca042022-05-23 12:41:21 -070076Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070077 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070078 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080087 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080088 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070090 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070093 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000095 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010096 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070097 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070098 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -070099 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800100 mOverrideToPortrait(overrideToPortrait),
101 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102{
103 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800105}
106
107Camera3Device::~Camera3Device()
108{
109 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700111 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800112}
113
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800115 return mId;
116}
117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118status_t Camera3Device::initializeCommonLocked() {
119
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700120 /** Start up status tracker thread */
121 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700123 if (res != OK) {
124 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
125 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800126 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700127 mStatusTracker.clear();
128 return res;
129 }
130
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700132 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700133
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700134 if (mUseHalBufManager) {
135 res = mRequestBufferSM.initialize(mStatusTracker);
136 if (res != OK) {
137 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
138 strerror(-res), res);
139 mInterface->close();
140 mStatusTracker.clear();
141 return res;
142 }
143 }
144
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800145 /** Create buffer manager */
146 mBufferManager = new Camera3BufferManager();
147
148 Vector<int32_t> sessionParamKeys;
149 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
150 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
151 if (sessionKeysEntry.count > 0) {
152 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
153 }
154
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700155 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
156 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
157 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
158 if (availableTestPatternModes.data.i32[i] ==
159 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
160 mSupportCameraMute = true;
161 mSupportTestPatternSolidColor = true;
162 break;
163 } else if (availableTestPatternModes.data.i32[i] ==
164 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
165 mSupportCameraMute = true;
166 mSupportTestPatternSolidColor = false;
167 }
168 }
169
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700170 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800171 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700172 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger18b30a72022-10-27 12:20:29 -0700173 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800174 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800175 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700176 SET_ERR_L("Unable to start request queue thread: %s (%d)",
177 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800178 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800179 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800180 return res;
181 }
182
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700183 mPreparerThread = new PreparerThread();
184
Ruben Brunk183f0562015-08-12 12:55:02 -0700185 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800186 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400187 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700188 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700189 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800190 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800191
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800193 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800194 camera_metadata_entry timestampSource =
195 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
196 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
197 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800198 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800199 }
200
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700201 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100202 camera_metadata_entry partialResultsCount =
203 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
204 if (partialResultsCount.count > 0) {
205 mNumPartialResults = partialResultsCount.data.i32[0];
206 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700207 }
208
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800209 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
210 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700211 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700212 if (res != OK) {
213 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
214 return res;
215 }
216 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800218 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800220
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700221 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
222 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
223 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
224 }
225
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800226 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
227 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
228 }
229
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800230 // Hidl/AidlCamera3DeviceInjectionMethods
231 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800232
Ravneetaeb20dc2022-03-30 05:33:03 +0000233 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800234 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700235 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
236 if (res != OK) {
237 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
238 strerror(-res), res);
239 return res;
240 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000241
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800242 return OK;
243}
244
245status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700246 return disconnectImpl();
247}
248
249status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800250 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700251 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800252
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700253 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700254 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700255 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800256 Mutex::Autolock il(mInterfaceLock);
257 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
258 {
259 Mutex::Autolock l(mLock);
260 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000262 if (mRequestThread != NULL) {
263 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
264 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800265 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000266 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000268 } else {
269 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
270 if (res != OK) {
271 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
272 maxExpectedDuration);
273 // Continue to close device even in case of error
274 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000277 // Signal to request thread that we're not expecting any
278 // more requests. This will be true since once we're in
279 // disconnect and we've cleared off the request queue, the
280 // request thread can't receive any new requests through
281 // binder calls - since disconnect holds
282 // mBinderSerialization lock.
283 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700284 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800285
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800286 if (mStatus == STATUS_ERROR) {
287 CLOGE("Shutting down in an error state");
288 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700289
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800290 if (mStatusTracker != NULL) {
291 mStatusTracker->requestExit();
292 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700293
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 if (mRequestThread != NULL) {
295 mRequestThread->requestExit();
296 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800298 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
299 for (size_t i = 0; i < mOutputStreams.size(); i++) {
300 streams.push_back(mOutputStreams[i]);
301 }
302 if (mInputStream != nullptr) {
303 streams.push_back(mInputStream);
304 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700305 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800307 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
308 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
310 // HAL may be in a bad state, so waiting for request thread
311 // (which may be stuck in the HAL processCaptureRequest call)
312 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800313 // give up mInterfaceLock here and then lock it again. Could this lead
314 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mRequestThread->join();
316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800318 Mutex::Autolock il(mInterfaceLock);
319 if (mStatusTracker != NULL) {
320 mStatusTracker->join();
321 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800323 if (mInjectionMethods->isInjecting()) {
324 mInjectionMethods->stopInjection();
325 }
326
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800327 HalInterface* interface;
328 {
329 Mutex::Autolock l(mLock);
330 mRequestThread.clear();
331 Mutex::Autolock stLock(mTrackerLock);
332 mStatusTracker.clear();
333 interface = mInterface.get();
334 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700335
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800336 // Call close without internal mutex held, as the HAL close may need to
337 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000338 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800340 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800342 {
343 Mutex::Autolock l(mLock);
344 mInterface->clear();
345 mOutputStreams.clear();
346 mInputStream.clear();
347 mDeletedStreams.clear();
348 mBufferManager.clear();
349 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
350 }
351
352 for (auto& weakStream : streams) {
353 sp<Camera3StreamInterface> stream = weakStream.promote();
354 if (stream != nullptr) {
355 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
356 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
357 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700358 }
359 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700360 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000361
362 if (mCameraServiceWatchdog != NULL) {
363 mCameraServiceWatchdog->requestExit();
364 mCameraServiceWatchdog.clear();
365 }
366
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700367 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800368}
369
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370// For dumping/debugging only -
371// try to acquire a lock a few times, eventually give up to proceed with
372// debug/dump operations
373bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
374 bool gotLock = false;
375 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
376 if (lock.tryLock() == NO_ERROR) {
377 gotLock = true;
378 break;
379 } else {
380 usleep(kDumpSleepDuration);
381 }
382 }
383 return gotLock;
384}
385
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800386nsecs_t Camera3Device::getMonoToBoottimeOffset() {
387 // try three times to get the clock offset, choose the one
388 // with the minimum gap in measurements.
389 const int tries = 3;
390 nsecs_t bestGap, measured;
391 for (int i = 0; i < tries; ++i) {
392 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
393 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
394 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
395 const nsecs_t gap = tmono2 - tmono;
396 if (i == 0 || gap < bestGap) {
397 bestGap = gap;
398 measured = tbase - ((tmono + tmono2) >> 1);
399 }
400 }
401 return measured;
402}
403
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
405 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700406 // Get max jpeg size (area-wise) for default sensor pixel mode
407 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800408 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700409 /*isUltraHighResolutionSensor*/false);
410 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
411 // not ultra high res sensor
412 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800413 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700414 /*isUltraHighResolution*/true);
415 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
417 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700418 return BAD_VALUE;
419 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700420 bool useMaxSensorPixelModeThreshold = false;
421 if (uhrMaxJpegResolution.width != 0 &&
422 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
423 // Use the ultra high res max jpeg size and max jpeg buffer size
424 useMaxSensorPixelModeThreshold = true;
425 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700426
Zhijun Hef7da0962014-04-24 13:27:56 -0700427 // Get max jpeg buffer size
428 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800429 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700430 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800431 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
432 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700433 return BAD_VALUE;
434 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700435 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700436
437 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
438 if (useMaxSensorPixelModeThreshold) {
439 maxJpegBufferSize =
440 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
441 maxDefaultJpegResolution, maxJpegBufferSize);
442 chosenMaxJpegResolution = uhrMaxJpegResolution;
443 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800444 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700445
446 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700447 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700448 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800449 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
450 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700451 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800452 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
453 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700454 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700455 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700456 return jpegBufferSize;
457}
458
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800459ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700460 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800461 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700462 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800463 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
464 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700465 return BAD_VALUE;
466 }
467 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
468 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
469 return maxBytesForPointCloud;
470}
471
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800472ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
473 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 const int PER_CONFIGURATION_SIZE = 3;
475 const int WIDTH_OFFSET = 0;
476 const int HEIGHT_OFFSET = 1;
477 const int SIZE_OFFSET = 2;
478 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800479 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800480 camera3::SessionConfigurationUtils::getAppropriateModeTag(
481 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
482 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800483 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800484 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800485 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
486 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800487 return BAD_VALUE;
488 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700489
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800490 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
491 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
492 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
493 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
494 }
495 }
496
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800497 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
498 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800499 return BAD_VALUE;
500}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700501
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800502status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
503 ATRACE_CALL();
504 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700505
506 // Try to lock, but continue in case of failure (to avoid blocking in
507 // deadlocks)
508 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
509 bool gotLock = tryLockSpinRightRound(mLock);
510
511 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
513 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700514 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800515 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
516 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700517
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800518 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700519
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800520 String16 templatesOption("-t");
521 int n = args.size();
522 for (int i = 0; i < n; i++) {
523 if (args[i] == templatesOption) {
524 dumpTemplates = true;
525 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000526 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700527 if (i + 1 < n) {
528 String8 monitorTags = String8(args[i + 1]);
529 if (monitorTags == "off") {
530 mTagMonitor.disableMonitoring();
531 } else {
532 mTagMonitor.parseTagsToMonitor(monitorTags);
533 }
534 } else {
535 mTagMonitor.disableMonitoring();
536 }
537 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800538 }
539
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800540 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800542 const char *status =
543 mStatus == STATUS_ERROR ? "ERROR" :
544 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700545 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
546 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800547 mStatus == STATUS_ACTIVE ? "ACTIVE" :
548 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700549
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800550 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700551 if (mStatus == STATUS_ERROR) {
552 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
553 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800555 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000556 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
557 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
558 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800559 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800560
561 if (mInputStream != NULL) {
562 write(fd, lines.string(), lines.size());
563 mInputStream->dump(fd, args);
564 } else {
565 lines.appendFormat(" No input stream.\n");
566 write(fd, lines.string(), lines.size());
567 }
568 for (size_t i = 0; i < mOutputStreams.size(); i++) {
569 mOutputStreams[i]->dump(fd,args);
570 }
571
Zhijun He431503c2016-03-07 17:30:16 -0800572 if (mBufferManager != NULL) {
573 lines = String8(" Camera3 Buffer Manager:\n");
574 write(fd, lines.string(), lines.size());
575 mBufferManager->dump(fd, args);
576 }
Zhijun He125684a2015-12-26 15:07:30 -0800577
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700578 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700579 if (mInFlightLock.try_lock()) {
580 if (mInFlightMap.size() == 0) {
581 lines.append(" None\n");
582 } else {
583 for (size_t i = 0; i < mInFlightMap.size(); i++) {
584 InFlightRequest r = mInFlightMap.valueAt(i);
585 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
586 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
587 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
588 r.numBuffersLeft);
589 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700590 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700591 mInFlightLock.unlock();
592 } else {
593 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700594 }
595 write(fd, lines.string(), lines.size());
596
Shuzhen Wang686f6442017-06-20 16:16:04 -0700597 if (mRequestThread != NULL) {
598 mRequestThread->dumpCaptureRequestLatency(fd,
599 " ProcessCaptureRequest latency histogram:");
600 }
601
Igor Murashkin1e479c02013-09-06 16:55:14 -0700602 {
603 lines = String8(" Last request sent:\n");
604 write(fd, lines.string(), lines.size());
605
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700607 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
608 }
609
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700611 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 "TEMPLATE_PREVIEW",
613 "TEMPLATE_STILL_CAPTURE",
614 "TEMPLATE_VIDEO_RECORD",
615 "TEMPLATE_VIDEO_SNAPSHOT",
616 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800617 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800618 };
619
Emilian Peevf4816702020-04-03 15:44:51 -0700620 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 camera_metadata_t *templateRequest = nullptr;
622 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700623 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 lines.append(" Not supported\n");
627 write(fd, lines.string(), lines.size());
628 } else {
629 write(fd, lines.string(), lines.size());
630 dump_indented_camera_metadata(templateRequest,
631 fd, /*verbosity*/2, /*indentation*/8);
632 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800634 }
635 }
636
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700637 mTagMonitor.dumpMonitoredMetadata(fd);
638
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800640 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800642 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 if (gotLock) mLock.unlock();
646 if (gotInterfaceLock) mInterfaceLock.unlock();
647
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800648 return OK;
649}
650
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700651status_t Camera3Device::startWatchingTags(const String8 &tags) {
652 mTagMonitor.parseTagsToMonitor(tags);
653 return OK;
654}
655
656status_t Camera3Device::stopWatchingTags() {
657 mTagMonitor.disableMonitoring();
658 return OK;
659}
660
661status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
662 mTagMonitor.getLatestMonitoredTagEvents(out);
663 return OK;
664}
665
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800666const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
669 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700670 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800671 mStatus == STATUS_ERROR ?
672 "when in error state" : "before init");
673 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700674 if (physicalId.isEmpty()) {
675 return mDeviceInfo;
676 } else {
677 std::string id(physicalId.c_str());
678 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
679 return mPhysicalDeviceInfoMap.at(id);
680 } else {
681 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
682 return mDeviceInfo;
683 }
684 }
685}
686
687const CameraMetadata& Camera3Device::info() const {
688 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800689 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800690}
691
Jianing Wei90e59c92014-03-12 18:29:36 -0700692status_t Camera3Device::checkStatusOkToCaptureLocked() {
693 switch (mStatus) {
694 case STATUS_ERROR:
695 CLOGE("Device has encountered a serious error");
696 return INVALID_OPERATION;
697 case STATUS_UNINITIALIZED:
698 CLOGE("Device not initialized");
699 return INVALID_OPERATION;
700 case STATUS_UNCONFIGURED:
701 case STATUS_CONFIGURED:
702 case STATUS_ACTIVE:
703 // OK
704 break;
705 default:
706 SET_ERR_L("Unexpected status: %d", mStatus);
707 return INVALID_OPERATION;
708 }
709 return OK;
710}
711
712status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000713 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700714 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700715 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700716 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700717 if (requestList == NULL) {
718 CLOGE("requestList cannot be NULL.");
719 return BAD_VALUE;
720 }
721
Jianing Weicb0652e2014-03-12 18:29:36 -0700722 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000723 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700724 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
725 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
726 ++metadataIt, ++surfaceMapIt) {
727 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700728 if (newRequest == 0) {
729 CLOGE("Can't create capture request");
730 return BAD_VALUE;
731 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700732
Shuzhen Wang9d066012016-09-30 11:30:20 -0700733 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700734 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700735
Jianing Weicb0652e2014-03-12 18:29:36 -0700736 // Setup burst Id and request Id
737 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800738 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
739 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700740 CLOGE("RequestID does not exist in metadata");
741 return BAD_VALUE;
742 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800743 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700744
Jianing Wei90e59c92014-03-12 18:29:36 -0700745 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700746
747 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700748 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
750 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
751 return BAD_VALUE;
752 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700753
754 // Setup batch size if this is a high speed video recording request.
755 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
756 auto firstRequest = requestList->begin();
757 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
758 if (outputStream->isVideoStream()) {
759 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800760 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700761 break;
762 }
763 }
764 }
765
Jianing Wei90e59c92014-03-12 18:29:36 -0700766 return OK;
767}
768
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800769status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771
Emilian Peevaebbe412018-01-15 13:53:24 +0000772 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700773 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000774 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700775
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800776 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777}
778
Emilian Peevaebbe412018-01-15 13:53:24 +0000779void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700780 std::list<const SurfaceMap>& surfaceMaps,
781 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000782 PhysicalCameraSettingsList requestList;
783 requestList.push_back({std::string(getId().string()), request});
784 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785
786 SurfaceMap surfaceMap;
787 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
788 // With no surface list passed in, stream and surface will have 1-to-1
789 // mapping. So the surface index is 0 for each stream in the surfaceMap.
790 for (size_t i = 0; i < streams.count; i++) {
791 surfaceMap[streams.data.i32[i]].push_back(0);
792 }
793 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800794}
795
Jianing Wei90e59c92014-03-12 18:29:36 -0700796status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000797 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 const std::list<const SurfaceMap> &surfaceMaps,
799 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 /*out*/
801 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700803 nsecs_t requestTimeNs = systemTime();
804
Jianing Wei90e59c92014-03-12 18:29:36 -0700805 Mutex::Autolock il(mInterfaceLock);
806 Mutex::Autolock l(mLock);
807
808 status_t res = checkStatusOkToCaptureLocked();
809 if (res != OK) {
810 // error logged by previous call
811 return res;
812 }
813
814 RequestList requestList;
815
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700817 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700818 if (res != OK) {
819 // error logged by previous call
820 return res;
821 }
822
823 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700824 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700826 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 }
828
829 if (res == OK) {
830 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
831 if (res != OK) {
832 SET_ERR_L("Can't transition to active in %f seconds!",
833 kActiveTimeout/1e9);
834 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700836 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837 } else {
838 CLOGE("Cannot queue request. Impossible.");
839 return BAD_VALUE;
840 }
841
842 return res;
843}
844
Emilian Peevaebbe412018-01-15 13:53:24 +0000845status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700847 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 ATRACE_CALL();
849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700851}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
854 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000859 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863}
864
Emilian Peevaebbe412018-01-15 13:53:24 +0000865status_t Camera3Device::setStreamingRequestList(
866 const List<const PhysicalCameraSettingsList> &requestsList,
867 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 ATRACE_CALL();
869
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700871}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872
873sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800875 status_t res;
876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700877 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800878 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
879 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000880 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700881 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700882 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800883 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700884 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700886 } else if (mStatus == STATUS_UNCONFIGURED) {
887 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700888 CLOGE("No streams configured");
889 return NULL;
890 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 }
892
Shuzhen Wang0129d522016-10-30 22:43:41 -0700893 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800895}
896
Jianing Weicb0652e2014-03-12 18:29:36 -0700897status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800900 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800901
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 switch (mStatus) {
903 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700904 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800905 return INVALID_OPERATION;
906 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700907 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800908 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 case STATUS_UNCONFIGURED:
910 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800911 case STATUS_ACTIVE:
912 // OK
913 break;
914 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700915 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800916 return INVALID_OPERATION;
917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700919
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700920 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800921}
922
923status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
924 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700927 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800928}
929
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700930status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800931 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700934 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700935 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
937 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700938
939 status_t res;
940 bool wasActive = false;
941
942 switch (mStatus) {
943 case STATUS_ERROR:
944 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
945 return INVALID_OPERATION;
946 case STATUS_UNINITIALIZED:
947 ALOGE("%s: Device not initialized", __FUNCTION__);
948 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 case STATUS_UNCONFIGURED:
950 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700951 // OK
952 break;
953 case STATUS_ACTIVE:
954 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700955 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700956 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700957 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700958 return res;
959 }
960 wasActive = true;
961 break;
962 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700963 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700964 return INVALID_OPERATION;
965 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700966 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700967
968 if (mInputStream != 0) {
969 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
970 return INVALID_OPERATION;
971 }
972
973 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
974 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700975 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700976
977 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800978 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979
980 *id = mNextStreamId++;
981
982 // Continue captures if active at start
983 if (wasActive) {
984 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100985 // Reuse current operating mode and session parameters for new stream config
986 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700987 if (res != OK) {
988 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
989 __FUNCTION__, mNextStreamId, strerror(-res), res);
990 return res;
991 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700992 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700993 }
994
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700996 return OK;
997}
998
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700999status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001000 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001001 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001002 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001003 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1004 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001005 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001006 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
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 Wangbce53db2022-12-03 00:38:20 +00001020 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001021}
1022
1023static bool isRawFormat(int format) {
1024 switch (format) {
1025 case HAL_PIXEL_FORMAT_RAW16:
1026 case HAL_PIXEL_FORMAT_RAW12:
1027 case HAL_PIXEL_FORMAT_RAW10:
1028 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1029 return true;
1030 default:
1031 return false;
1032 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001033}
1034
1035status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1036 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001037 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001038 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001039 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001040 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001041 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001042 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001043
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001044 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001045 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001046 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001047 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001048 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001049 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001050 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001051 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001052 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001053 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1054 useReadoutTimestamp);
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 Wangbce53db2022-12-03 00:38:20 +00001125 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
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 Wangbce53db2022-12-03 00:38:20 +00001140 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
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 Wangbce53db2022-12-03 00:38:20 +00001146 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
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 Wangbce53db2022-12-03 00:38:20 +00001152 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
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 Wangbce53db2022-12-03 00:38:20 +00001158 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
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 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001202 ALOGV("Camera %s: Created new stream", mId.string());
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();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001246 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248}
1249
1250status_t Camera3Device::setStreamTransform(int id,
1251 int transform) {
1252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 switch (mStatus) {
1257 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 case STATUS_ACTIVE:
1266 // OK
1267 break;
1268 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
1271 }
1272
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001273 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1274 if (stream == nullptr) {
1275 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return BAD_VALUE;
1277 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001278 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001279}
1280
1281status_t Camera3Device::deleteStream(int id) {
1282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 Mutex::Autolock l(mLock);
1285 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001286
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001287 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001288
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001289 // CameraDevice semantics require device to already be idle before
1290 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001292 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001293 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 }
1295
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001296 if (mStatus == STATUS_ERROR) {
1297 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1298 __FUNCTION__, mId.string());
1299 return -EBUSY;
1300 }
1301
Igor Murashkin2fba5842013-04-22 14:03:54 -07001302 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001303 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304 if (mInputStream != NULL && id == mInputStream->getId()) {
1305 deletedStream = mInputStream;
1306 mInputStream.clear();
1307 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001308 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001309 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310 return BAD_VALUE;
1311 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001312 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001313 }
1314
1315 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001316 if (stream != nullptr) {
1317 deletedStream = stream;
1318 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001319 }
1320
1321 // Free up the stream endpoint so that it can be used by some other stream
1322 res = deletedStream->disconnect();
1323 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001324 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001325 // fall through since we want to still list the stream as deleted.
1326 }
1327 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001328 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329
1330 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001331}
1332
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001333status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001334 ATRACE_CALL();
1335 ALOGV("%s: E", __FUNCTION__);
1336
1337 Mutex::Autolock il(mInterfaceLock);
1338 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001339
Emilian Peev811d2952018-05-25 11:08:40 +01001340 // In case the client doesn't include any session parameter, try a
1341 // speculative configuration using the values from the last cached
1342 // default request.
1343 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001344 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001345 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1346 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1347 mLastTemplateId);
1348 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1349 operatingMode);
1350 }
1351
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001352 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1353}
1354
1355status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1356 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001357 //Filter out any incoming session parameters
1358 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001359 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1360 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001361 CameraMetadata filteredParams(availableSessionKeys.count);
1362 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1363 filteredParams.getAndLock());
1364 set_camera_metadata_vendor_id(meta, mVendorTagId);
1365 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001366 if (availableSessionKeys.count > 0) {
1367 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 }
1373 }
1374 }
1375
1376 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001377}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001378
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001379status_t Camera3Device::getInputBufferProducer(
1380 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001381 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001382 Mutex::Autolock il(mInterfaceLock);
1383 Mutex::Autolock l(mLock);
1384
1385 if (producer == NULL) {
1386 return BAD_VALUE;
1387 } else if (mInputStream == NULL) {
1388 return INVALID_OPERATION;
1389 }
1390
1391 return mInputStream->getInputBufferProducer(producer);
1392}
1393
Emilian Peevf4816702020-04-03 15:44:51 -07001394status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001395 CameraMetadata *request) {
1396 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001397 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001398
Emilian Peevf4816702020-04-03 15:44:51 -07001399 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001400 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001401 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001402 return BAD_VALUE;
1403 }
1404
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001405 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001407 {
1408 Mutex::Autolock l(mLock);
1409 switch (mStatus) {
1410 case STATUS_ERROR:
1411 CLOGE("Device has encountered a serious error");
1412 return INVALID_OPERATION;
1413 case STATUS_UNINITIALIZED:
1414 CLOGE("Device is not initialized!");
1415 return INVALID_OPERATION;
1416 case STATUS_UNCONFIGURED:
1417 case STATUS_CONFIGURED:
1418 case STATUS_ACTIVE:
1419 // OK
1420 break;
1421 default:
1422 SET_ERR_L("Unexpected status: %d", mStatus);
1423 return INVALID_OPERATION;
1424 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001425
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001426 if (!mRequestTemplateCache[templateId].isEmpty()) {
1427 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001428 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001429 return OK;
1430 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001431 }
1432
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001433 camera_metadata_t *rawRequest;
1434 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001435 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001436
1437 {
1438 Mutex::Autolock l(mLock);
1439 if (res == BAD_VALUE) {
1440 ALOGI("%s: template %d is not supported on this camera device",
1441 __FUNCTION__, templateId);
1442 return res;
1443 } else if (res != OK) {
1444 CLOGE("Unable to construct request template %d: %s (%d)",
1445 templateId, strerror(-res), res);
1446 return res;
1447 }
1448
1449 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1450 mRequestTemplateCache[templateId].acquire(rawRequest);
1451
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001452 // Override the template request with zoomRatioMapper
1453 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1454 &mRequestTemplateCache[templateId]);
1455 if (res != OK) {
1456 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1457 templateId, strerror(-res), res);
1458 return res;
1459 }
1460
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001461 // Fill in JPEG_QUALITY if not available
1462 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1463 static const uint8_t kDefaultJpegQuality = 95;
1464 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1465 &kDefaultJpegQuality, 1);
1466 }
1467
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001468 // Fill in AUTOFRAMING if not available
1469 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1470 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1471 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1472 &kDefaultAutoframingMode, 1);
1473 }
1474
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001475 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001476 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001477 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478 return OK;
1479}
1480
1481status_t Camera3Device::waitUntilDrained() {
1482 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001483 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001484 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001487 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001488}
1489
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001490status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 switch (mStatus) {
1492 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 ALOGV("%s: Already idle", __FUNCTION__);
1495 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 case STATUS_CONFIGURED:
1497 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 case STATUS_ERROR:
1499 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 break;
1502 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001503 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 return INVALID_OPERATION;
1505 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001506 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1507 maxExpectedDuration);
1508 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001509 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001510 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001511 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1512 res);
1513 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 return res;
1515}
1516
Ruben Brunk183f0562015-08-12 12:55:02 -07001517void Camera3Device::internalUpdateStatusLocked(Status status) {
1518 mStatus = status;
1519 mRecentStatusUpdates.add(mStatus);
1520 mStatusChanged.broadcast();
1521}
1522
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001524status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001525 if (mRequestThread.get() != nullptr) {
1526 mRequestThread->setPaused(true);
1527 } else {
1528 return NO_INIT;
1529 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001530
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001531 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1532 maxExpectedDuration);
1533 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001534 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001535 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001537 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 }
1539
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 return res;
1541}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543// Resume after internalPauseAndWaitLocked
1544status_t Camera3Device::internalResumeLocked() {
1545 status_t res;
1546
1547 mRequestThread->setPaused(false);
1548
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001549 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1550 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1552 if (res != OK) {
1553 SET_ERR_L("Can't transition to active in %f seconds!",
1554 kActiveTimeout/1e9);
1555 }
1556 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558}
1559
Ruben Brunk183f0562015-08-12 12:55:02 -07001560status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001562
1563 size_t startIndex = 0;
1564 if (mStatusWaiters == 0) {
1565 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1566 // this status list
1567 mRecentStatusUpdates.clear();
1568 } else {
1569 // If other threads are waiting on updates to this status list, set the position of the
1570 // first element that this list will check rather than clearing the list.
1571 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 }
1573
Ruben Brunk183f0562015-08-12 12:55:02 -07001574 mStatusWaiters++;
1575
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001576 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001577 if (!active && mUseHalBufManager) {
1578 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001579 if (mStatus == STATUS_ACTIVE) {
1580 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001581 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001582 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001583 mRequestBufferSM.onWaitUntilIdle();
1584 }
1585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001587 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001589 if (active == (mStatus == STATUS_ACTIVE)) {
1590 // Desired state is current
1591 break;
1592 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001593
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001594 nsecs_t timeElapsed = systemTime() - startTime;
1595 nsecs_t timeToWait = timeout - timeElapsed;
1596 if (timeToWait <= 0) {
1597 // Thread woke up spuriously but has timed out since.
1598 // Force out of loop with TIMED_OUT result.
1599 res = TIMED_OUT;
1600 break;
1601 }
1602 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 if (res != OK) break;
1604
Ruben Brunk183f0562015-08-12 12:55:02 -07001605 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1606 // transitions.
1607 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1608 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1609 __FUNCTION__);
1610
1611 // Encountered desired state since we began waiting
1612 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1614 stateSeen = true;
1615 break;
1616 }
1617 }
1618 } while (!stateSeen);
1619
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001620 if (signalPipelineDrain) {
1621 mRequestThread->resetPipelineDrain();
1622 }
1623
Ruben Brunk183f0562015-08-12 12:55:02 -07001624 mStatusWaiters--;
1625
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001626 return res;
1627}
1628
1629
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001630status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001632 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001633
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001634 if (listener != NULL && mListener != NULL) {
1635 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1636 }
1637 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001638 mRequestThread->setNotificationListener(listener);
1639 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001640
1641 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642}
1643
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001644bool Camera3Device::willNotify3A() {
1645 return false;
1646}
1647
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001649 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001650 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001652 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001653 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1654 if (st == std::cv_status::timeout) {
1655 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001656 }
1657 }
1658 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659}
1660
Jianing Weicb0652e2014-03-12 18:29:36 -07001661status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001663 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001665 if (mResultQueue.empty()) {
1666 return NOT_ENOUGH_DATA;
1667 }
1668
Jianing Weicb0652e2014-03-12 18:29:36 -07001669 if (frame == NULL) {
1670 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1671 return BAD_VALUE;
1672 }
1673
1674 CaptureResult &result = *(mResultQueue.begin());
1675 frame->mResultExtras = result.mResultExtras;
1676 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001677 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 mResultQueue.erase(mResultQueue.begin());
1679
1680 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001681}
1682
1683status_t Camera3Device::triggerAutofocus(uint32_t id) {
1684 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001685 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1688 // Mix-in this trigger into the next request and only the next request.
1689 RequestTrigger trigger[] = {
1690 {
1691 ANDROID_CONTROL_AF_TRIGGER,
1692 ANDROID_CONTROL_AF_TRIGGER_START
1693 },
1694 {
1695 ANDROID_CONTROL_AF_TRIGGER_ID,
1696 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001697 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001698 };
1699
1700 return mRequestThread->queueTrigger(trigger,
1701 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001702}
1703
1704status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1705 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001708 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1709 // Mix-in this trigger into the next request and only the next request.
1710 RequestTrigger trigger[] = {
1711 {
1712 ANDROID_CONTROL_AF_TRIGGER,
1713 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1714 },
1715 {
1716 ANDROID_CONTROL_AF_TRIGGER_ID,
1717 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001718 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001719 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001721 return mRequestThread->queueTrigger(trigger,
1722 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723}
1724
1725status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1726 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001729 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1730 // Mix-in this trigger into the next request and only the next request.
1731 RequestTrigger trigger[] = {
1732 {
1733 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1734 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1735 },
1736 {
1737 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1738 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001739 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001740 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001742 return mRequestThread->queueTrigger(trigger,
1743 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744}
1745
Jianing Weicb0652e2014-03-12 18:29:36 -07001746status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001747 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001748 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001749 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001750
Zhijun He7ef20392014-04-21 16:04:17 -07001751 {
1752 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001753
1754 // b/116514106 "disconnect()" can get called twice for the same device. The
1755 // camera device will not be initialized during the second run.
1756 if (mStatus == STATUS_UNINITIALIZED) {
1757 return OK;
1758 }
1759
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001760 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001761
1762 // Stop session and stream counter
1763 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001764 }
1765
Ravneetdbd5b242022-03-02 07:22:46 +00001766 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001767 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001768 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1769 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1770
1771 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001772}
1773
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001774status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001775 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1776}
1777
1778status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001779 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001780 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001781 Mutex::Autolock il(mInterfaceLock);
1782 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001783
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001784 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1785 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001786 CLOGE("Stream %d does not exist", streamId);
1787 return BAD_VALUE;
1788 }
1789
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001790 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001791 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001792 return BAD_VALUE;
1793 }
1794
1795 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001796 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001797 return BAD_VALUE;
1798 }
1799
Ruben Brunkc78ac262015-08-13 17:58:46 -07001800 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001801}
1802
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001803status_t Camera3Device::tearDown(int streamId) {
1804 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001805 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001806 Mutex::Autolock il(mInterfaceLock);
1807 Mutex::Autolock l(mLock);
1808
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001809 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1810 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001811 CLOGE("Stream %d does not exist", streamId);
1812 return BAD_VALUE;
1813 }
1814
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001815 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1816 CLOGE("Stream %d is a target of a in-progress request", streamId);
1817 return BAD_VALUE;
1818 }
1819
1820 return stream->tearDown();
1821}
1822
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001823status_t Camera3Device::addBufferListenerForStream(int streamId,
1824 wp<Camera3StreamBufferListener> listener) {
1825 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001826 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001827 Mutex::Autolock il(mInterfaceLock);
1828 Mutex::Autolock l(mLock);
1829
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001830 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1831 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001832 CLOGE("Stream %d does not exist", streamId);
1833 return BAD_VALUE;
1834 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001835 stream->addBufferListener(listener);
1836
1837 return OK;
1838}
1839
Austin Borger4a870a32022-02-25 01:48:41 +00001840float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1841 camera_metadata_entry minDurations =
1842 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1843 for (size_t i = 0; i < minDurations.count; i += 4) {
1844 if (minDurations.data.i64[i] == stream->getFormat()
1845 && minDurations.data.i64[i+1] == stream->getWidth()
1846 && minDurations.data.i64[i+2] == stream->getHeight()) {
1847 int64_t minFrameDuration = minDurations.data.i64[i+3];
1848 return 1e9f / minFrameDuration;
1849 }
1850 }
1851 return 0.0f;
1852}
1853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 * Methods called by subclasses
1856 */
1857
1858void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001859 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001860 std::vector<int> streamIds;
1861 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001862 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001863
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 {
1865 // Need mLock to safely update state and synchronize to current
1866 // state of methods in flight.
1867 Mutex::Autolock l(mLock);
1868 // We can get various system-idle notices from the status tracker
1869 // while starting up. Only care about them if we've actually sent
1870 // in some requests recently.
1871 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1872 return;
1873 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001874 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1875 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001876 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877
1878 // Skip notifying listener if we're doing some user-transparent
1879 // state changes
1880 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001881
Austin Borger4a870a32022-02-25 01:48:41 +00001882 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1883 auto stream = mOutputStreams[i];
1884 if (stream.get() == nullptr) continue;
1885
1886 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1887 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1888
1889 // Populate stream statistics in case of Idle
1890 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001891 streamIds.push_back(stream->getId());
1892 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1893 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001894 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001895 if (camera3Stream != nullptr) {
1896 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001897 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001898 }
1899 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001900 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001901 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001902 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001903 stream->getDynamicRangeProfile(), streamUseCase,
1904 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001905 }
1906 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001907 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001908
1909 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001910 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001911 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001912 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001914 status_t res = OK;
1915 if (listener != nullptr) {
1916 if (idle) {
1917 // Get session stats from the builder, and notify the listener.
1918 int64_t requestCount, resultErrorCount;
1919 bool deviceError;
1920 std::map<int, StreamStats> streamStatsMap;
1921 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1922 &deviceError, &streamStatsMap);
1923 for (size_t i = 0; i < streamIds.size(); i++) {
1924 int streamId = streamIds[i];
1925 auto stats = streamStatsMap.find(streamId);
1926 if (stats != streamStatsMap.end()) {
1927 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1928 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1929 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1930 streamStats[i].mHistogramType =
1931 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1932 streamStats[i].mHistogramBins.assign(
1933 stats->second.mCaptureLatencyBins.begin(),
1934 stats->second.mCaptureLatencyBins.end());
1935 streamStats[i].mHistogramCounts.assign(
1936 stats->second.mCaptureLatencyHistogram.begin(),
1937 stats->second.mCaptureLatencyHistogram.end());
1938 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001939 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001940 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1941 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001942 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001943 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001944 }
1945 if (res != OK) {
1946 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1947 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 }
1949}
1950
Shuzhen Wang758c2152017-01-10 18:26:18 -08001951status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001952 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001953 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001954 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1955 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001956
1957 if (surfaceIds == nullptr) {
1958 return BAD_VALUE;
1959 }
1960
Zhijun He5d677d12016-05-29 16:52:39 -07001961 Mutex::Autolock il(mInterfaceLock);
1962 Mutex::Autolock l(mLock);
1963
Shuzhen Wang758c2152017-01-10 18:26:18 -08001964 if (consumers.size() == 0) {
1965 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001966 return BAD_VALUE;
1967 }
1968
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001969 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1970 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001971 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001972 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001973 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001974
1975 // isConsumerConfigurationDeferred will be off after setConsumers
1976 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001977 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001978 if (res != OK) {
1979 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1980 return res;
1981 }
1982
Emilian Peev40ead602017-09-26 15:46:36 +01001983 for (auto &consumer : consumers) {
1984 int id = stream->getSurfaceId(consumer);
1985 if (id < 0) {
1986 CLOGE("Invalid surface id!");
1987 return BAD_VALUE;
1988 }
1989 surfaceIds->push_back(id);
1990 }
1991
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001992 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001993 if (!stream->isConfiguring()) {
1994 CLOGE("Stream %d was already fully configured.", streamId);
1995 return INVALID_OPERATION;
1996 }
Zhijun He5d677d12016-05-29 16:52:39 -07001997
Shuzhen Wang0129d522016-10-30 22:43:41 -07001998 res = stream->finishConfiguration();
1999 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002000 // If finishConfiguration fails due to abandoned surface, do not set
2001 // device to error state.
2002 bool isSurfaceAbandoned =
2003 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2004 if (!isSurfaceAbandoned) {
2005 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2006 stream->getId(), strerror(-res), res);
2007 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002008 return res;
2009 }
Zhijun He5d677d12016-05-29 16:52:39 -07002010 }
2011
2012 return OK;
2013}
2014
Emilian Peev40ead602017-09-26 15:46:36 +01002015status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2016 const std::vector<OutputStreamInfo> &outputInfo,
2017 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2018 Mutex::Autolock il(mInterfaceLock);
2019 Mutex::Autolock l(mLock);
2020
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002021 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2022 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002023 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002024 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002025 }
2026
2027 for (const auto &it : removedSurfaceIds) {
2028 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2029 CLOGE("Shared surface still part of a pending request!");
2030 return -EBUSY;
2031 }
2032 }
2033
Emilian Peev40ead602017-09-26 15:46:36 +01002034 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2035 if (res != OK) {
2036 CLOGE("Stream %d failed to update stream (error %d %s) ",
2037 streamId, res, strerror(-res));
2038 if (res == UNKNOWN_ERROR) {
2039 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2040 __FUNCTION__);
2041 }
2042 return res;
2043 }
2044
2045 return res;
2046}
2047
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002048status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002052 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2053 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002054 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2055 return BAD_VALUE;
2056 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002057
2058 if (dropping) {
2059 mSessionStatsBuilder.stopCounter(streamId);
2060 } else {
2061 mSessionStatsBuilder.startCounter(streamId);
2062 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002063 return stream->dropBuffers(dropping);
2064}
2065
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 * Camera3Device private methods
2068 */
2069
2070sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002071 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002074 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002075 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076
2077 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002078 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 if (inputStreams.count > 0) {
2080 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002081 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002082 CLOGE("Request references unknown input stream %d",
2083 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084 return NULL;
2085 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002086
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002088 SET_ERR_L("%s: input stream %d is not configured!",
2089 __FUNCTION__, mInputStream->getId());
2090 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002091 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002092 // Check if stream prepare is blocking requests.
2093 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094 CLOGE("Request references an input stream that's being prepared!");
2095 return NULL;
2096 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097
2098 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002099 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 }
2101
2102 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002103 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002105 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002106 return NULL;
2107 }
2108
2109 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002110 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2111 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002112 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002113 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114 return NULL;
2115 }
Zhijun He5d677d12016-05-29 16:52:39 -07002116 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002117 auto iter = surfaceMap.find(streams.data.i32[i]);
2118 if (iter != surfaceMap.end()) {
2119 const std::vector<size_t>& surfaces = iter->second;
2120 for (const auto& surface : surfaces) {
2121 if (stream->isConsumerConfigurationDeferred(surface)) {
2122 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2123 "due to deferred consumer", stream->getId(), surface);
2124 return NULL;
2125 }
2126 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002127 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002128 }
2129
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002131 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2132 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002134 // Check if stream prepare is blocking requests.
2135 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002136 CLOGE("Request references an output stream that's being prepared!");
2137 return NULL;
2138 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139
2140 newRequest->mOutputStreams.push(stream);
2141 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002142 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002143 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002145 auto rotateAndCropEntry =
2146 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2147 if (rotateAndCropEntry.count > 0 &&
2148 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2149 newRequest->mRotateAndCropAuto = true;
2150 } else {
2151 newRequest->mRotateAndCropAuto = false;
2152 }
2153
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002154 auto autoframingEntry =
2155 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2156 if (autoframingEntry.count > 0 &&
2157 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2158 newRequest->mAutoframingAuto = true;
2159 } else {
2160 newRequest->mAutoframingAuto = false;
2161 }
2162
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002163 auto zoomRatioEntry =
2164 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2165 if (zoomRatioEntry.count > 0 &&
2166 zoomRatioEntry.data.f[0] == 1.0f) {
2167 newRequest->mZoomRatioIs1x = true;
2168 } else {
2169 newRequest->mZoomRatioIs1x = false;
2170 }
2171
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002172 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002173 for (auto& settings : newRequest->mSettingsList) {
2174 auto testPatternModeEntry =
2175 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2176 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2177 testPatternModeEntry.data.i32[0] :
2178 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002179
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002180 auto testPatternDataEntry =
2181 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2182 if (testPatternDataEntry.count >= 4) {
2183 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2184 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2185 } else {
2186 settings.mOriginalTestPatternData[0] = 0;
2187 settings.mOriginalTestPatternData[1] = 0;
2188 settings.mOriginalTestPatternData[2] = 0;
2189 settings.mOriginalTestPatternData[3] = 0;
2190 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002191 }
2192 }
2193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002195}
2196
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002197void Camera3Device::cancelStreamsConfigurationLocked() {
2198 int res = OK;
2199 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2200 res = mInputStream->cancelConfiguration();
2201 if (res != OK) {
2202 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2203 mInputStream->getId(), strerror(-res), res);
2204 }
2205 }
2206
2207 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002208 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002209 if (outputStream->isConfiguring()) {
2210 res = outputStream->cancelConfiguration();
2211 if (res != OK) {
2212 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2213 outputStream->getId(), strerror(-res), res);
2214 }
2215 }
2216 }
2217
2218 // Return state to that at start of call, so that future configures
2219 // properly clean things up
2220 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2221 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002222
2223 res = mPreparerThread->resume();
2224 if (res != OK) {
2225 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2226 }
2227}
2228
Emilian Peev0d0191e2020-04-21 17:01:18 -07002229bool Camera3Device::checkAbandonedStreamsLocked() {
2230 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2231 return true;
2232 }
2233
2234 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2235 auto stream = mOutputStreams[i];
2236 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2237 return true;
2238 }
2239 }
2240
2241 return false;
2242}
2243
Emilian Peev3bead5f2020-05-28 17:29:08 -07002244bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002245 ATRACE_CALL();
2246 bool ret = false;
2247
Shuzhen Wang316781a2020-08-18 18:11:01 -07002248 nsecs_t startTime = systemTime();
2249
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002250 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002251 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2252
2253 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002254 if (checkAbandonedStreamsLocked()) {
2255 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2256 __FUNCTION__);
2257 return true;
2258 }
2259
Emilian Peev3bead5f2020-05-28 17:29:08 -07002260 status_t rc = NO_ERROR;
2261 bool markClientActive = false;
2262 if (mStatus == STATUS_ACTIVE) {
2263 markClientActive = true;
2264 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002265
2266 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2267 }
2268
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002269 if (rc == NO_ERROR) {
2270 mNeedConfig = true;
2271 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2272 if (rc == NO_ERROR) {
2273 ret = true;
2274 mPauseStateNotify = false;
2275 //Moving to active state while holding 'mLock' is important.
2276 //There could be pending calls to 'create-/deleteStream' which
2277 //will trigger another stream configuration while the already
2278 //present streams end up with outstanding buffers that will
2279 //not get drained.
2280 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002281 } else if (rc == DEAD_OBJECT) {
2282 // DEAD_OBJECT can be returned if either the consumer surface is
2283 // abandoned, or the HAL has died.
2284 // - If the HAL has died, configureStreamsLocked call will set
2285 // device to error state,
2286 // - If surface is abandoned, we should not set device to error
2287 // state.
2288 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002289 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002290 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002291 }
2292 } else {
2293 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2294 }
2295
Austin Borger74fca042022-05-23 12:41:21 -07002296 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002297 ns2ms(systemTime() - startTime));
2298
Emilian Peev3bead5f2020-05-28 17:29:08 -07002299 if (markClientActive) {
2300 mStatusTracker->markComponentActive(clientStatusId);
2301 }
2302
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002303 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002304}
2305
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002306status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002307 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 ATRACE_CALL();
2309 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002310
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002311 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002312 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 return INVALID_OPERATION;
2314 }
2315
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002316 if (operatingMode < 0) {
2317 CLOGE("Invalid operating mode: %d", operatingMode);
2318 return BAD_VALUE;
2319 }
2320
2321 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002322 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002323
2324 if (mOperatingMode != operatingMode) {
2325 mNeedConfig = true;
2326 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2327 mOperatingMode = operatingMode;
2328 }
2329
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002330 // Reset min expected duration when session is reconfigured.
2331 mMinExpectedDuration = 0;
2332
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002333 // In case called from configureStreams, abort queued input buffers not belonging to
2334 // any pending requests.
2335 if (mInputStream != NULL && notifyRequestThread) {
2336 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002337 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002338 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002339 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002340 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002341 if (res != OK) {
2342 // Exhausted acquiring all input buffers.
2343 break;
2344 }
2345
Emilian Peevf4816702020-04-03 15:44:51 -07002346 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002347 res = mInputStream->returnInputBuffer(inputBuffer);
2348 if (res != OK) {
2349 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2350 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2351 }
2352 }
2353 }
2354
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002355 if (!mNeedConfig) {
2356 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2357 return OK;
2358 }
2359
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002360 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002361 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002362 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2363 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002364 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002365 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002366 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002367 }
2368
Shuzhen Wang16610a62022-12-15 22:38:07 -08002369 // Override stream use case based on "adb shell command"
2370 overrideStreamUseCaseLocked();
2371
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002372 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002373 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002375 mPreparerThread->pause();
2376
Emilian Peevf4816702020-04-03 15:44:51 -07002377 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002378 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002380 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381
Emilian Peevf4816702020-04-03 15:44:51 -07002382 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002384 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386
2387 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002388 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389 inputStream = mInputStream->startConfiguration();
2390 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002391 CLOGE("Can't start input stream configuration");
2392 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 return INVALID_OPERATION;
2394 }
2395 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002396
2397 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 }
2399
Shuzhen Wang99080502021-03-07 21:08:20 -08002400 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002401 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002402 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002403
2404 // Don't configure bidi streams twice, nor add them twice to the list
2405 if (mOutputStreams[i].get() ==
2406 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2407
2408 config.num_streams--;
2409 continue;
2410 }
2411
Emilian Peevf4816702020-04-03 15:44:51 -07002412 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002413 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002415 CLOGE("Can't start output stream configuration");
2416 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417 return INVALID_OPERATION;
2418 }
2419 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002420
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002421 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002422 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2423 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002424 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2425 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002426 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2427 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002428 } else if (outputStream->data_space ==
2429 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2430 bufferSizes[k] = outputStream->width * outputStream->height;
2431 } else {
2432 ALOGW("%s: Blob dataSpace %d not supported",
2433 __FUNCTION__, outputStream->data_space);
2434 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002435 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002436
2437 if (mOutputStreams[i]->isMultiResolution()) {
2438 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2439 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2440 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2441 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002442
2443 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2444 composerSurfacePresent = true;
2445 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 }
2447
2448 config.streams = streams.editArray();
2449
2450 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002451 // max_buffers, usage, and priv fields, as well as data_space and format
2452 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002453
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002454 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002455 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002456 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002457 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002458
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002459 if (res == BAD_VALUE) {
2460 // HAL rejected this set of streams as unsupported, clean up config
2461 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002462 CLOGE("Set of requested inputs/outputs not supported by HAL");
2463 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002464 return BAD_VALUE;
2465 } else if (res != OK) {
2466 // Some other kind of error from configure_streams - this is not
2467 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002468 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2469 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002470 return res;
2471 }
2472
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002473 // Finish all stream configuration immediately.
2474 // TODO: Try to relax this later back to lazy completion, which should be
2475 // faster
2476
Igor Murashkin073f8572013-05-02 14:59:28 -07002477 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002478 bool streamReConfigured = false;
2479 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002480 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002481 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002482 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002483 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002484 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2485 return DEAD_OBJECT;
2486 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002487 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002488 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002489 if (streamReConfigured) {
2490 mInterface->onStreamReConfigured(mInputStream->getId());
2491 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002492 }
2493
2494 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002495 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002496 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002497 bool streamReConfigured = false;
2498 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002499 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002500 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002501 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002503 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2504 return DEAD_OBJECT;
2505 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002506 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002507 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002508 if (streamReConfigured) {
2509 mInterface->onStreamReConfigured(outputStream->getId());
2510 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002511 }
2512 }
2513
Emilian Peeve23f1d92021-09-20 14:56:01 -07002514 mRequestThread->setComposerSurface(composerSurfacePresent);
2515
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002516 // Request thread needs to know to avoid using repeat-last-settings protocol
2517 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002518 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002519 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2520 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002521 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002522
Zhijun He90f7c372016-08-16 16:19:43 -07002523 char value[PROPERTY_VALUE_MAX];
2524 property_get("camera.fifo.disable", value, "0");
2525 int32_t disableFifo = atoi(value);
2526 if (disableFifo != 1) {
2527 // Boost priority of request thread to SCHED_FIFO.
2528 pid_t requestThreadTid = mRequestThread->getTid();
2529 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002530 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002531 if (res != OK) {
2532 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2533 strerror(-res), res);
2534 } else {
2535 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2536 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002537 }
2538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002539 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002540 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2541 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2542 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2543 sessionParams.unlock(newSessionParams);
2544 mSessionParams.unlock(currentSessionParams);
2545 if (updateSessionParams) {
2546 mSessionParams = sessionParams;
2547 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002548
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002549 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002550
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002552 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002553
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002554 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002555
Zhijun He0a210512014-07-24 13:45:15 -07002556 // tear down the deleted streams after configure streams.
2557 mDeletedStreams.clear();
2558
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002559 auto rc = mPreparerThread->resume();
2560 if (rc != OK) {
2561 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2562 return rc;
2563 }
2564
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002565 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002566 mRequestBufferSM.onStreamsConfigured();
2567 }
2568
Cliff Wu3b268182021-07-06 15:44:43 +08002569 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002570 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002571 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002572 // configure the injection streams.
2573 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002574 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002575 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2576 res = mInjectionMethods->injectCamera(config, bufferSizes);
2577 if (res != OK) {
2578 ALOGE("Can't finish inject camera process!");
2579 return res;
2580 }
Cliff Wu3b268182021-07-06 15:44:43 +08002581 } else {
2582 // First run configureStreamsLocked() and then call injectCamera() case:
2583 // If the stream configuration has been completed and camera deive is active, but the
2584 // injection camera has not been injected yet, we need to store the stream configuration of
2585 // the internal camera (because the stream configuration of the injection camera is based
2586 // on the internal camera). When injecting occurs later, this configuration can be used by
2587 // the injection camera.
2588 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2589 " injection camera has not been injected yet.", __FUNCTION__);
2590 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002591 }
2592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002594}
2595
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002596status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002597 ATRACE_CALL();
2598 status_t res;
2599
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002600 if (mFakeStreamId != NO_STREAM) {
2601 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002602 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002603 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002604 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002605 return INVALID_OPERATION;
2606 }
2607
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002608 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002609
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002610 sp<Camera3OutputStreamInterface> fakeStream =
2611 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002612
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002613 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002614 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002615 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616 return res;
2617 }
2618
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002619 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002620 mNextStreamId++;
2621
2622 return OK;
2623}
2624
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002625status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002626 ATRACE_CALL();
2627 status_t res;
2628
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002629 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002630 if (mOutputStreams.size() == 1) return OK;
2631
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002632 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002633
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002634 // Ok, have a fake stream and there's at least one other output stream,
2635 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002636
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002637 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002638 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002639 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002640 return INVALID_OPERATION;
2641 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002642 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002643
2644 // Free up the stream endpoint so that it can be used by some other stream
2645 res = deletedStream->disconnect();
2646 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002647 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002648 // fall through since we want to still list the stream as deleted.
2649 }
2650 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652
2653 return res;
2654}
2655
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002656void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002657 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002658 Mutex::Autolock l(mLock);
2659 va_list args;
2660 va_start(args, fmt);
2661
2662 setErrorStateLockedV(fmt, args);
2663
2664 va_end(args);
2665}
2666
2667void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002668 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002669 Mutex::Autolock l(mLock);
2670 setErrorStateLockedV(fmt, args);
2671}
2672
2673void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2674 va_list args;
2675 va_start(args, fmt);
2676
2677 setErrorStateLockedV(fmt, args);
2678
2679 va_end(args);
2680}
2681
2682void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002683 // Print out all error messages to log
2684 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002685 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002686
2687 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002688 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002689
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002690 mErrorCause = errorCause;
2691
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002692 if (mRequestThread != nullptr) {
2693 mRequestThread->setPaused(true);
2694 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002695 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002696
2697 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002698 sp<NotificationListener> listener = mListener.promote();
2699 if (listener != NULL) {
2700 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002701 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002702 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002703 }
2704
2705 // Save stack trace. View by dumping it later.
2706 CameraTraces::saveTrace();
2707 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002708}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002709
2710/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002711 * In-flight request management
2712 */
2713
Jianing Weicb0652e2014-03-12 18:29:36 -07002714status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002715 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002716 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002717 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002718 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002719 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002720 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002721 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002722 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723
2724 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002725 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002726 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002727 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2728 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002729 if (res < 0) return res;
2730
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002731 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002732 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2733 // avoid a deadlock during reprocess requests.
2734 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002735 if (mStatusTracker != nullptr) {
2736 mStatusTracker->markComponentActive(mInFlightStatusId);
2737 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002738 }
2739
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002740 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002741 return OK;
2742}
2743
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002744void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002745 // Indicate idle inFlightMap to the status tracker
2746 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002747 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002748 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2749 // avoid a deadlock during reprocess requests.
2750 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002751 if (mStatusTracker != nullptr) {
2752 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2753 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002754 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002755 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002756}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002757
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002758void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002759 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002760 // something has likely gone wrong. This might still be legit only if application send in
2761 // a long burst of long exposure requests.
2762 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2763 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2764 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2765 mInFlightMap.size(), mExpectedInflightDuration);
2766 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2767 kInFlightWarnLimitHighSpeed) {
2768 CLOGW("In-flight list too large for high speed configuration: %zu,"
2769 "total inflight duration %" PRIu64,
2770 mInFlightMap.size(), mExpectedInflightDuration);
2771 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002772 }
2773}
2774
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002775void Camera3Device::onInflightMapFlushedLocked() {
2776 mExpectedInflightDuration = 0;
2777}
2778
2779void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002780 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002781 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2782 mInFlightMap.removeItemsAt(idx, 1);
2783
2784 onInflightEntryRemovedLocked(duration);
2785}
2786
2787
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002788void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002789 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002790 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002791 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002792 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002793 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002794 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002795
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002796 FlushInflightReqStates states {
2797 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002798 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002799
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002801}
2802
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002803CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002804 ALOGV("%s", __FUNCTION__);
2805
Igor Murashkin1e479c02013-09-06 16:55:14 -07002806 CameraMetadata retVal;
2807
2808 if (mRequestThread != NULL) {
2809 retVal = mRequestThread->getLatestRequest();
2810 }
2811
Igor Murashkin1e479c02013-09-06 16:55:14 -07002812 return retVal;
2813}
2814
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002815void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002816 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002817 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002818 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2819 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002820
2821 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002822 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002823}
2824
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002825void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002826 std::vector<native_handle_t*> *handles, bool closeFd) {
2827 if (handles == nullptr) {
2828 return;
2829 }
2830 if (closeFd) {
2831 for (auto& handle : *handles) {
2832 native_handle_close(handle);
2833 }
2834 }
2835 for (auto& handle : *handles) {
2836 native_handle_delete(handle);
2837 }
2838 handles->clear();
2839 return;
2840}
2841
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002842/**
2843 * HalInterface inner class methods
2844 */
2845
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002846void Camera3Device::HalInterface::getInflightBufferKeys(
2847 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002848 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002849 return;
2850}
2851
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002852void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2853 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002854 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002855 return;
2856}
2857
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002858bool Camera3Device::HalInterface::verifyBufferIds(
2859 int32_t streamId, std::vector<uint64_t>& bufIds) {
2860 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002861}
2862
2863status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002864 int32_t frameNumber, int32_t streamId,
2865 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002866 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002867}
2868
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002869status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002870 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002871 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002872}
2873
2874// Find and pop a buffer_handle_t based on bufferId
2875status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002876 uint64_t bufferId,
2877 /*out*/ buffer_handle_t** buffer,
2878 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002879 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002880}
2881
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002882std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2883 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002884 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002885}
2886
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002887uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2888 const native_handle_t* handle) {
2889 return mBufferRecords.removeOneBufferCache(streamId, handle);
2890}
2891
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002892void Camera3Device::HalInterface::onBufferFreed(
2893 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002894 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2895 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2896 if (bufferId != BUFFER_ID_NO_BUFFER) {
2897 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002898 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002899}
2900
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002901void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002902 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2903 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2904 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002905 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2906 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002907}
2908
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002909/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002910 * RequestThread inner class methods
2911 */
2912
2913Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002914 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002915 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002916 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002917 bool supportCameraMute,
2918 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002919 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002920 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002921 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002923 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002924 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002925 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002926 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002927 mReconfigured(false),
2928 mDoPause(false),
2929 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002930 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002931 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002932 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002933 mCurrentAfTriggerId(0),
2934 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002935 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00002936 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002937 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002938 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002939 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 mRepeatingLastFrameNumber(
2941 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002942 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002943 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002944 mRequestLatency(kRequestLatencyBinSize),
2945 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002946 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002947 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07002948 mSupportCameraMute(supportCameraMute),
2949 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002950 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08002951 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002952}
2953
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954Camera3Device::RequestThread::~RequestThread() {}
2955
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002956void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002957 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002958 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002959 Mutex::Autolock l(mRequestLock);
2960 mListener = listener;
2961}
2962
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002963void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002964 const CameraMetadata& sessionParams,
2965 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002966 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002967 Mutex::Autolock l(mRequestLock);
2968 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002969 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002970 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002971 // Prepare video stream for high speed recording.
2972 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002973 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974}
2975
Jianing Wei90e59c92014-03-12 18:29:36 -07002976status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002977 List<sp<CaptureRequest> > &requests,
2978 /*out*/
2979 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002980 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002981 Mutex::Autolock l(mRequestLock);
2982 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2983 ++it) {
2984 mRequestQueue.push_back(*it);
2985 }
2986
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002987 if (lastFrameNumber != NULL) {
2988 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2989 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2990 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2991 *lastFrameNumber);
2992 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002993
Jianing Wei90e59c92014-03-12 18:29:36 -07002994 unpauseForNewRequests();
2995
2996 return OK;
2997}
2998
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002999
3000status_t Camera3Device::RequestThread::queueTrigger(
3001 RequestTrigger trigger[],
3002 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003003 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003004 Mutex::Autolock l(mTriggerMutex);
3005 status_t ret;
3006
3007 for (size_t i = 0; i < count; ++i) {
3008 ret = queueTriggerLocked(trigger[i]);
3009
3010 if (ret != OK) {
3011 return ret;
3012 }
3013 }
3014
3015 return OK;
3016}
3017
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003018const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3019 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003020 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003021 if (d != nullptr) return d->mId;
3022 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023}
3024
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003025status_t Camera3Device::RequestThread::queueTriggerLocked(
3026 RequestTrigger trigger) {
3027
3028 uint32_t tag = trigger.metadataTag;
3029 ssize_t index = mTriggerMap.indexOfKey(tag);
3030
3031 switch (trigger.getTagType()) {
3032 case TYPE_BYTE:
3033 // fall-through
3034 case TYPE_INT32:
3035 break;
3036 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003037 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3038 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003039 return INVALID_OPERATION;
3040 }
3041
3042 /**
3043 * Collect only the latest trigger, since we only have 1 field
3044 * in the request settings per trigger tag, and can't send more than 1
3045 * trigger per request.
3046 */
3047 if (index != NAME_NOT_FOUND) {
3048 mTriggerMap.editValueAt(index) = trigger;
3049 } else {
3050 mTriggerMap.add(tag, trigger);
3051 }
3052
3053 return OK;
3054}
3055
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003056status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003057 const RequestList &requests,
3058 /*out*/
3059 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003061 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003062 if (lastFrameNumber != NULL) {
3063 *lastFrameNumber = mRepeatingLastFrameNumber;
3064 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003065 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003066 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003067 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3068 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003069
3070 unpauseForNewRequests();
3071
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003073 return OK;
3074}
3075
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003076bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003077 if (mRepeatingRequests.empty()) {
3078 return false;
3079 }
3080 int32_t requestId = requestIn->mResultExtras.requestId;
3081 const RequestList &repeatRequests = mRepeatingRequests;
3082 // All repeating requests are guaranteed to have same id so only check first quest
3083 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3084 return (firstRequest->mResultExtras.requestId == requestId);
3085}
3086
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003087status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003088 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003089 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003090 return clearRepeatingRequestsLocked(lastFrameNumber);
3091
3092}
3093
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003094status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3095 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003096 std::vector<int32_t> streamIds;
3097 for (const auto& request : mRepeatingRequests) {
3098 for (const auto& stream : request->mOutputStreams) {
3099 streamIds.push_back(stream->getId());
3100 }
3101 }
3102
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003103 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003104 if (lastFrameNumber != NULL) {
3105 *lastFrameNumber = mRepeatingLastFrameNumber;
3106 }
Emilian Peev2295df72021-11-12 18:14:10 -08003107
3108 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003111 return OK;
3112}
3113
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003114status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003115 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003116 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003117 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003118 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003120 // Send errors for all requests pending in the request queue, including
3121 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003122 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003123 if (listener != NULL) {
3124 for (RequestList::iterator it = mRequestQueue.begin();
3125 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003126 // Abort the input buffers for reprocess requests.
3127 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003128 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003129 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003130 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003131 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003132 if (res != OK) {
3133 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3134 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3135 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003136 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003137 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3138 if (res != OK) {
3139 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3140 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3141 }
3142 }
3143 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003144 // Set the frame number this request would have had, if it
3145 // had been submitted; this frame number will not be reused.
3146 // The requestId and burstId fields were set when the request was
3147 // submitted originally (in convertMetadataListToRequestListLocked)
3148 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003149 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003150 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003151 }
3152 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003153 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003154
3155 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003156 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003157 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003158 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003159 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003160 return OK;
3161}
3162
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003163status_t Camera3Device::RequestThread::flush() {
3164 ATRACE_CALL();
3165 Mutex::Autolock l(mFlushLock);
3166
Emilian Peev08dd2452017-04-06 16:55:14 +01003167 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003168}
3169
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003170void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003171 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003172 Mutex::Autolock l(mPauseLock);
3173 mDoPause = paused;
3174 mDoPauseSignal.signal();
3175}
3176
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003177status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3178 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003179 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003180 Mutex::Autolock l(mLatestRequestMutex);
3181 status_t res;
3182 while (mLatestRequestId != requestId) {
3183 nsecs_t startTime = systemTime();
3184
3185 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3186 if (res != OK) return res;
3187
3188 timeout -= (systemTime() - startTime);
3189 }
3190
3191 return OK;
3192}
3193
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003194void Camera3Device::RequestThread::requestExit() {
3195 // Call parent to set up shutdown
3196 Thread::requestExit();
3197 // The exit from any possible waits
3198 mDoPauseSignal.signal();
3199 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003200
3201 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3202 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003203}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003204
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003205void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003206 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003207 bool surfaceAbandoned = false;
3208 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003209 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003210 {
3211 Mutex::Autolock l(mRequestLock);
3212 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3213 // repeating requests.
3214 for (const auto& request : mRepeatingRequests) {
3215 for (const auto& s : request->mOutputStreams) {
3216 if (s->isAbandoned()) {
3217 surfaceAbandoned = true;
3218 clearRepeatingRequestsLocked(&lastFrameNumber);
3219 break;
3220 }
3221 }
3222 if (surfaceAbandoned) {
3223 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003224 }
3225 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003226 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003227 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003228
3229 if (listener != NULL && surfaceAbandoned) {
3230 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003231 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003232}
3233
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003234bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003235 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003236 status_t res;
3237 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003238 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003239 uint32_t numRequestProcessed = 0;
3240 for (size_t i = 0; i < batchSize; i++) {
3241 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003242 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003243 }
3244
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003245 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3246
3247 bool triggerRemoveFailed = false;
3248 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3249 for (size_t i = 0; i < numRequestProcessed; i++) {
3250 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3251 nextRequest.submitted = true;
3252
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003253 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003254
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003255 if (!triggerRemoveFailed) {
3256 // Remove any previously queued triggers (after unlock)
3257 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3258 if (removeTriggerRes != OK) {
3259 triggerRemoveFailed = true;
3260 triggerFailedRequest = nextRequest;
3261 }
3262 }
3263 }
3264
3265 if (triggerRemoveFailed) {
3266 SET_ERR("RequestThread: Unable to remove triggers "
3267 "(capture request %d, HAL device: %s (%d)",
3268 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3269 cleanUpFailedRequests(/*sendRequestError*/ false);
3270 return false;
3271 }
3272
3273 if (res != OK) {
3274 // Should only get a failure here for malformed requests or device-level
3275 // errors, so consider all errors fatal. Bad metadata failures should
3276 // come through notify.
3277 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3278 mNextRequests[numRequestProcessed].halRequest.frame_number,
3279 strerror(-res), res);
3280 cleanUpFailedRequests(/*sendRequestError*/ false);
3281 return false;
3282 }
3283 return true;
3284}
3285
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003286Camera3Device::RequestThread::ExpectedDurationInfo
3287 Camera3Device::RequestThread::calculateExpectedDurationRange(
3288 const camera_metadata_t *request) {
3289 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003290 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003291 InFlightRequest::kDefaultMaxExpectedDuration,
3292 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003293 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3294 find_camera_metadata_ro_entry(request,
3295 ANDROID_CONTROL_AE_MODE,
3296 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003297 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003298
3299 switch (e.data.u8[0]) {
3300 case ANDROID_CONTROL_AE_MODE_OFF:
3301 find_camera_metadata_ro_entry(request,
3302 ANDROID_SENSOR_EXPOSURE_TIME,
3303 &e);
3304 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003305 expectedDurationInfo.minDuration = e.data.i64[0];
3306 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003307 }
3308 find_camera_metadata_ro_entry(request,
3309 ANDROID_SENSOR_FRAME_DURATION,
3310 &e);
3311 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003312 expectedDurationInfo.minDuration =
3313 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3314 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003315 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003316 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003317 break;
3318 default:
3319 find_camera_metadata_ro_entry(request,
3320 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3321 &e);
3322 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003323 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3324 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003325 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003326 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003327 break;
3328 }
3329
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003330 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003331}
3332
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003333bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3334 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3335 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3336 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3337 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3338 return true;
3339 }
3340
3341 return false;
3342}
3343
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003344void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3345 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003346 camera_capture_request_t& halRequest = nextRequest.halRequest;
3347 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003348 Mutex::Autolock al(mLatestRequestMutex);
3349
Shuzhen Wang83bff122020-11-20 15:51:39 -08003350 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003351 mLatestRequest.acquire(cloned);
3352
3353 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003354 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3355 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3356 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003357 CameraMetadata(cloned));
3358 }
3359
3360 sp<Camera3Device> parent = mParent.promote();
3361 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003362 int32_t inputStreamId = -1;
3363 if (halRequest.input_buffer != nullptr) {
3364 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3365 }
3366
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003367 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003368 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003369 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3370 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003371 }
3372 }
3373
Shuzhen Wang83bff122020-11-20 15:51:39 -08003374 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003375 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003376 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003377 }
3378
Shuzhen Wang83bff122020-11-20 15:51:39 -08003379 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003380}
3381
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003382bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3383 ATRACE_CALL();
3384 bool updatesDetected = false;
3385
Emilian Peev4ec17882019-01-24 17:16:58 -08003386 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003387 for (auto tag : mSessionParamKeys) {
3388 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003389 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003390
3391 if (entry.count > 0) {
3392 bool isDifferent = false;
3393 if (lastEntry.count > 0) {
3394 // Have a last value, compare to see if changed
3395 if (lastEntry.type == entry.type &&
3396 lastEntry.count == entry.count) {
3397 // Same type and count, compare values
3398 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3399 size_t entryBytes = bytesPerValue * lastEntry.count;
3400 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3401 if (cmp != 0) {
3402 isDifferent = true;
3403 }
3404 } else {
3405 // Count or type has changed
3406 isDifferent = true;
3407 }
3408 } else {
3409 // No last entry, so always consider to be different
3410 isDifferent = true;
3411 }
3412
3413 if (isDifferent) {
3414 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003415 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3416 updatesDetected = true;
3417 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003418 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003419 }
3420 } else if (lastEntry.count > 0) {
3421 // Value has been removed
3422 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003423 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003424 updatesDetected = true;
3425 }
3426 }
3427
Emilian Peev4ec17882019-01-24 17:16:58 -08003428 bool reconfigureRequired;
3429 if (updatesDetected) {
3430 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3431 updatedParams);
3432 mLatestSessionParams = updatedParams;
3433 } else {
3434 reconfigureRequired = false;
3435 }
3436
3437 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003438}
3439
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003440bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003441 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003442 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003443 // Any function called from threadLoop() must not hold mInterfaceLock since
3444 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3445 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446
3447 // Handle paused state.
3448 if (waitIfPaused()) {
3449 return true;
3450 }
3451
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003452 // Wait for the next batch of requests.
3453 waitForNextRequestBatch();
3454 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003455 return true;
3456 }
3457
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003458 // Get the latest request ID, if any
3459 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003460 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003461 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003462 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003463 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003464 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003465 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3466 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003467 }
3468
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003469 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3470 // or a single request from streaming or burst. In either case the first element
3471 // should contain the latest camera settings that we need to check for any session
3472 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003473 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003474 res = OK;
3475
3476 //Input stream buffers are already acquired at this point so an input stream
3477 //will not be able to move to idle state unless we force it.
3478 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3479 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3480 if (res != OK) {
3481 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3482 cleanUpFailedRequests(/*sendRequestError*/ false);
3483 return false;
3484 }
3485 }
3486
3487 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003488 sp<Camera3Device> parent = mParent.promote();
3489 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003490 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3491 if (statusTracker != nullptr) {
3492 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3493 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003494 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003495 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003496 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003497
3498 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3499 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3500 if (res != OK) {
3501 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3502 cleanUpFailedRequests(/*sendRequestError*/ false);
3503 return false;
3504 }
3505 }
3506 }
3507 }
3508
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003509 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003510 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003511 if (res == TIMED_OUT) {
3512 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003513 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003514 // Check if any stream is abandoned.
3515 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003516 return true;
3517 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003518 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003519 return false;
3520 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003521
Zhijun Hecc27e112013-10-03 16:12:43 -07003522 // Inform waitUntilRequestProcessed thread of a new request ID
3523 {
3524 Mutex::Autolock al(mLatestRequestMutex);
3525
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003526 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003527 mLatestRequestSignal.signal();
3528 }
3529
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003530 // Submit a batch of requests to HAL.
3531 // Use flush lock only when submitting multilple requests in a batch.
3532 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3533 // which may take a long time to finish so synchronizing flush() and
3534 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3535 // For now, only synchronize for high speed recording and we should figure something out for
3536 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003537 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003539 if (useFlushLock) {
3540 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003541 }
3542
Zhijun Hef0645c12016-08-02 00:58:11 -07003543 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003544 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003545
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003546 sp<Camera3Device> parent = mParent.promote();
3547 if (parent != nullptr) {
3548 parent->mRequestBufferSM.onSubmittingRequest();
3549 }
3550
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003551 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003552 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003553 submitRequestSuccess = sendRequestsBatch();
3554
Shuzhen Wang686f6442017-06-20 16:16:04 -07003555 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3556 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003557
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003558 if (useFlushLock) {
3559 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003560 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003561
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003562 // Unset as current request
3563 {
3564 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003565 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003566 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003567 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003568
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003569 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003570}
3571
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003572status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3573 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3574 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3575 ANDROID_SCALER_CROP_REGION_SET};
3576 if (request == nullptr) {
3577 ALOGE("%s request metadata nullptr", __FUNCTION__);
3578 return BAD_VALUE;
3579 }
3580 status_t res = OK;
3581 for (const auto &key : kFwkOnlyRegionKeys) {
3582 if (request->exists(key)) {
3583 res = request->erase(key);
3584 if (res != OK) {
3585 return res;
3586 }
3587 }
3588 }
3589 return OK;
3590}
3591
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003592status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003593 ATRACE_CALL();
3594
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003595 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003596 for (size_t i = 0; i < mNextRequests.size(); i++) {
3597 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003598 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003599 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3600 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003601
3602 // Prepare a request to HAL
3603 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3604
3605 // Insert any queued triggers (before metadata is locked)
3606 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003607 if (res < 0) {
3608 SET_ERR("RequestThread: Unable to insert triggers "
3609 "(capture request %d, HAL device: %s (%d)",
3610 halRequest->frame_number, strerror(-res), res);
3611 return INVALID_OPERATION;
3612 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003613
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003614 int triggerCount = res;
3615 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3616 mPrevTriggers = triggerCount;
3617
Emilian Peeve23f1d92021-09-20 14:56:01 -07003618 // Do not override rotate&crop for stream configurations that include
Austin Borger18b30a72022-10-27 12:20:29 -07003619 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3620 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3621 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003622 overrideAutoRotateAndCrop(captureRequest);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003623 bool autoframingChanged = overrideAutoframing(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003624 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003625
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003626 // If the request is the same as last, or we had triggers now or last time or
3627 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003628 bool newRequest =
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003629 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged ||
3630 autoframingChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003631 // Request settings are all the same within one batch, so only treat the first
3632 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003633 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003634 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003635 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003636 /**
3637 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003638 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003639 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003640 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003641 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003642 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 "(capture request %d, HAL device: %s (%d)",
3644 halRequest->frame_number, strerror(-res), res);
3645 return INVALID_OPERATION;
3646 }
3647
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003648 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003649 sp<Camera3Device> parent = mParent.promote();
3650 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003651 List<PhysicalCameraSettings>::iterator it;
3652 for (it = captureRequest->mSettingsList.begin();
3653 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003654 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3655 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003656 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3657 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3658 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3659 res);
3660 return INVALID_OPERATION;
3661 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003662 continue;
3663 }
3664
3665 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3666 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3667 updateCaptureRequest(&(it->metadata));
3668 if (res != OK) {
3669 SET_ERR("RequestThread: Unable to correct capture requests "
3670 "for scaler crop region and metering regions for request "
3671 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3672 res);
3673 return INVALID_OPERATION;
3674 }
3675 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003676 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3677 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3678 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3679 res);
3680 return INVALID_OPERATION;
3681 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003682 }
3683 }
3684
3685 // Correct metadata regions for distortion correction if enabled
3686 for (it = captureRequest->mSettingsList.begin();
3687 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003688 if (parent->mDistortionMappers.find(it->cameraId) ==
3689 parent->mDistortionMappers.end()) {
3690 continue;
3691 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003692
3693 if (!captureRequest->mDistortionCorrectionUpdated) {
3694 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3695 &(it->metadata));
3696 if (res != OK) {
3697 SET_ERR("RequestThread: Unable to correct capture requests "
3698 "for lens distortion for request %d: %s (%d)",
3699 halRequest->frame_number, strerror(-res), res);
3700 return INVALID_OPERATION;
3701 }
3702 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003703 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003704 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003705
3706 for (it = captureRequest->mSettingsList.begin();
3707 it != captureRequest->mSettingsList.end(); it++) {
3708 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3709 parent->mZoomRatioMappers.end()) {
3710 continue;
3711 }
3712
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003713 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003714 cameraIdsWithZoom.insert(it->cameraId);
3715 }
3716
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003717 if (!captureRequest->mZoomRatioUpdated) {
3718 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3719 &(it->metadata));
3720 if (res != OK) {
3721 SET_ERR("RequestThread: Unable to correct capture requests "
3722 "for zoom ratio for request %d: %s (%d)",
3723 halRequest->frame_number, strerror(-res), res);
3724 return INVALID_OPERATION;
3725 }
3726 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003727 }
3728 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003729 if (captureRequest->mRotateAndCropAuto &&
3730 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003731 for (it = captureRequest->mSettingsList.begin();
3732 it != captureRequest->mSettingsList.end(); it++) {
3733 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3734 if (mapper != parent->mRotateAndCropMappers.end()) {
3735 res = mapper->second.updateCaptureRequest(&(it->metadata));
3736 if (res != OK) {
3737 SET_ERR("RequestThread: Unable to correct capture requests "
3738 "for rotate-and-crop for request %d: %s (%d)",
3739 halRequest->frame_number, strerror(-res), res);
3740 return INVALID_OPERATION;
3741 }
3742 }
3743 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003744 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003745 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003746
3747 for (it = captureRequest->mSettingsList.begin();
3748 it != captureRequest->mSettingsList.end(); it++) {
3749 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3750 mVndkVersion, it->metadata, false /*isStatic*/);
3751 if (res != OK) {
3752 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3753 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3754 return INVALID_OPERATION;
3755 }
3756 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003757 }
3758 }
3759
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003760 /**
3761 * The request should be presorted so accesses in HAL
3762 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3763 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003764 captureRequest->mSettingsList.begin()->metadata.sort();
3765 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003766 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003767 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003768 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3769
3770 IF_ALOGV() {
3771 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3772 find_camera_metadata_ro_entry(
3773 halRequest->settings,
3774 ANDROID_CONTROL_AF_TRIGGER,
3775 &e
3776 );
3777 if (e.count > 0) {
3778 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3779 __FUNCTION__,
3780 halRequest->frame_number,
3781 e.data.u8[0]);
3782 }
3783 }
3784 } else {
3785 // leave request.settings NULL to indicate 'reuse latest given'
3786 ALOGVV("%s: Request settings are REUSED",
3787 __FUNCTION__);
3788 }
3789
Emilian Peevaebbe412018-01-15 13:53:24 +00003790 if (captureRequest->mSettingsList.size() > 1) {
3791 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3792 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003793 if (newRequest) {
3794 halRequest->physcam_settings =
3795 new const camera_metadata* [halRequest->num_physcam_settings];
3796 } else {
3797 halRequest->physcam_settings = nullptr;
3798 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003799 auto it = ++captureRequest->mSettingsList.begin();
3800 size_t i = 0;
3801 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3802 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003803 if (newRequest) {
3804 it->metadata.sort();
3805 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3806 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003807 }
3808 }
3809
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003810 uint32_t totalNumBuffers = 0;
3811
3812 // Fill in buffers
3813 if (captureRequest->mInputStream != NULL) {
3814 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003815
3816 halRequest->input_width = captureRequest->mInputBufferSize.width;
3817 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003818 totalNumBuffers += 1;
3819 } else {
3820 halRequest->input_buffer = NULL;
3821 }
3822
Emilian Peevf4816702020-04-03 15:44:51 -07003823 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003824 captureRequest->mOutputStreams.size());
3825 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003826 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003827
3828 sp<Camera3Device> parent = mParent.promote();
3829 if (parent == NULL) {
3830 // Should not happen, and nowhere to send errors to, so just log it
3831 CLOGE("RequestThread: Parent is gone");
3832 return INVALID_OPERATION;
3833 }
3834 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3835
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003836 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003837 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003838 sp<Camera3OutputStreamInterface> outputStream =
3839 captureRequest->mOutputStreams.editItemAt(j);
3840 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003841
3842 // Prepare video buffers for high speed recording on the first video request.
3843 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3844 // Only try to prepare video stream on the first video request.
3845 mPrepareVideoStream = false;
3846
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003847 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3848 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003849 while (res == NOT_ENOUGH_DATA) {
3850 res = outputStream->prepareNextBuffer();
3851 }
3852 if (res != OK) {
3853 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3854 __FUNCTION__, strerror(-res), res);
3855 outputStream->cancelPrepare();
3856 }
3857 }
3858
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003859 std::vector<size_t> uniqueSurfaceIds;
3860 res = outputStream->getUniqueSurfaceIds(
3861 captureRequest->mOutputSurfaces[streamId],
3862 &uniqueSurfaceIds);
3863 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3864 if (res != OK && res != INVALID_OPERATION) {
3865 ALOGE("%s: failed to query stream %d unique surface IDs",
3866 __FUNCTION__, streamId);
3867 return res;
3868 }
3869 if (res == OK) {
3870 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3871 }
3872
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003873 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003874 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003875 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003876 return TIMED_OUT;
3877 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003878 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003879 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003880 buffer.stream = outputStream->asHalStream();
3881 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003882 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003883 buffer.acquire_fence = -1;
3884 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003885 // Mark the output stream as unpreparable to block clients from calling
3886 // 'prepare' after this request reaches CameraHal and before the respective
3887 // buffers are requested.
3888 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003889 } else {
3890 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3891 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003892 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003893 if (res != OK) {
3894 // Can't get output buffer from gralloc queue - this could be due to
3895 // abandoned queue or other consumer misbehavior, so not a fatal
3896 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003897 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003898 " %s (%d)", strerror(-res), res);
3899
3900 return TIMED_OUT;
3901 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003902 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003903
3904 {
3905 sp<Camera3Device> parent = mParent.promote();
3906 if (parent != nullptr) {
3907 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3908 for (const auto& settings : captureRequest->mSettingsList) {
3909 if ((streamCameraId.isEmpty() &&
3910 parent->getId() == settings.cameraId.c_str()) ||
3911 streamCameraId == settings.cameraId.c_str()) {
3912 outputStream->fireBufferRequestForFrameNumber(
3913 captureRequest->mResultExtras.frameNumber,
3914 settings.metadata);
3915 }
3916 }
3917 }
3918 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003919
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003920 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003921 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3922 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3923 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3924 } else if (!physicalCameraId.isEmpty()) {
3925 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003926 }
3927 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003928 }
3929 totalNumBuffers += halRequest->num_output_buffers;
3930
3931 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003932 // If this request list is for constrained high speed recording (not
3933 // preview), and the current request is not the last one in the batch,
3934 // do not send callback to the app.
3935 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003936 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003937 hasCallback = false;
3938 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003939 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003940 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003941 const camera_metadata_t* settings = halRequest->settings;
3942 bool shouldUnlockSettings = false;
3943 if (settings == nullptr) {
3944 shouldUnlockSettings = true;
3945 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3946 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003947 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3948 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003949 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003950 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3951 isStillCapture = true;
3952 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3953 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003954
Emilian Peevaf8416e2021-02-04 17:52:43 -08003955 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003956 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003957 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3958 isZslCapture = true;
3959 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003960 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003961 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003962 res = parent->registerInFlight(halRequest->frame_number,
3963 totalNumBuffers, captureRequest->mResultExtras,
3964 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003965 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003966 expectedDurationInfo.minDuration,
3967 expectedDurationInfo.maxDuration,
3968 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003969 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003970 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
3971 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003972 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003973 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003974 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3975 ", burstId = %" PRId32 ".",
3976 __FUNCTION__,
3977 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3978 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003979
3980 if (shouldUnlockSettings) {
3981 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3982 }
3983
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003984 if (res != OK) {
3985 SET_ERR("RequestThread: Unable to register new in-flight request:"
3986 " %s (%d)", strerror(-res), res);
3987 return INVALID_OPERATION;
3988 }
3989 }
3990
3991 return OK;
3992}
3993
Igor Murashkin1e479c02013-09-06 16:55:14 -07003994CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003995 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003996 Mutex::Autolock al(mLatestRequestMutex);
3997
3998 ALOGV("RequestThread::%s", __FUNCTION__);
3999
4000 return mLatestRequest;
4001}
4002
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004003bool Camera3Device::RequestThread::isStreamPending(
4004 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004005 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004006 Mutex::Autolock l(mRequestLock);
4007
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004008 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004009 if (!nextRequest.submitted) {
4010 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4011 if (stream == s) return true;
4012 }
4013 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004014 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004015 }
4016
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004017 for (const auto& request : mRequestQueue) {
4018 for (const auto& s : request->mOutputStreams) {
4019 if (stream == s) return true;
4020 }
4021 if (stream == request->mInputStream) return true;
4022 }
4023
4024 for (const auto& request : mRepeatingRequests) {
4025 for (const auto& s : request->mOutputStreams) {
4026 if (stream == s) return true;
4027 }
4028 if (stream == request->mInputStream) return true;
4029 }
4030
4031 return false;
4032}
Jianing Weicb0652e2014-03-12 18:29:36 -07004033
Emilian Peev40ead602017-09-26 15:46:36 +01004034bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4035 ATRACE_CALL();
4036 Mutex::Autolock l(mRequestLock);
4037
4038 for (const auto& nextRequest : mNextRequests) {
4039 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4040 if (s.first == streamId) {
4041 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4042 if (it != s.second.end()) {
4043 return true;
4044 }
4045 }
4046 }
4047 }
4048
4049 for (const auto& request : mRequestQueue) {
4050 for (const auto& s : request->mOutputSurfaces) {
4051 if (s.first == streamId) {
4052 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4053 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004054 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004055 }
4056 }
4057 }
4058 }
4059
4060 for (const auto& request : mRepeatingRequests) {
4061 for (const auto& s : request->mOutputSurfaces) {
4062 if (s.first == streamId) {
4063 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4064 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004065 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004066 }
4067 }
4068 }
4069 }
4070
4071 return false;
4072}
4073
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004074void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4075 if (!mUseHalBufManager) {
4076 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4077 return;
4078 }
4079
4080 Mutex::Autolock pl(mPauseLock);
4081 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004082 mInterface->signalPipelineDrain(streamIds);
4083 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004084 }
4085 // If request thread is still busy, wait until paused then notify HAL
4086 mNotifyPipelineDrain = true;
4087 mStreamIdsToBeDrained = streamIds;
4088}
4089
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004090void Camera3Device::RequestThread::resetPipelineDrain() {
4091 Mutex::Autolock pl(mPauseLock);
4092 mNotifyPipelineDrain = false;
4093 mStreamIdsToBeDrained.clear();
4094}
4095
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004096void Camera3Device::RequestThread::clearPreviousRequest() {
4097 Mutex::Autolock l(mRequestLock);
4098 mPrevRequest.clear();
4099}
4100
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004101status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4102 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4103 ATRACE_CALL();
4104 Mutex::Autolock l(mTriggerMutex);
4105 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4106 return BAD_VALUE;
4107 }
4108 mRotateAndCropOverride = rotateAndCropValue;
4109 return OK;
4110}
4111
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004112status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4113 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4114 ATRACE_CALL();
4115 Mutex::Autolock l(mTriggerMutex);
4116 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
4117 return BAD_VALUE;
4118 }
4119 mAutoframingOverride = autoframingValue;
4120 return OK;
4121}
4122
Emilian Peeve23f1d92021-09-20 14:56:01 -07004123status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4124 ATRACE_CALL();
4125 Mutex::Autolock l(mTriggerMutex);
4126 mComposerOutput = composerSurfacePresent;
4127 return OK;
4128}
4129
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004130status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004131 ATRACE_CALL();
4132 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004133 if (muteMode != mCameraMute) {
4134 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004135 mCameraMuteChanged = true;
4136 }
4137 return OK;
4138}
4139
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004140nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004141 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004142 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004143 return mExpectedInflightDuration > kMinInflightDuration ?
4144 mExpectedInflightDuration : kMinInflightDuration;
4145}
4146
Emilian Peevaebbe412018-01-15 13:53:24 +00004147void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004148 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004149 if ((request == nullptr) || (halRequest == nullptr)) {
4150 ALOGE("%s: Invalid request!", __FUNCTION__);
4151 return;
4152 }
4153
4154 if (halRequest->num_physcam_settings > 0) {
4155 if (halRequest->physcam_id != nullptr) {
4156 delete [] halRequest->physcam_id;
4157 halRequest->physcam_id = nullptr;
4158 }
4159 if (halRequest->physcam_settings != nullptr) {
4160 auto it = ++(request->mSettingsList.begin());
4161 size_t i = 0;
4162 for (; it != request->mSettingsList.end(); it++, i++) {
4163 it->metadata.unlock(halRequest->physcam_settings[i]);
4164 }
4165 delete [] halRequest->physcam_settings;
4166 halRequest->physcam_settings = nullptr;
4167 }
4168 }
4169}
4170
Ravneetaeb20dc2022-03-30 05:33:03 +00004171status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4172 Mutex::Autolock il(mInterfaceLock);
4173 Mutex::Autolock l(mLock);
4174
4175 if (mCameraServiceWatchdog != NULL) {
4176 mCameraServiceWatchdog->setEnabled(enabled);
4177 }
4178
4179 return OK;
4180}
4181
Shuzhen Wang16610a62022-12-15 22:38:07 -08004182void Camera3Device::setStreamUseCaseOverrides(
4183 const std::vector<int64_t>& useCaseOverrides) {
4184 Mutex::Autolock il(mInterfaceLock);
4185 Mutex::Autolock l(mLock);
4186 mStreamUseCaseOverrides = useCaseOverrides;
4187}
4188
4189void Camera3Device::clearStreamUseCaseOverrides() {
4190 Mutex::Autolock il(mInterfaceLock);
4191 Mutex::Autolock l(mLock);
4192 mStreamUseCaseOverrides.clear();
4193}
4194
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004195bool Camera3Device::hasDeviceError() {
4196 Mutex::Autolock il(mInterfaceLock);
4197 Mutex::Autolock l(mLock);
4198 return mStatus == STATUS_ERROR;
4199}
4200
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004201void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4202 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004203 return;
4204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004206 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004207 // Skip the ones that have been submitted successfully.
4208 if (nextRequest.submitted) {
4209 continue;
4210 }
4211
4212 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004213 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4214 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004215
4216 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004217 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004218 }
4219
Emilian Peevaebbe412018-01-15 13:53:24 +00004220 cleanupPhysicalSettings(captureRequest, halRequest);
4221
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004223 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004224 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4225 }
4226
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004227 // No output buffer can be returned when using HAL buffer manager
4228 if (!mUseHalBufManager) {
4229 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4230 //Buffers that failed processing could still have
4231 //valid acquire fence.
4232 int acquireFence = (*outputBuffers)[i].acquire_fence;
4233 if (0 <= acquireFence) {
4234 close(acquireFence);
4235 outputBuffers->editItemAt(i).acquire_fence = -1;
4236 }
Emilian Peevf4816702020-04-03 15:44:51 -07004237 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004238 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4239 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004240 /*timestampIncreasing*/true, std::vector<size_t> (),
4241 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004242 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004243 }
4244
4245 if (sendRequestError) {
4246 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004247 sp<NotificationListener> listener = mListener.promote();
4248 if (listener != NULL) {
4249 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004250 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004251 captureRequest->mResultExtras);
4252 }
4253 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004254
4255 // Remove yet-to-be submitted inflight request from inflightMap
4256 {
4257 sp<Camera3Device> parent = mParent.promote();
4258 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004259 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004260 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4261 if (idx >= 0) {
4262 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4263 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4264 parent->removeInFlightMapEntryLocked(idx);
4265 }
4266 }
4267 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004268 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004269
4270 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272}
4273
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004274void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004275 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276 // Optimized a bit for the simple steady-state case (single repeating
4277 // request), to avoid putting that request in the queue temporarily.
4278 Mutex::Autolock l(mRequestLock);
4279
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004280 assert(mNextRequests.empty());
4281
4282 NextRequest nextRequest;
4283 nextRequest.captureRequest = waitForNextRequestLocked();
4284 if (nextRequest.captureRequest == nullptr) {
4285 return;
4286 }
4287
Emilian Peevf4816702020-04-03 15:44:51 -07004288 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004289 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004290 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004291
4292 // Wait for additional requests
4293 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4294
4295 for (size_t i = 1; i < batchSize; i++) {
4296 NextRequest additionalRequest;
4297 additionalRequest.captureRequest = waitForNextRequestLocked();
4298 if (additionalRequest.captureRequest == nullptr) {
4299 break;
4300 }
4301
Emilian Peevf4816702020-04-03 15:44:51 -07004302 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004303 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004304 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004305 }
4306
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004307 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004308 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004309 mNextRequests.size(), batchSize);
4310 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004311 }
4312
4313 return;
4314}
4315
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004316void Camera3Device::RequestThread::setRequestClearing() {
4317 Mutex::Autolock l(mRequestLock);
4318 mRequestClearing = true;
4319}
4320
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004321sp<Camera3Device::CaptureRequest>
4322 Camera3Device::RequestThread::waitForNextRequestLocked() {
4323 status_t res;
4324 sp<CaptureRequest> nextRequest;
4325
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004326 while (mRequestQueue.empty()) {
4327 if (!mRepeatingRequests.empty()) {
4328 // Always atomically enqueue all requests in a repeating request
4329 // list. Guarantees a complete in-sequence set of captures to
4330 // application.
4331 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004332 if (mFirstRepeating) {
4333 mFirstRepeating = false;
4334 } else {
4335 for (auto& request : requests) {
4336 // For repeating requests, override timestamp request using
4337 // the time a request is inserted into the request queue,
4338 // because the original repeating request will have an old
4339 // fixed timestamp.
4340 request->mRequestTimeNs = systemTime();
4341 }
4342 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004343 RequestList::const_iterator firstRequest =
4344 requests.begin();
4345 nextRequest = *firstRequest;
4346 mRequestQueue.insert(mRequestQueue.end(),
4347 ++firstRequest,
4348 requests.end());
4349 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004350
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004351 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004352
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004353 break;
4354 }
4355
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004356 if (!mRequestClearing) {
4357 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004359
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004360 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4361 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004362 Mutex::Autolock pl(mPauseLock);
4363 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004364 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004365 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004366 if (mNotifyPipelineDrain) {
4367 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4368 mNotifyPipelineDrain = false;
4369 mStreamIdsToBeDrained.clear();
4370 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004371 // Let the tracker know
4372 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4373 if (statusTracker != 0) {
4374 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4375 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004376 sp<Camera3Device> parent = mParent.promote();
4377 if (parent != nullptr) {
4378 parent->mRequestBufferSM.onRequestThreadPaused();
4379 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004381 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004382 // Stop waiting for now and let thread management happen
4383 return NULL;
4384 }
4385 }
4386
4387 if (nextRequest == NULL) {
4388 // Don't have a repeating request already in hand, so queue
4389 // must have an entry now.
4390 RequestList::iterator firstRequest =
4391 mRequestQueue.begin();
4392 nextRequest = *firstRequest;
4393 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004394 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4395 sp<NotificationListener> listener = mListener.promote();
4396 if (listener != NULL) {
4397 listener->notifyRequestQueueEmpty();
4398 }
4399 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004400 }
4401
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004402 // In case we've been unpaused by setPaused clearing mDoPause, need to
4403 // update internal pause state (capture/setRepeatingRequest unpause
4404 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004405 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004406 if (mPaused) {
4407 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4408 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4409 if (statusTracker != 0) {
4410 statusTracker->markComponentActive(mStatusId);
4411 }
4412 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 mPaused = false;
4414
4415 // Check if we've reconfigured since last time, and reset the preview
4416 // request if so. Can't use 'NULL request == repeat' across configure calls.
4417 if (mReconfigured) {
4418 mPrevRequest.clear();
4419 mReconfigured = false;
4420 }
4421
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004422 if (nextRequest != NULL) {
4423 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004424 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4425 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004426
4427 // Since RequestThread::clear() removes buffers from the input stream,
4428 // get the right buffer here before unlocking mRequestLock
4429 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004430 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4431 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004432 if (res != OK) {
4433 // Can't get input buffer from gralloc queue - this could be due to
4434 // disconnected queue or other producer misbehavior, so not a fatal
4435 // error
4436 ALOGE("%s: Can't get input buffer, skipping request:"
4437 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004438
4439 sp<NotificationListener> listener = mListener.promote();
4440 if (listener != NULL) {
4441 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004442 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004443 nextRequest->mResultExtras);
4444 }
4445 return NULL;
4446 }
4447 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004448 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004450 return nextRequest;
4451}
4452
4453bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004454 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004455 status_t res;
4456 Mutex::Autolock l(mPauseLock);
4457 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004458 if (mPaused == false) {
4459 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004460 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004461 if (mNotifyPipelineDrain) {
4462 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4463 mNotifyPipelineDrain = false;
4464 mStreamIdsToBeDrained.clear();
4465 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004466 // Let the tracker know
4467 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4468 if (statusTracker != 0) {
4469 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4470 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004471 sp<Camera3Device> parent = mParent.promote();
4472 if (parent != nullptr) {
4473 parent->mRequestBufferSM.onRequestThreadPaused();
4474 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004475 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004476
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004477 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004478 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 return true;
4480 }
4481 }
4482 // We don't set mPaused to false here, because waitForNextRequest needs
4483 // to further manage the paused state in case of starvation.
4484 return false;
4485}
4486
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004487void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004488 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004489 // With work to do, mark thread as unpaused.
4490 // If paused by request (setPaused), don't resume, to avoid
4491 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004492 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004493 Mutex::Autolock p(mPauseLock);
4494 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004495 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4496 if (mPaused) {
4497 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4498 if (statusTracker != 0) {
4499 statusTracker->markComponentActive(mStatusId);
4500 }
4501 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004502 mPaused = false;
4503 }
4504}
4505
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004506void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4507 sp<Camera3Device> parent = mParent.promote();
4508 if (parent != NULL) {
4509 va_list args;
4510 va_start(args, fmt);
4511
4512 parent->setErrorStateV(fmt, args);
4513
4514 va_end(args);
4515 }
4516}
4517
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004518status_t Camera3Device::RequestThread::insertTriggers(
4519 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004520 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004521 Mutex::Autolock al(mTriggerMutex);
4522
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004523 sp<Camera3Device> parent = mParent.promote();
4524 if (parent == NULL) {
4525 CLOGE("RequestThread: Parent is gone");
4526 return DEAD_OBJECT;
4527 }
4528
Emilian Peevaebbe412018-01-15 13:53:24 +00004529 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004530 size_t count = mTriggerMap.size();
4531
4532 for (size_t i = 0; i < count; ++i) {
4533 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004534 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004535
4536 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4537 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4538 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004539 if (isAeTrigger) {
4540 request->mResultExtras.precaptureTriggerId = triggerId;
4541 mCurrentPreCaptureTriggerId = triggerId;
4542 } else {
4543 request->mResultExtras.afTriggerId = triggerId;
4544 mCurrentAfTriggerId = triggerId;
4545 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004546 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004547 }
4548
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004549 camera_metadata_entry entry = metadata.find(tag);
4550
4551 if (entry.count > 0) {
4552 /**
4553 * Already has an entry for this trigger in the request.
4554 * Rewrite it with our requested trigger value.
4555 */
4556 RequestTrigger oldTrigger = trigger;
4557
4558 oldTrigger.entryValue = entry.data.u8[0];
4559
4560 mTriggerReplacedMap.add(tag, oldTrigger);
4561 } else {
4562 /**
4563 * More typical, no trigger entry, so we just add it
4564 */
4565 mTriggerRemovedMap.add(tag, trigger);
4566 }
4567
4568 status_t res;
4569
4570 switch (trigger.getTagType()) {
4571 case TYPE_BYTE: {
4572 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4573 res = metadata.update(tag,
4574 &entryValue,
4575 /*count*/1);
4576 break;
4577 }
4578 case TYPE_INT32:
4579 res = metadata.update(tag,
4580 &trigger.entryValue,
4581 /*count*/1);
4582 break;
4583 default:
4584 ALOGE("%s: Type not supported: 0x%x",
4585 __FUNCTION__,
4586 trigger.getTagType());
4587 return INVALID_OPERATION;
4588 }
4589
4590 if (res != OK) {
4591 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4592 ", value %d", __FUNCTION__, trigger.getTagName(),
4593 trigger.entryValue);
4594 return res;
4595 }
4596
4597 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4598 trigger.getTagName(),
4599 trigger.entryValue);
4600 }
4601
4602 mTriggerMap.clear();
4603
4604 return count;
4605}
4606
4607status_t Camera3Device::RequestThread::removeTriggers(
4608 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004609 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004610 Mutex::Autolock al(mTriggerMutex);
4611
Emilian Peevaebbe412018-01-15 13:53:24 +00004612 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004613
4614 /**
4615 * Replace all old entries with their old values.
4616 */
4617 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4618 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4619
4620 status_t res;
4621
4622 uint32_t tag = trigger.metadataTag;
4623 switch (trigger.getTagType()) {
4624 case TYPE_BYTE: {
4625 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4626 res = metadata.update(tag,
4627 &entryValue,
4628 /*count*/1);
4629 break;
4630 }
4631 case TYPE_INT32:
4632 res = metadata.update(tag,
4633 &trigger.entryValue,
4634 /*count*/1);
4635 break;
4636 default:
4637 ALOGE("%s: Type not supported: 0x%x",
4638 __FUNCTION__,
4639 trigger.getTagType());
4640 return INVALID_OPERATION;
4641 }
4642
4643 if (res != OK) {
4644 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4645 ", trigger value %d", __FUNCTION__,
4646 trigger.getTagName(), trigger.entryValue);
4647 return res;
4648 }
4649 }
4650 mTriggerReplacedMap.clear();
4651
4652 /**
4653 * Remove all new entries.
4654 */
4655 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4656 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4657 status_t res = metadata.erase(trigger.metadataTag);
4658
4659 if (res != OK) {
4660 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4661 ", trigger value %d", __FUNCTION__,
4662 trigger.getTagName(), trigger.entryValue);
4663 return res;
4664 }
4665 }
4666 mTriggerRemovedMap.clear();
4667
4668 return OK;
4669}
4670
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004671status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004672 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004673 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004674 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004675 status_t res;
4676
Emilian Peevaebbe412018-01-15 13:53:24 +00004677 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004678
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004679 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004680 // exists
4681 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4682 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4683 if (afTrigger.count > 0 &&
4684 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4685 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004686 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004687 if (res != OK) return res;
4688 }
4689
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004690 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004691 // if none already exists
4692 camera_metadata_entry pcTrigger =
4693 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4694 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4695 if (pcTrigger.count > 0 &&
4696 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4697 pcId.count == 0) {
4698 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004699 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004700 if (res != OK) return res;
4701 }
4702
4703 return OK;
4704}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004705
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004706bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4707 const sp<CaptureRequest> &request) {
4708 ATRACE_CALL();
4709
Austin Borger18b30a72022-10-27 12:20:29 -07004710 if (mOverrideToPortrait) {
4711 Mutex::Autolock l(mTriggerMutex);
4712 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4713 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4714 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4715 &rotateAndCrop_u8, 1);
4716 return true;
4717 }
4718
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004719 if (request->mRotateAndCropAuto) {
4720 Mutex::Autolock l(mTriggerMutex);
4721 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4722
4723 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4724 if (rotateAndCropEntry.count > 0) {
4725 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4726 return false;
4727 } else {
4728 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4729 return true;
4730 }
4731 } else {
4732 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4733 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4734 &rotateAndCrop_u8, 1);
4735 return true;
4736 }
4737 }
4738 return false;
4739}
4740
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004741bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4742 ATRACE_CALL();
4743
4744 if (request->mAutoframingAuto) {
4745 Mutex::Autolock l(mTriggerMutex);
4746 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4747
4748 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4749 if (autoframingEntry.count > 0) {
4750 if (autoframingEntry.data.u8[0] == mAutoframingOverride) {
4751 return false;
4752 } else {
4753 autoframingEntry.data.u8[0] = mAutoframingOverride;
4754 return true;
4755 }
4756 } else {
4757 uint8_t autoframing_u8 = mAutoframingOverride;
4758 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4759 &autoframing_u8, 1);
4760 return true;
4761 }
4762 }
4763 return false;
4764}
4765
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004766bool Camera3Device::RequestThread::overrideTestPattern(
4767 const sp<CaptureRequest> &request) {
4768 ATRACE_CALL();
4769
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004770 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004771
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004772 Mutex::Autolock l(mTriggerMutex);
4773
4774 bool changed = false;
4775
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004776 // For a multi-camera, the physical cameras support the same set of
4777 // test pattern modes as the logical camera.
4778 for (auto& settings : request->mSettingsList) {
4779 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004780
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004781 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4782 int32_t testPatternData[4] = {
4783 settings.mOriginalTestPatternData[0],
4784 settings.mOriginalTestPatternData[1],
4785 settings.mOriginalTestPatternData[2],
4786 settings.mOriginalTestPatternData[3]
4787 };
4788 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4789 testPatternMode = mCameraMute;
4790 testPatternData[0] = 0;
4791 testPatternData[1] = 0;
4792 testPatternData[2] = 0;
4793 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004794 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004795
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004796 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4797 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4798 if (testPatternEntry.count > 0) {
4799 if (testPatternEntry.data.i32[0] != testPatternMode) {
4800 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004801 changed = true;
4802 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004803 } else if (supportTestPatternModeKey) {
4804 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4805 &testPatternMode, 1);
4806 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004807 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004808
4809 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4810 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4811 if (testPatternColor.count >= 4) {
4812 for (size_t i = 0; i < 4; i++) {
4813 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4814 testPatternColor.data.i32[i] = testPatternData[i];
4815 changed = true;
4816 }
4817 }
4818 } else if (supportTestPatternDataKey) {
4819 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4820 testPatternData, 4);
4821 changed = true;
4822 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004823 }
4824
4825 return changed;
4826}
4827
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004828status_t Camera3Device::RequestThread::setHalInterface(
4829 sp<HalInterface> newHalInterface) {
4830 if (newHalInterface.get() == nullptr) {
4831 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4832 return DEAD_OBJECT;
4833 }
4834
4835 mInterface = newHalInterface;
4836
4837 return OK;
4838}
4839
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004840/**
4841 * PreparerThread inner class methods
4842 */
4843
4844Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004845 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004846 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004847}
4848
4849Camera3Device::PreparerThread::~PreparerThread() {
4850 Thread::requestExitAndWait();
4851 if (mCurrentStream != nullptr) {
4852 mCurrentStream->cancelPrepare();
4853 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4854 mCurrentStream.clear();
4855 }
4856 clear();
4857}
4858
Ruben Brunkc78ac262015-08-13 17:58:46 -07004859status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004860 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004861 status_t res;
4862
4863 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004864 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004865
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004866 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004867 if (res == OK) {
4868 // No preparation needed, fire listener right off
4869 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004870 if (listener != NULL) {
4871 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004872 }
4873 return OK;
4874 } else if (res != NOT_ENOUGH_DATA) {
4875 return res;
4876 }
4877
4878 // Need to prepare, start up thread if necessary
4879 if (!mActive) {
4880 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4881 // isn't running
4882 Thread::requestExitAndWait();
4883 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4884 if (res != OK) {
4885 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004886 if (listener != NULL) {
4887 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004888 }
4889 return res;
4890 }
4891 mCancelNow = false;
4892 mActive = true;
4893 ALOGV("%s: Preparer stream started", __FUNCTION__);
4894 }
4895
4896 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004897 mPendingStreams.push_back(
4898 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004899 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4900
4901 return OK;
4902}
4903
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004904void Camera3Device::PreparerThread::pause() {
4905 ATRACE_CALL();
4906
4907 Mutex::Autolock l(mLock);
4908
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004909 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
4910 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004911 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4912 int currentMaxCount = mCurrentMaxCount;
4913 mPendingStreams.clear();
4914 mCancelNow = true;
4915 while (mActive) {
4916 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4917 if (res == TIMED_OUT) {
4918 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4919 return;
4920 } else if (res != OK) {
4921 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4922 return;
4923 }
4924 }
4925
4926 //Check whether the prepare thread was able to complete the current
4927 //stream. In case work is still pending emplace it along with the rest
4928 //of the streams in the pending list.
4929 if (currentStream != nullptr) {
4930 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004931 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004932 }
4933 }
4934
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004935 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004936 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004937 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004938 }
4939}
4940
4941status_t Camera3Device::PreparerThread::resume() {
4942 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004943 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004944 status_t res;
4945
4946 Mutex::Autolock l(mLock);
4947 sp<NotificationListener> listener = mListener.promote();
4948
4949 if (mActive) {
4950 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4951 return NO_INIT;
4952 }
4953
4954 auto it = mPendingStreams.begin();
4955 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004956 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004957 if (res == OK) {
4958 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004959 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004960 }
4961 it = mPendingStreams.erase(it);
4962 } else if (res != NOT_ENOUGH_DATA) {
4963 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4964 res, strerror(-res));
4965 it = mPendingStreams.erase(it);
4966 } else {
4967 it++;
4968 }
4969 }
4970
4971 if (mPendingStreams.empty()) {
4972 return OK;
4973 }
4974
4975 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4976 if (res != OK) {
4977 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4978 __FUNCTION__, res, strerror(-res));
4979 return res;
4980 }
4981 mCancelNow = false;
4982 mActive = true;
4983 ALOGV("%s: Preparer stream started", __FUNCTION__);
4984
4985 return OK;
4986}
4987
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004988status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004989 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004990 Mutex::Autolock l(mLock);
4991
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004992 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004993 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004994 }
4995 mPendingStreams.clear();
4996 mCancelNow = true;
4997
4998 return OK;
4999}
5000
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005001void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005002 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005003 Mutex::Autolock l(mLock);
5004 mListener = listener;
5005}
5006
5007bool Camera3Device::PreparerThread::threadLoop() {
5008 status_t res;
5009 {
5010 Mutex::Autolock l(mLock);
5011 if (mCurrentStream == nullptr) {
5012 // End thread if done with work
5013 if (mPendingStreams.empty()) {
5014 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5015 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5016 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5017 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005018 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005019 return false;
5020 }
5021
5022 // Get next stream to prepare
5023 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005024 mCurrentMaxCount = std::get<0>(*it);
5025 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005026 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005027 mPendingStreams.erase(it);
5028 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5029 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5030 } else if (mCancelNow) {
5031 mCurrentStream->cancelPrepare();
5032 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5033 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5034 mCurrentStream.clear();
5035 mCancelNow = false;
5036 return true;
5037 }
5038 }
5039
5040 res = mCurrentStream->prepareNextBuffer();
5041 if (res == NOT_ENOUGH_DATA) return true;
5042 if (res != OK) {
5043 // Something bad happened; try to recover by cancelling prepare and
5044 // signalling listener anyway
5045 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5046 mCurrentStream->getId(), res, strerror(-res));
5047 mCurrentStream->cancelPrepare();
5048 }
5049
5050 // This stream has finished, notify listener
5051 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005052 sp<NotificationListener> listener = mListener.promote();
5053 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005054 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5055 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005056 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005057 }
5058
5059 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5060 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005061 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005062
5063 return true;
5064}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005065
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005066status_t Camera3Device::RequestBufferStateMachine::initialize(
5067 sp<camera3::StatusTracker> statusTracker) {
5068 if (statusTracker == nullptr) {
5069 ALOGE("%s: statusTracker is null", __FUNCTION__);
5070 return BAD_VALUE;
5071 }
5072
5073 std::lock_guard<std::mutex> lock(mLock);
5074 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005075 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005076 return OK;
5077}
5078
5079bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5080 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005081 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005082 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005083 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005084 return true;
5085 }
5086 return false;
5087}
5088
5089void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5090 std::lock_guard<std::mutex> lock(mLock);
5091 if (!mRequestBufferOngoing) {
5092 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5093 return;
5094 }
5095 mRequestBufferOngoing = false;
5096 if (mStatus == RB_STATUS_PENDING_STOP) {
5097 checkSwitchToStopLocked();
5098 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005099 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005100}
5101
5102void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5103 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005104 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005105 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005106 return;
5107}
5108
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005109void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005110 std::lock_guard<std::mutex> lock(mLock);
5111 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005112 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5113 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005114 mInflightMapEmpty = false;
5115 if (mStatus == RB_STATUS_STOPPED) {
5116 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005117 }
5118 return;
5119}
5120
5121void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5122 std::lock_guard<std::mutex> lock(mLock);
5123 mRequestThreadPaused = true;
5124 if (mStatus == RB_STATUS_PENDING_STOP) {
5125 checkSwitchToStopLocked();
5126 }
5127 return;
5128}
5129
5130void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5131 std::lock_guard<std::mutex> lock(mLock);
5132 mInflightMapEmpty = true;
5133 if (mStatus == RB_STATUS_PENDING_STOP) {
5134 checkSwitchToStopLocked();
5135 }
5136 return;
5137}
5138
5139void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5140 std::lock_guard<std::mutex> lock(mLock);
5141 if (!checkSwitchToStopLocked()) {
5142 mStatus = RB_STATUS_PENDING_STOP;
5143 }
5144 return;
5145}
5146
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005147bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5148 std::lock_guard<std::mutex> lock(mLock);
5149 if (mRequestBufferOngoing) {
5150 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5151 __FUNCTION__);
5152 return false;
5153 }
5154 mSwitchedToOffline = true;
5155 mInflightMapEmpty = true;
5156 mRequestThreadPaused = true;
5157 mStatus = RB_STATUS_STOPPED;
5158 return true;
5159}
5160
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005161void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5162 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5163 if (statusTracker != nullptr) {
5164 if (active) {
5165 statusTracker->markComponentActive(mRequestBufferStatusId);
5166 } else {
5167 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5168 }
5169 }
5170}
5171
5172bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5173 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5174 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005175 return true;
5176 }
5177 return false;
5178}
5179
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005180bool Camera3Device::startRequestBuffer() {
5181 return mRequestBufferSM.startRequestBuffer();
5182}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005183
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005184void Camera3Device::endRequestBuffer() {
5185 mRequestBufferSM.endRequestBuffer();
5186}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005187
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005188nsecs_t Camera3Device::getWaitDuration() {
5189 return kBaseGetBufferWait + getExpectedInFlightDuration();
5190}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005191
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005192void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5193 mInterface->getInflightBufferKeys(out);
5194}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005195
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005196void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5197 mInterface->getInflightRequestBufferKeys(out);
5198}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005199
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005200std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5201 std::vector<sp<Camera3StreamInterface>> ret;
5202 bool hasInputStream = mInputStream != nullptr;
5203 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5204 if (hasInputStream) {
5205 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005206 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005207 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5208 ret.push_back(mOutputStreams[i]);
5209 }
5210 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5211 ret.push_back(mDeletedStreams[i]);
5212 }
5213 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005214}
5215
Emilian Peevcc0b7952020-01-07 13:54:47 -08005216void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5217 ATRACE_CALL();
5218
5219 if (offlineStreamIds == nullptr) {
5220 return;
5221 }
5222
5223 Mutex::Autolock il(mInterfaceLock);
5224
5225 auto streamIds = mOutputStreams.getStreamIds();
5226 bool hasInputStream = mInputStream != nullptr;
5227 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5228 offlineStreamIds->push_back(mInputStream->getId());
5229 }
5230
5231 for (const auto & streamId : streamIds) {
5232 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5233 // Streams that use the camera buffer manager are currently not supported in
5234 // offline mode
5235 if (stream->getOfflineProcessingSupport() &&
5236 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5237 offlineStreamIds->push_back(streamId);
5238 }
5239 }
5240}
5241
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005242status_t Camera3Device::setRotateAndCropAutoBehavior(
5243 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5244 ATRACE_CALL();
5245 Mutex::Autolock il(mInterfaceLock);
5246 Mutex::Autolock l(mLock);
5247 if (mRequestThread == nullptr) {
5248 return INVALID_OPERATION;
5249 }
5250 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5251}
5252
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005253status_t Camera3Device::setAutoframingAutoBehavior(
5254 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5255 ATRACE_CALL();
5256 Mutex::Autolock il(mInterfaceLock);
5257 Mutex::Autolock l(mLock);
5258 if (mRequestThread == nullptr) {
5259 return INVALID_OPERATION;
5260 }
5261 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5262}
5263
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005264bool Camera3Device::supportsCameraMute() {
5265 Mutex::Autolock il(mInterfaceLock);
5266 Mutex::Autolock l(mLock);
5267
5268 return mSupportCameraMute;
5269}
5270
5271status_t Camera3Device::setCameraMute(bool enabled) {
5272 ATRACE_CALL();
5273 Mutex::Autolock il(mInterfaceLock);
5274 Mutex::Autolock l(mLock);
5275
5276 if (mRequestThread == nullptr || !mSupportCameraMute) {
5277 return INVALID_OPERATION;
5278 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005279 int32_t muteMode =
5280 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5281 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5282 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5283 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005284}
5285
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005286status_t Camera3Device::injectCamera(const String8& injectedCamId,
5287 sp<CameraProviderManager> manager) {
5288 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5289 ATRACE_CALL();
5290 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005291 // When the camera device is active, injectCamera() and stopInjection() will call
5292 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5293 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5294 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5295 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5296 // waitUntilStateThenRelock().
5297 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005298
5299 status_t res = NO_ERROR;
5300 if (mInjectionMethods->isInjecting()) {
5301 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5302 return OK;
5303 } else {
5304 res = mInjectionMethods->stopInjection();
5305 if (res != OK) {
5306 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5307 __FUNCTION__, res);
5308 return res;
5309 }
5310 }
5311 }
5312
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005313 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005314 if (res != OK) {
5315 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5316 __FUNCTION__, res);
5317 return res;
5318 }
5319
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005320 // When the second display of android is cast to the remote device, and the opened camera is
5321 // also cast to the second display, in this case, because the camera has configured the streams
5322 // at this time, we can directly call injectCamera() to replace the internal camera with
5323 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005324 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5325 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5326
5327 camera3::camera_stream_configuration injectionConfig;
5328 std::vector<uint32_t> injectionBufferSizes;
5329 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5330 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5331 || injectionBufferSizes.size() <= 0) {
5332 ALOGE("Failed to inject camera due to abandoned configuration! "
5333 "mOperatingMode: %d injectionConfig.num_streams: %d "
5334 "injectionBufferSizes.size(): %zu", mOperatingMode,
5335 injectionConfig.num_streams, injectionBufferSizes.size());
5336 return DEAD_OBJECT;
5337 }
5338
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005339 res = mInjectionMethods->injectCamera(
5340 injectionConfig, injectionBufferSizes);
5341 if (res != OK) {
5342 ALOGE("Can't finish inject camera process!");
5343 return res;
5344 }
5345 }
5346
5347 return OK;
5348}
5349
5350status_t Camera3Device::stopInjection() {
5351 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5352 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005353 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005354 return mInjectionMethods->stopInjection();
5355}
5356
Shuzhen Wang16610a62022-12-15 22:38:07 -08005357void Camera3Device::overrideStreamUseCaseLocked() {
5358 if (mStreamUseCaseOverrides.size() == 0) {
5359 return;
5360 }
5361
5362 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5363 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5364 // Refer to CameraService::printHelp for details.
5365 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5366 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5367 outputStreamsIndices[i] = i;
5368 }
5369
5370 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5371 [&](int a, int b) -> bool {
5372
5373 auto formatScore = [](int format) {
5374 switch (format) {
5375 case HAL_PIXEL_FORMAT_BLOB:
5376 return 4;
5377 case HAL_PIXEL_FORMAT_RAW16:
5378 case HAL_PIXEL_FORMAT_RAW10:
5379 case HAL_PIXEL_FORMAT_RAW12:
5380 return 3;
5381 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5382 return 2;
5383 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5384 return 1;
5385 default:
5386 return 0;
5387 }
5388 };
5389
5390 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5391 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5392 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5393 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5394 if (sizeA > sizeB ||
5395 (sizeA == sizeB && formatAScore >= formatBScore)) {
5396 return true;
5397 } else {
5398 return false;
5399 }
5400 });
5401
5402 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5403 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5404 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5405 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5406 }
5407}
5408
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005409}; // namespace android