blob: 4047c135b26aa72754fc9dd691dc516d9a39538b [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080066
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080067#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080068#include <tuple>
69
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080070using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080071using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080072
73namespace android {
74
Austin Borger74fca042022-05-23 12:41:21 -070075Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070076 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070077 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080078 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070079 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080086 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -070098 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -080099 mOverrideToPortrait(overrideToPortrait),
100 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
106Camera3Device::~Camera3Device()
107{
108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700110 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111}
112
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800113const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800114 return mId;
115}
116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117status_t Camera3Device::initializeCommonLocked() {
118
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700119 /** Start up status tracker thread */
120 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800121 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700122 if (res != OK) {
123 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
124 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700126 mStatusTracker.clear();
127 return res;
128 }
129
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700130 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700131 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700132
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700133 if (mUseHalBufManager) {
134 res = mRequestBufferSM.initialize(mStatusTracker);
135 if (res != OK) {
136 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
137 strerror(-res), res);
138 mInterface->close();
139 mStatusTracker.clear();
140 return res;
141 }
142 }
143
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800144 /** Create buffer manager */
145 mBufferManager = new Camera3BufferManager();
146
147 Vector<int32_t> sessionParamKeys;
148 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
149 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
150 if (sessionKeysEntry.count > 0) {
151 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
152 }
153
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700154 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
155 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
156 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
157 if (availableTestPatternModes.data.i32[i] ==
158 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
159 mSupportCameraMute = true;
160 mSupportTestPatternSolidColor = true;
161 break;
162 } else if (availableTestPatternModes.data.i32[i] ==
163 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
164 mSupportCameraMute = true;
165 mSupportTestPatternSolidColor = false;
166 }
167 }
168
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700169 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800170 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700171 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger18b30a72022-10-27 12:20:29 -0700172 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800174 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700175 SET_ERR_L("Unable to start request queue thread: %s (%d)",
176 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800177 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800178 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800179 return res;
180 }
181
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700182 mPreparerThread = new PreparerThread();
183
Ruben Brunk183f0562015-08-12 12:55:02 -0700184 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800185 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400186 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700187 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700188 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800189 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800190
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800191 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800192 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800193 camera_metadata_entry timestampSource =
194 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
195 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
196 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800197 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800198 }
199
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700200 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100201 camera_metadata_entry partialResultsCount =
202 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
203 if (partialResultsCount.count > 0) {
204 mNumPartialResults = partialResultsCount.data.i32[0];
205 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700206 }
207
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800208 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
209 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700210 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700211 if (res != OK) {
212 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
213 return res;
214 }
215 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800216
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800217 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700220 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
221 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
222 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
223 }
224
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800225 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
226 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
227 }
228
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800229 // Hidl/AidlCamera3DeviceInjectionMethods
230 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800231
Ravneetaeb20dc2022-03-30 05:33:03 +0000232 /** Start watchdog thread */
233 mCameraServiceWatchdog = new CameraServiceWatchdog();
Austin Borger7b129542022-06-09 13:23:06 -0700234 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
235 if (res != OK) {
236 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
237 strerror(-res), res);
238 return res;
239 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000240
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800241 return OK;
242}
243
244status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700245 return disconnectImpl();
246}
247
248status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800249 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700250 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800251
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700253 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 Mutex::Autolock il(mInterfaceLock);
256 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
257 {
258 Mutex::Autolock l(mLock);
259 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000261 if (mRequestThread != NULL) {
262 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
263 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800264 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000265 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800266 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000267 } else {
268 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
269 if (res != OK) {
270 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
271 maxExpectedDuration);
272 // Continue to close device even in case of error
273 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800274 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700275 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000276 // Signal to request thread that we're not expecting any
277 // more requests. This will be true since once we're in
278 // disconnect and we've cleared off the request queue, the
279 // request thread can't receive any new requests through
280 // binder calls - since disconnect holds
281 // mBinderSerialization lock.
282 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700283 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800284
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800285 if (mStatus == STATUS_ERROR) {
286 CLOGE("Shutting down in an error state");
287 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700288
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800289 if (mStatusTracker != NULL) {
290 mStatusTracker->requestExit();
291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800293 if (mRequestThread != NULL) {
294 mRequestThread->requestExit();
295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800297 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
298 for (size_t i = 0; i < mOutputStreams.size(); i++) {
299 streams.push_back(mOutputStreams[i]);
300 }
301 if (mInputStream != nullptr) {
302 streams.push_back(mInputStream);
303 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700304 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800306 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
307 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
309 // HAL may be in a bad state, so waiting for request thread
310 // (which may be stuck in the HAL processCaptureRequest call)
311 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800312 // give up mInterfaceLock here and then lock it again. Could this lead
313 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 mRequestThread->join();
315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 Mutex::Autolock il(mInterfaceLock);
318 if (mStatusTracker != NULL) {
319 mStatusTracker->join();
320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800321
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800322 if (mInjectionMethods->isInjecting()) {
323 mInjectionMethods->stopInjection();
324 }
325
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800326 HalInterface* interface;
327 {
328 Mutex::Autolock l(mLock);
329 mRequestThread.clear();
330 Mutex::Autolock stLock(mTrackerLock);
331 mStatusTracker.clear();
332 interface = mInterface.get();
333 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700334
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800335 // Call close without internal mutex held, as the HAL close may need to
336 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000337 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700338
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800339 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800340
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800341 {
342 Mutex::Autolock l(mLock);
343 mInterface->clear();
344 mOutputStreams.clear();
345 mInputStream.clear();
346 mDeletedStreams.clear();
347 mBufferManager.clear();
348 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
349 }
350
351 for (auto& weakStream : streams) {
352 sp<Camera3StreamInterface> stream = weakStream.promote();
353 if (stream != nullptr) {
354 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
355 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
356 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700357 }
358 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700359 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000360
361 if (mCameraServiceWatchdog != NULL) {
362 mCameraServiceWatchdog->requestExit();
363 mCameraServiceWatchdog.clear();
364 }
365
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700366 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800367}
368
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369// For dumping/debugging only -
370// try to acquire a lock a few times, eventually give up to proceed with
371// debug/dump operations
372bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
373 bool gotLock = false;
374 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
375 if (lock.tryLock() == NO_ERROR) {
376 gotLock = true;
377 break;
378 } else {
379 usleep(kDumpSleepDuration);
380 }
381 }
382 return gotLock;
383}
384
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800385nsecs_t Camera3Device::getMonoToBoottimeOffset() {
386 // try three times to get the clock offset, choose the one
387 // with the minimum gap in measurements.
388 const int tries = 3;
389 nsecs_t bestGap, measured;
390 for (int i = 0; i < tries; ++i) {
391 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
392 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
393 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
394 const nsecs_t gap = tmono2 - tmono;
395 if (i == 0 || gap < bestGap) {
396 bestGap = gap;
397 measured = tbase - ((tmono + tmono2) >> 1);
398 }
399 }
400 return measured;
401}
402
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800403ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
404 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700405 // Get max jpeg size (area-wise) for default sensor pixel mode
406 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800407 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700408 /*isUltraHighResolutionSensor*/false);
409 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
410 // not ultra high res sensor
411 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800412 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700413 /*isUltraHighResolution*/true);
414 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800415 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
416 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700417 return BAD_VALUE;
418 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700419 bool useMaxSensorPixelModeThreshold = false;
420 if (uhrMaxJpegResolution.width != 0 &&
421 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
422 // Use the ultra high res max jpeg size and max jpeg buffer size
423 useMaxSensorPixelModeThreshold = true;
424 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700425
Zhijun Hef7da0962014-04-24 13:27:56 -0700426 // Get max jpeg buffer size
427 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800428 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700429 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800430 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
431 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700432 return BAD_VALUE;
433 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700434 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700435
436 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
437 if (useMaxSensorPixelModeThreshold) {
438 maxJpegBufferSize =
439 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
440 maxDefaultJpegResolution, maxJpegBufferSize);
441 chosenMaxJpegResolution = uhrMaxJpegResolution;
442 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800443 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700444
445 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700446 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700447 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800448 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
449 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700450 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800451 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
452 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700453 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700454 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700455 return jpegBufferSize;
456}
457
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800458ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700459 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800460 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700461 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800462 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
463 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464 return BAD_VALUE;
465 }
466 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
467 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
468 return maxBytesForPointCloud;
469}
470
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800471ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
472 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800473 const int PER_CONFIGURATION_SIZE = 3;
474 const int WIDTH_OFFSET = 0;
475 const int HEIGHT_OFFSET = 1;
476 const int SIZE_OFFSET = 2;
477 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800478 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800479 camera3::SessionConfigurationUtils::getAppropriateModeTag(
480 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
481 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800482 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800483 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800484 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
485 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800486 return BAD_VALUE;
487 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700488
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800489 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
490 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
491 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
492 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
493 }
494 }
495
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800496 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
497 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800498 return BAD_VALUE;
499}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700500
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800501status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
502 ATRACE_CALL();
503 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700504
505 // Try to lock, but continue in case of failure (to avoid blocking in
506 // deadlocks)
507 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
508 bool gotLock = tryLockSpinRightRound(mLock);
509
510 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
512 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700513 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800514 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
515 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700516
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800517 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700518
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800519 String16 templatesOption("-t");
520 int n = args.size();
521 for (int i = 0; i < n; i++) {
522 if (args[i] == templatesOption) {
523 dumpTemplates = true;
524 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000525 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700526 if (i + 1 < n) {
527 String8 monitorTags = String8(args[i + 1]);
528 if (monitorTags == "off") {
529 mTagMonitor.disableMonitoring();
530 } else {
531 mTagMonitor.parseTagsToMonitor(monitorTags);
532 }
533 } else {
534 mTagMonitor.disableMonitoring();
535 }
536 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800537 }
538
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800539 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800541 const char *status =
542 mStatus == STATUS_ERROR ? "ERROR" :
543 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700544 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
545 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800546 mStatus == STATUS_ACTIVE ? "ACTIVE" :
547 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700548
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800549 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700550 if (mStatus == STATUS_ERROR) {
551 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
552 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800553 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800554 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000555 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
556 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
557 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800558 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800559
560 if (mInputStream != NULL) {
561 write(fd, lines.string(), lines.size());
562 mInputStream->dump(fd, args);
563 } else {
564 lines.appendFormat(" No input stream.\n");
565 write(fd, lines.string(), lines.size());
566 }
567 for (size_t i = 0; i < mOutputStreams.size(); i++) {
568 mOutputStreams[i]->dump(fd,args);
569 }
570
Zhijun He431503c2016-03-07 17:30:16 -0800571 if (mBufferManager != NULL) {
572 lines = String8(" Camera3 Buffer Manager:\n");
573 write(fd, lines.string(), lines.size());
574 mBufferManager->dump(fd, args);
575 }
Zhijun He125684a2015-12-26 15:07:30 -0800576
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700577 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700578 if (mInFlightLock.try_lock()) {
579 if (mInFlightMap.size() == 0) {
580 lines.append(" None\n");
581 } else {
582 for (size_t i = 0; i < mInFlightMap.size(); i++) {
583 InFlightRequest r = mInFlightMap.valueAt(i);
584 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
585 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
586 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
587 r.numBuffersLeft);
588 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700589 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700590 mInFlightLock.unlock();
591 } else {
592 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700593 }
594 write(fd, lines.string(), lines.size());
595
Shuzhen Wang686f6442017-06-20 16:16:04 -0700596 if (mRequestThread != NULL) {
597 mRequestThread->dumpCaptureRequestLatency(fd,
598 " ProcessCaptureRequest latency histogram:");
599 }
600
Igor Murashkin1e479c02013-09-06 16:55:14 -0700601 {
602 lines = String8(" Last request sent:\n");
603 write(fd, lines.string(), lines.size());
604
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700605 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700606 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
607 }
608
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800609 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700610 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800611 "TEMPLATE_PREVIEW",
612 "TEMPLATE_STILL_CAPTURE",
613 "TEMPLATE_VIDEO_RECORD",
614 "TEMPLATE_VIDEO_SNAPSHOT",
615 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800616 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800617 };
618
Emilian Peevf4816702020-04-03 15:44:51 -0700619 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 camera_metadata_t *templateRequest = nullptr;
621 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700622 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800623 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800624 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800625 lines.append(" Not supported\n");
626 write(fd, lines.string(), lines.size());
627 } else {
628 write(fd, lines.string(), lines.size());
629 dump_indented_camera_metadata(templateRequest,
630 fd, /*verbosity*/2, /*indentation*/8);
631 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800633 }
634 }
635
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700636 mTagMonitor.dumpMonitoredMetadata(fd);
637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800639 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800642 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700644 if (gotLock) mLock.unlock();
645 if (gotInterfaceLock) mInterfaceLock.unlock();
646
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800647 return OK;
648}
649
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700650status_t Camera3Device::startWatchingTags(const String8 &tags) {
651 mTagMonitor.parseTagsToMonitor(tags);
652 return OK;
653}
654
655status_t Camera3Device::stopWatchingTags() {
656 mTagMonitor.disableMonitoring();
657 return OK;
658}
659
660status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
661 mTagMonitor.getLatestMonitoredTagEvents(out);
662 return OK;
663}
664
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800667 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
668 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700669 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800670 mStatus == STATUS_ERROR ?
671 "when in error state" : "before init");
672 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700673 if (physicalId.isEmpty()) {
674 return mDeviceInfo;
675 } else {
676 std::string id(physicalId.c_str());
677 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
678 return mPhysicalDeviceInfoMap.at(id);
679 } else {
680 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
681 return mDeviceInfo;
682 }
683 }
684}
685
686const CameraMetadata& Camera3Device::info() const {
687 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800688 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800689}
690
Jianing Wei90e59c92014-03-12 18:29:36 -0700691status_t Camera3Device::checkStatusOkToCaptureLocked() {
692 switch (mStatus) {
693 case STATUS_ERROR:
694 CLOGE("Device has encountered a serious error");
695 return INVALID_OPERATION;
696 case STATUS_UNINITIALIZED:
697 CLOGE("Device not initialized");
698 return INVALID_OPERATION;
699 case STATUS_UNCONFIGURED:
700 case STATUS_CONFIGURED:
701 case STATUS_ACTIVE:
702 // OK
703 break;
704 default:
705 SET_ERR_L("Unexpected status: %d", mStatus);
706 return INVALID_OPERATION;
707 }
708 return OK;
709}
710
711status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000712 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700713 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700714 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700715 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700716 if (requestList == NULL) {
717 CLOGE("requestList cannot be NULL.");
718 return BAD_VALUE;
719 }
720
Jianing Weicb0652e2014-03-12 18:29:36 -0700721 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000722 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700723 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
724 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
725 ++metadataIt, ++surfaceMapIt) {
726 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700727 if (newRequest == 0) {
728 CLOGE("Can't create capture request");
729 return BAD_VALUE;
730 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700731
Shuzhen Wang9d066012016-09-30 11:30:20 -0700732 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700733 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700734
Jianing Weicb0652e2014-03-12 18:29:36 -0700735 // Setup burst Id and request Id
736 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800737 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
738 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700739 CLOGE("RequestID does not exist in metadata");
740 return BAD_VALUE;
741 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800742 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700743
Jianing Wei90e59c92014-03-12 18:29:36 -0700744 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700745
746 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700747 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700748 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
749 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
750 return BAD_VALUE;
751 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700752
753 // Setup batch size if this is a high speed video recording request.
754 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
755 auto firstRequest = requestList->begin();
756 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
757 if (outputStream->isVideoStream()) {
758 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800759 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700760 break;
761 }
762 }
763 }
764
Jianing Wei90e59c92014-03-12 18:29:36 -0700765 return OK;
766}
767
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800768status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800769 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770
Emilian Peevaebbe412018-01-15 13:53:24 +0000771 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700772 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800775 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700776}
777
Emilian Peevaebbe412018-01-15 13:53:24 +0000778void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700779 std::list<const SurfaceMap>& surfaceMaps,
780 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000781 PhysicalCameraSettingsList requestList;
782 requestList.push_back({std::string(getId().string()), request});
783 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784
785 SurfaceMap surfaceMap;
786 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
787 // With no surface list passed in, stream and surface will have 1-to-1
788 // mapping. So the surface index is 0 for each stream in the surfaceMap.
789 for (size_t i = 0; i < streams.count; i++) {
790 surfaceMap[streams.data.i32[i]].push_back(0);
791 }
792 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800793}
794
Jianing Wei90e59c92014-03-12 18:29:36 -0700795status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000796 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700797 const std::list<const SurfaceMap> &surfaceMaps,
798 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700799 /*out*/
800 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700802 nsecs_t requestTimeNs = systemTime();
803
Jianing Wei90e59c92014-03-12 18:29:36 -0700804 Mutex::Autolock il(mInterfaceLock);
805 Mutex::Autolock l(mLock);
806
807 status_t res = checkStatusOkToCaptureLocked();
808 if (res != OK) {
809 // error logged by previous call
810 return res;
811 }
812
813 RequestList requestList;
814
Shuzhen Wang0129d522016-10-30 22:43:41 -0700815 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700816 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700817 if (res != OK) {
818 // error logged by previous call
819 return res;
820 }
821
822 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700823 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700825 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 }
827
828 if (res == OK) {
829 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
830 if (res != OK) {
831 SET_ERR_L("Can't transition to active in %f seconds!",
832 kActiveTimeout/1e9);
833 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800834 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700835 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700836 } else {
837 CLOGE("Cannot queue request. Impossible.");
838 return BAD_VALUE;
839 }
840
841 return res;
842}
843
Emilian Peevaebbe412018-01-15 13:53:24 +0000844status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700845 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700846 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700847 ATRACE_CALL();
848
Emilian Peevaebbe412018-01-15 13:53:24 +0000849 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800851
Jianing Weicb0652e2014-03-12 18:29:36 -0700852status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
853 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700857 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700861 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800862}
863
Emilian Peevaebbe412018-01-15 13:53:24 +0000864status_t Camera3Device::setStreamingRequestList(
865 const List<const PhysicalCameraSettingsList> &requestsList,
866 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700867 ATRACE_CALL();
868
Emilian Peevaebbe412018-01-15 13:53:24 +0000869 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800871
872sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000873 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800874 status_t res;
875
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700876 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800877 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
878 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700880 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700881 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800882 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700883 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700885 } else if (mStatus == STATUS_UNCONFIGURED) {
886 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700887 CLOGE("No streams configured");
888 return NULL;
889 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800890 }
891
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800893 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800894}
895
Jianing Weicb0652e2014-03-12 18:29:36 -0700896status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700898 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800899 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800900
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800901 switch (mStatus) {
902 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700903 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800904 return INVALID_OPERATION;
905 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700906 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800907 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700908 case STATUS_UNCONFIGURED:
909 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800910 case STATUS_ACTIVE:
911 // OK
912 break;
913 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700914 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800915 return INVALID_OPERATION;
916 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800917 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700918
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800920}
921
922status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
923 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700924 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700926 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800927}
928
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700929status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800930 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700931 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700932 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700933 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800935 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
936 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700937
938 status_t res;
939 bool wasActive = false;
940
941 switch (mStatus) {
942 case STATUS_ERROR:
943 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
944 return INVALID_OPERATION;
945 case STATUS_UNINITIALIZED:
946 ALOGE("%s: Device not initialized", __FUNCTION__);
947 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700948 case STATUS_UNCONFIGURED:
949 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950 // OK
951 break;
952 case STATUS_ACTIVE:
953 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700954 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700956 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700957 return res;
958 }
959 wasActive = true;
960 break;
961 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700962 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 return INVALID_OPERATION;
964 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700965 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700966
967 if (mInputStream != 0) {
968 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
969 return INVALID_OPERATION;
970 }
971
972 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
973 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700974 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700975
976 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800977 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700978
979 *id = mNextStreamId++;
980
981 // Continue captures if active at start
982 if (wasActive) {
983 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100984 // Reuse current operating mode and session parameters for new stream config
985 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700986 if (res != OK) {
987 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
988 __FUNCTION__, mNextStreamId, strerror(-res), res);
989 return res;
990 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700991 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700992 }
993
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800994 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700995 return OK;
996}
997
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700998status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700999 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001000 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001001 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001002 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1003 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001004 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001005 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001006 ATRACE_CALL();
1007
1008 if (consumer == nullptr) {
1009 ALOGE("%s: consumer must not be null", __FUNCTION__);
1010 return BAD_VALUE;
1011 }
1012
1013 std::vector<sp<Surface>> consumers;
1014 consumers.push_back(consumer);
1015
1016 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001017 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001018 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001019 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001020}
1021
1022static bool isRawFormat(int format) {
1023 switch (format) {
1024 case HAL_PIXEL_FORMAT_RAW16:
1025 case HAL_PIXEL_FORMAT_RAW12:
1026 case HAL_PIXEL_FORMAT_RAW10:
1027 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1028 return true;
1029 default:
1030 return false;
1031 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001032}
1033
1034status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1035 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001036 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001037 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001038 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001039 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001040 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001041 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001042
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001043 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001044 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001045 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001046 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001047 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001048 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001049 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001050 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001051 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001052 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1053 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001054
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 status_t res;
1056 bool wasActive = false;
1057
1058 switch (mStatus) {
1059 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001060 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001061 return INVALID_OPERATION;
1062 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001063 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001065 case STATUS_UNCONFIGURED:
1066 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001067 // OK
1068 break;
1069 case STATUS_ACTIVE:
1070 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001071 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001072 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001073 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 return res;
1075 }
1076 wasActive = true;
1077 break;
1078 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001079 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080 return INVALID_OPERATION;
1081 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001082 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083
1084 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001085
Shuzhen Wang0129d522016-10-30 22:43:41 -07001086 if (consumers.size() == 0 && !hasDeferredConsumer) {
1087 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1088 return BAD_VALUE;
1089 }
Zhijun He5d677d12016-05-29 16:52:39 -07001090
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001092 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1093 return BAD_VALUE;
1094 }
1095
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001096 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1097 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1098 // be found in only one sensor pixel mode.
1099 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1100 return BAD_VALUE;
1101 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001102 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001103 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001104 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001105 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001106 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001107 if (blobBufferSize <= 0) {
1108 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1109 return BAD_VALUE;
1110 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001111 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1112 blobBufferSize = width * height;
1113 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001114 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001115 if (blobBufferSize <= 0) {
1116 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1117 return BAD_VALUE;
1118 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001119 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001121 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001122 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001123 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001124 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001125 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001126 bool maxResolution =
1127 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1128 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001129 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1130 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001131 if (rawOpaqueBufferSize <= 0) {
1132 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1133 return BAD_VALUE;
1134 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001135 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001136 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001137 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001138 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001139 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001140 } else if (isShared) {
1141 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1142 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001143 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001144 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001145 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001146 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001147 newStream = new Camera3OutputStream(mNextStreamId,
1148 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001149 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001150 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001151 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001153 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001154 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001155 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001156 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001157 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 }
Emilian Peev40ead602017-09-26 15:46:36 +01001159
1160 size_t consumerCount = consumers.size();
1161 for (size_t i = 0; i < consumerCount; i++) {
1162 int id = newStream->getSurfaceId(consumers[i]);
1163 if (id < 0) {
1164 SET_ERR_L("Invalid surface id");
1165 return BAD_VALUE;
1166 }
1167 if (surfaceIds != nullptr) {
1168 surfaceIds->push_back(id);
1169 }
1170 }
1171
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173
Emilian Peev08dd2452017-04-06 16:55:14 +01001174 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001175
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001176 newStream->setImageDumpMask(mImageDumpMask);
1177
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 res = mOutputStreams.add(mNextStreamId, newStream);
1179 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181 return res;
1182 }
1183
Shuzhen Wang316781a2020-08-18 18:11:01 -07001184 mSessionStatsBuilder.addStream(mNextStreamId);
1185
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001187 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188
1189 // Continue captures if active at start
1190 if (wasActive) {
1191 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001192 // Reuse current operating mode and session parameters for new stream config
1193 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001195 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1196 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return res;
1198 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001201 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001203}
1204
Emilian Peev710c1422017-08-30 11:19:38 +01001205status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001207 if (nullptr == streamInfo) {
1208 return BAD_VALUE;
1209 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 switch (mStatus) {
1214 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001215 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return INVALID_OPERATION;
1217 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 case STATUS_UNCONFIGURED:
1221 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 case STATUS_ACTIVE:
1223 // OK
1224 break;
1225 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001226 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 return INVALID_OPERATION;
1228 }
1229
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001230 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1231 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001233 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 }
1235
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001236 streamInfo->width = stream->getWidth();
1237 streamInfo->height = stream->getHeight();
1238 streamInfo->format = stream->getFormat();
1239 streamInfo->dataSpace = stream->getDataSpace();
1240 streamInfo->formatOverridden = stream->isFormatOverridden();
1241 streamInfo->originalFormat = stream->getOriginalFormat();
1242 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1243 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001244 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001245 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247}
1248
1249status_t Camera3Device::setStreamTransform(int id,
1250 int transform) {
1251 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 switch (mStatus) {
1256 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 case STATUS_UNCONFIGURED:
1263 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 case STATUS_ACTIVE:
1265 // OK
1266 break;
1267 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001268 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 return INVALID_OPERATION;
1270 }
1271
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001272 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1273 if (stream == nullptr) {
1274 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return BAD_VALUE;
1276 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001277 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
1280status_t Camera3Device::deleteStream(int id) {
1281 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 Mutex::Autolock l(mLock);
1284 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001285
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001287
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 // CameraDevice semantics require device to already be idle before
1289 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001291 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001292 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 }
1294
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001295 if (mStatus == STATUS_ERROR) {
1296 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1297 __FUNCTION__, mId.string());
1298 return -EBUSY;
1299 }
1300
Igor Murashkin2fba5842013-04-22 14:03:54 -07001301 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001302 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001303 if (mInputStream != NULL && id == mInputStream->getId()) {
1304 deletedStream = mInputStream;
1305 mInputStream.clear();
1306 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001307 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001308 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 return BAD_VALUE;
1310 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001311 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001312 }
1313
1314 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001315 if (stream != nullptr) {
1316 deletedStream = stream;
1317 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 }
1319
1320 // Free up the stream endpoint so that it can be used by some other stream
1321 res = deletedStream->disconnect();
1322 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001323 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001324 // fall through since we want to still list the stream as deleted.
1325 }
1326 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001327 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001328
1329 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001330}
1331
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001332status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001333 ATRACE_CALL();
1334 ALOGV("%s: E", __FUNCTION__);
1335
1336 Mutex::Autolock il(mInterfaceLock);
1337 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001338
Emilian Peev811d2952018-05-25 11:08:40 +01001339 // In case the client doesn't include any session parameter, try a
1340 // speculative configuration using the values from the last cached
1341 // default request.
1342 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001343 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001344 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1345 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1346 mLastTemplateId);
1347 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1348 operatingMode);
1349 }
1350
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001351 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1352}
1353
1354status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1355 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001356 //Filter out any incoming session parameters
1357 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001358 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1359 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001360 CameraMetadata filteredParams(availableSessionKeys.count);
1361 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1362 filteredParams.getAndLock());
1363 set_camera_metadata_vendor_id(meta, mVendorTagId);
1364 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001365 if (availableSessionKeys.count > 0) {
1366 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1367 camera_metadata_ro_entry entry = params.find(
1368 availableSessionKeys.data.i32[i]);
1369 if (entry.count > 0) {
1370 filteredParams.update(entry);
1371 }
1372 }
1373 }
1374
1375 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001376}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001378status_t Camera3Device::getInputBufferProducer(
1379 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001380 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001381 Mutex::Autolock il(mInterfaceLock);
1382 Mutex::Autolock l(mLock);
1383
1384 if (producer == NULL) {
1385 return BAD_VALUE;
1386 } else if (mInputStream == NULL) {
1387 return INVALID_OPERATION;
1388 }
1389
1390 return mInputStream->getInputBufferProducer(producer);
1391}
1392
Emilian Peevf4816702020-04-03 15:44:51 -07001393status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001394 CameraMetadata *request) {
1395 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001396 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001397
Emilian Peevf4816702020-04-03 15:44:51 -07001398 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001399 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001400 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001401 return BAD_VALUE;
1402 }
1403
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001404 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001406 {
1407 Mutex::Autolock l(mLock);
1408 switch (mStatus) {
1409 case STATUS_ERROR:
1410 CLOGE("Device has encountered a serious error");
1411 return INVALID_OPERATION;
1412 case STATUS_UNINITIALIZED:
1413 CLOGE("Device is not initialized!");
1414 return INVALID_OPERATION;
1415 case STATUS_UNCONFIGURED:
1416 case STATUS_CONFIGURED:
1417 case STATUS_ACTIVE:
1418 // OK
1419 break;
1420 default:
1421 SET_ERR_L("Unexpected status: %d", mStatus);
1422 return INVALID_OPERATION;
1423 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001424
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001425 if (!mRequestTemplateCache[templateId].isEmpty()) {
1426 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001427 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001428 return OK;
1429 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001430 }
1431
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001432 camera_metadata_t *rawRequest;
1433 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001434 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001435
1436 {
1437 Mutex::Autolock l(mLock);
1438 if (res == BAD_VALUE) {
1439 ALOGI("%s: template %d is not supported on this camera device",
1440 __FUNCTION__, templateId);
1441 return res;
1442 } else if (res != OK) {
1443 CLOGE("Unable to construct request template %d: %s (%d)",
1444 templateId, strerror(-res), res);
1445 return res;
1446 }
1447
1448 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1449 mRequestTemplateCache[templateId].acquire(rawRequest);
1450
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001451 // Override the template request with zoomRatioMapper
1452 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1453 &mRequestTemplateCache[templateId]);
1454 if (res != OK) {
1455 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1456 templateId, strerror(-res), res);
1457 return res;
1458 }
1459
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001460 // Fill in JPEG_QUALITY if not available
1461 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1462 static const uint8_t kDefaultJpegQuality = 95;
1463 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1464 &kDefaultJpegQuality, 1);
1465 }
1466
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001467 // Fill in AUTOFRAMING if not available
1468 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1469 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1470 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1471 &kDefaultAutoframingMode, 1);
1472 }
1473
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001474 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001475 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001476 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477 return OK;
1478}
1479
1480status_t Camera3Device::waitUntilDrained() {
1481 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001483 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001485
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001486 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001487}
1488
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 switch (mStatus) {
1491 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 ALOGV("%s: Already idle", __FUNCTION__);
1494 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 case STATUS_CONFIGURED:
1496 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 case STATUS_ERROR:
1498 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 break;
1501 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001502 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return INVALID_OPERATION;
1504 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001505 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1506 maxExpectedDuration);
1507 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001508 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001509 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001510 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1511 res);
1512 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 return res;
1514}
1515
Ruben Brunk183f0562015-08-12 12:55:02 -07001516void Camera3Device::internalUpdateStatusLocked(Status status) {
1517 mStatus = status;
1518 mRecentStatusUpdates.add(mStatus);
1519 mStatusChanged.broadcast();
1520}
1521
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001523status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001524 if (mRequestThread.get() != nullptr) {
1525 mRequestThread->setPaused(true);
1526 } else {
1527 return NO_INIT;
1528 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001529
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001530 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1531 maxExpectedDuration);
1532 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001534 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001536 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 }
1538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 return res;
1540}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542// Resume after internalPauseAndWaitLocked
1543status_t Camera3Device::internalResumeLocked() {
1544 status_t res;
1545
1546 mRequestThread->setPaused(false);
1547
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001548 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1549 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1551 if (res != OK) {
1552 SET_ERR_L("Can't transition to active in %f seconds!",
1553 kActiveTimeout/1e9);
1554 }
1555 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557}
1558
Ruben Brunk183f0562015-08-12 12:55:02 -07001559status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001561
1562 size_t startIndex = 0;
1563 if (mStatusWaiters == 0) {
1564 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1565 // this status list
1566 mRecentStatusUpdates.clear();
1567 } else {
1568 // If other threads are waiting on updates to this status list, set the position of the
1569 // first element that this list will check rather than clearing the list.
1570 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 }
1572
Ruben Brunk183f0562015-08-12 12:55:02 -07001573 mStatusWaiters++;
1574
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001575 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001576 if (!active && mUseHalBufManager) {
1577 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001578 if (mStatus == STATUS_ACTIVE) {
1579 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001580 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001581 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001582 mRequestBufferSM.onWaitUntilIdle();
1583 }
1584
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001586 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001588 if (active == (mStatus == STATUS_ACTIVE)) {
1589 // Desired state is current
1590 break;
1591 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001593 nsecs_t timeElapsed = systemTime() - startTime;
1594 nsecs_t timeToWait = timeout - timeElapsed;
1595 if (timeToWait <= 0) {
1596 // Thread woke up spuriously but has timed out since.
1597 // Force out of loop with TIMED_OUT result.
1598 res = TIMED_OUT;
1599 break;
1600 }
1601 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 if (res != OK) break;
1603
Ruben Brunk183f0562015-08-12 12:55:02 -07001604 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1605 // transitions.
1606 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1607 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1608 __FUNCTION__);
1609
1610 // Encountered desired state since we began waiting
1611 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1613 stateSeen = true;
1614 break;
1615 }
1616 }
1617 } while (!stateSeen);
1618
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001619 if (signalPipelineDrain) {
1620 mRequestThread->resetPipelineDrain();
1621 }
1622
Ruben Brunk183f0562015-08-12 12:55:02 -07001623 mStatusWaiters--;
1624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 return res;
1626}
1627
1628
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001629status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001631 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001633 if (listener != NULL && mListener != NULL) {
1634 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1635 }
1636 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001637 mRequestThread->setNotificationListener(listener);
1638 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001639
1640 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641}
1642
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001643bool Camera3Device::willNotify3A() {
1644 return false;
1645}
1646
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001648 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001649 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001650
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001651 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001652 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1653 if (st == std::cv_status::timeout) {
1654 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001655 }
1656 }
1657 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658}
1659
Jianing Weicb0652e2014-03-12 18:29:36 -07001660status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001662 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001664 if (mResultQueue.empty()) {
1665 return NOT_ENOUGH_DATA;
1666 }
1667
Jianing Weicb0652e2014-03-12 18:29:36 -07001668 if (frame == NULL) {
1669 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1670 return BAD_VALUE;
1671 }
1672
1673 CaptureResult &result = *(mResultQueue.begin());
1674 frame->mResultExtras = result.mResultExtras;
1675 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001676 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001677 mResultQueue.erase(mResultQueue.begin());
1678
1679 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680}
1681
1682status_t Camera3Device::triggerAutofocus(uint32_t id) {
1683 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1687 // Mix-in this trigger into the next request and only the next request.
1688 RequestTrigger trigger[] = {
1689 {
1690 ANDROID_CONTROL_AF_TRIGGER,
1691 ANDROID_CONTROL_AF_TRIGGER_START
1692 },
1693 {
1694 ANDROID_CONTROL_AF_TRIGGER_ID,
1695 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001696 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 };
1698
1699 return mRequestThread->queueTrigger(trigger,
1700 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001701}
1702
1703status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1704 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001706
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001707 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1708 // Mix-in this trigger into the next request and only the next request.
1709 RequestTrigger trigger[] = {
1710 {
1711 ANDROID_CONTROL_AF_TRIGGER,
1712 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1713 },
1714 {
1715 ANDROID_CONTROL_AF_TRIGGER_ID,
1716 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001717 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001718 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001719
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001720 return mRequestThread->queueTrigger(trigger,
1721 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001722}
1723
1724status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1725 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001728 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1729 // Mix-in this trigger into the next request and only the next request.
1730 RequestTrigger trigger[] = {
1731 {
1732 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1733 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1734 },
1735 {
1736 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1737 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001738 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001739 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001741 return mRequestThread->queueTrigger(trigger,
1742 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
Jianing Weicb0652e2014-03-12 18:29:36 -07001745status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001746 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001747 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001748 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001749
Zhijun He7ef20392014-04-21 16:04:17 -07001750 {
1751 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001752
1753 // b/116514106 "disconnect()" can get called twice for the same device. The
1754 // camera device will not be initialized during the second run.
1755 if (mStatus == STATUS_UNINITIALIZED) {
1756 return OK;
1757 }
1758
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001759 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001760
1761 // Stop session and stream counter
1762 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001763 }
1764
Ravneetdbd5b242022-03-02 07:22:46 +00001765 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001766 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001767 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1768 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1769
1770 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001771}
1772
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001773status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001774 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1775}
1776
1777status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001778 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001779 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001780 Mutex::Autolock il(mInterfaceLock);
1781 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001782
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001783 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1784 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001785 CLOGE("Stream %d does not exist", streamId);
1786 return BAD_VALUE;
1787 }
1788
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001789 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001790 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001791 return BAD_VALUE;
1792 }
1793
1794 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001795 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001796 return BAD_VALUE;
1797 }
1798
Ruben Brunkc78ac262015-08-13 17:58:46 -07001799 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001800}
1801
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001802status_t Camera3Device::tearDown(int streamId) {
1803 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001804 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001805 Mutex::Autolock il(mInterfaceLock);
1806 Mutex::Autolock l(mLock);
1807
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001808 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1809 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001810 CLOGE("Stream %d does not exist", streamId);
1811 return BAD_VALUE;
1812 }
1813
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001814 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1815 CLOGE("Stream %d is a target of a in-progress request", streamId);
1816 return BAD_VALUE;
1817 }
1818
1819 return stream->tearDown();
1820}
1821
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001822status_t Camera3Device::addBufferListenerForStream(int streamId,
1823 wp<Camera3StreamBufferListener> listener) {
1824 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001825 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001826 Mutex::Autolock il(mInterfaceLock);
1827 Mutex::Autolock l(mLock);
1828
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001829 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1830 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001831 CLOGE("Stream %d does not exist", streamId);
1832 return BAD_VALUE;
1833 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001834 stream->addBufferListener(listener);
1835
1836 return OK;
1837}
1838
Austin Borger4a870a32022-02-25 01:48:41 +00001839float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1840 camera_metadata_entry minDurations =
1841 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1842 for (size_t i = 0; i < minDurations.count; i += 4) {
1843 if (minDurations.data.i64[i] == stream->getFormat()
1844 && minDurations.data.i64[i+1] == stream->getWidth()
1845 && minDurations.data.i64[i+2] == stream->getHeight()) {
1846 int64_t minFrameDuration = minDurations.data.i64[i+3];
1847 return 1e9f / minFrameDuration;
1848 }
1849 }
1850 return 0.0f;
1851}
1852
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 * Methods called by subclasses
1855 */
1856
1857void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001858 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001859 std::vector<int> streamIds;
1860 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001861 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001862
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863 {
1864 // Need mLock to safely update state and synchronize to current
1865 // state of methods in flight.
1866 Mutex::Autolock l(mLock);
1867 // We can get various system-idle notices from the status tracker
1868 // while starting up. Only care about them if we've actually sent
1869 // in some requests recently.
1870 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1871 return;
1872 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001873 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1874 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001875 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876
1877 // Skip notifying listener if we're doing some user-transparent
1878 // state changes
1879 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001880
Austin Borger4a870a32022-02-25 01:48:41 +00001881 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1882 auto stream = mOutputStreams[i];
1883 if (stream.get() == nullptr) continue;
1884
1885 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1886 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1887
1888 // Populate stream statistics in case of Idle
1889 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001890 streamIds.push_back(stream->getId());
1891 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1892 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001893 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001894 if (camera3Stream != nullptr) {
1895 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001896 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001897 }
1898 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001899 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001900 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001901 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001902 stream->getDynamicRangeProfile(), streamUseCase,
1903 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001904 }
1905 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001906 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001907
1908 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001909 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001910 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001911 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001912 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001913 status_t res = OK;
1914 if (listener != nullptr) {
1915 if (idle) {
1916 // Get session stats from the builder, and notify the listener.
1917 int64_t requestCount, resultErrorCount;
1918 bool deviceError;
1919 std::map<int, StreamStats> streamStatsMap;
1920 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1921 &deviceError, &streamStatsMap);
1922 for (size_t i = 0; i < streamIds.size(); i++) {
1923 int streamId = streamIds[i];
1924 auto stats = streamStatsMap.find(streamId);
1925 if (stats != streamStatsMap.end()) {
1926 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1927 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1928 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1929 streamStats[i].mHistogramType =
1930 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1931 streamStats[i].mHistogramBins.assign(
1932 stats->second.mCaptureLatencyBins.begin(),
1933 stats->second.mCaptureLatencyBins.end());
1934 streamStats[i].mHistogramCounts.assign(
1935 stats->second.mCaptureLatencyHistogram.begin(),
1936 stats->second.mCaptureLatencyHistogram.end());
1937 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001938 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001939 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1940 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001941 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001942 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001943 }
1944 if (res != OK) {
1945 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1946 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947 }
1948}
1949
Shuzhen Wang758c2152017-01-10 18:26:18 -08001950status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001951 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001952 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001953 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1954 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001955
1956 if (surfaceIds == nullptr) {
1957 return BAD_VALUE;
1958 }
1959
Zhijun He5d677d12016-05-29 16:52:39 -07001960 Mutex::Autolock il(mInterfaceLock);
1961 Mutex::Autolock l(mLock);
1962
Shuzhen Wang758c2152017-01-10 18:26:18 -08001963 if (consumers.size() == 0) {
1964 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001965 return BAD_VALUE;
1966 }
1967
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001968 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1969 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001970 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001972 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001973
1974 // isConsumerConfigurationDeferred will be off after setConsumers
1975 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001976 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001977 if (res != OK) {
1978 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1979 return res;
1980 }
1981
Emilian Peev40ead602017-09-26 15:46:36 +01001982 for (auto &consumer : consumers) {
1983 int id = stream->getSurfaceId(consumer);
1984 if (id < 0) {
1985 CLOGE("Invalid surface id!");
1986 return BAD_VALUE;
1987 }
1988 surfaceIds->push_back(id);
1989 }
1990
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001991 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001992 if (!stream->isConfiguring()) {
1993 CLOGE("Stream %d was already fully configured.", streamId);
1994 return INVALID_OPERATION;
1995 }
Zhijun He5d677d12016-05-29 16:52:39 -07001996
Shuzhen Wang0129d522016-10-30 22:43:41 -07001997 res = stream->finishConfiguration();
1998 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001999 // If finishConfiguration fails due to abandoned surface, do not set
2000 // device to error state.
2001 bool isSurfaceAbandoned =
2002 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2003 if (!isSurfaceAbandoned) {
2004 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2005 stream->getId(), strerror(-res), res);
2006 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002007 return res;
2008 }
Zhijun He5d677d12016-05-29 16:52:39 -07002009 }
2010
2011 return OK;
2012}
2013
Emilian Peev40ead602017-09-26 15:46:36 +01002014status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2015 const std::vector<OutputStreamInfo> &outputInfo,
2016 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2017 Mutex::Autolock il(mInterfaceLock);
2018 Mutex::Autolock l(mLock);
2019
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002020 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2021 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002022 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002023 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002024 }
2025
2026 for (const auto &it : removedSurfaceIds) {
2027 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2028 CLOGE("Shared surface still part of a pending request!");
2029 return -EBUSY;
2030 }
2031 }
2032
Emilian Peev40ead602017-09-26 15:46:36 +01002033 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2034 if (res != OK) {
2035 CLOGE("Stream %d failed to update stream (error %d %s) ",
2036 streamId, res, strerror(-res));
2037 if (res == UNKNOWN_ERROR) {
2038 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2039 __FUNCTION__);
2040 }
2041 return res;
2042 }
2043
2044 return res;
2045}
2046
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002047status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2048 Mutex::Autolock il(mInterfaceLock);
2049 Mutex::Autolock l(mLock);
2050
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002051 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2052 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002053 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2054 return BAD_VALUE;
2055 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002056
2057 if (dropping) {
2058 mSessionStatsBuilder.stopCounter(streamId);
2059 } else {
2060 mSessionStatsBuilder.startCounter(streamId);
2061 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002062 return stream->dropBuffers(dropping);
2063}
2064
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066 * Camera3Device private methods
2067 */
2068
2069sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002070 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002073 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002074 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075
2076 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002077 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078 if (inputStreams.count > 0) {
2079 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002080 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002081 CLOGE("Request references unknown input stream %d",
2082 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 return NULL;
2084 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002085
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002086 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002087 SET_ERR_L("%s: input stream %d is not configured!",
2088 __FUNCTION__, mInputStream->getId());
2089 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002090 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002091 // Check if stream prepare is blocking requests.
2092 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002093 CLOGE("Request references an input stream that's being prepared!");
2094 return NULL;
2095 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096
2097 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002098 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002099 }
2100
2101 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002102 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002104 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105 return NULL;
2106 }
2107
2108 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002109 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2110 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002111 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002112 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 return NULL;
2114 }
Zhijun He5d677d12016-05-29 16:52:39 -07002115 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002116 auto iter = surfaceMap.find(streams.data.i32[i]);
2117 if (iter != surfaceMap.end()) {
2118 const std::vector<size_t>& surfaces = iter->second;
2119 for (const auto& surface : surfaces) {
2120 if (stream->isConsumerConfigurationDeferred(surface)) {
2121 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2122 "due to deferred consumer", stream->getId(), surface);
2123 return NULL;
2124 }
2125 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002126 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002127 }
2128
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002130 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2131 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002133 // Check if stream prepare is blocking requests.
2134 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002135 CLOGE("Request references an output stream that's being prepared!");
2136 return NULL;
2137 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
2139 newRequest->mOutputStreams.push(stream);
2140 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002141 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002142 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002144 auto rotateAndCropEntry =
2145 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2146 if (rotateAndCropEntry.count > 0 &&
2147 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2148 newRequest->mRotateAndCropAuto = true;
2149 } else {
2150 newRequest->mRotateAndCropAuto = false;
2151 }
2152
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002153 auto autoframingEntry =
2154 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2155 if (autoframingEntry.count > 0 &&
2156 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2157 newRequest->mAutoframingAuto = true;
2158 } else {
2159 newRequest->mAutoframingAuto = false;
2160 }
2161
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002162 auto zoomRatioEntry =
2163 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2164 if (zoomRatioEntry.count > 0 &&
2165 zoomRatioEntry.data.f[0] == 1.0f) {
2166 newRequest->mZoomRatioIs1x = true;
2167 } else {
2168 newRequest->mZoomRatioIs1x = false;
2169 }
2170
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002171 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002172 for (auto& settings : newRequest->mSettingsList) {
2173 auto testPatternModeEntry =
2174 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2175 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2176 testPatternModeEntry.data.i32[0] :
2177 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002178
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002179 auto testPatternDataEntry =
2180 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2181 if (testPatternDataEntry.count >= 4) {
2182 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2183 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2184 } else {
2185 settings.mOriginalTestPatternData[0] = 0;
2186 settings.mOriginalTestPatternData[1] = 0;
2187 settings.mOriginalTestPatternData[2] = 0;
2188 settings.mOriginalTestPatternData[3] = 0;
2189 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002190 }
2191 }
2192
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194}
2195
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002196void Camera3Device::cancelStreamsConfigurationLocked() {
2197 int res = OK;
2198 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2199 res = mInputStream->cancelConfiguration();
2200 if (res != OK) {
2201 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2202 mInputStream->getId(), strerror(-res), res);
2203 }
2204 }
2205
2206 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002207 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002208 if (outputStream->isConfiguring()) {
2209 res = outputStream->cancelConfiguration();
2210 if (res != OK) {
2211 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2212 outputStream->getId(), strerror(-res), res);
2213 }
2214 }
2215 }
2216
2217 // Return state to that at start of call, so that future configures
2218 // properly clean things up
2219 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2220 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002221
2222 res = mPreparerThread->resume();
2223 if (res != OK) {
2224 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2225 }
2226}
2227
Emilian Peev0d0191e2020-04-21 17:01:18 -07002228bool Camera3Device::checkAbandonedStreamsLocked() {
2229 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2230 return true;
2231 }
2232
2233 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2234 auto stream = mOutputStreams[i];
2235 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2236 return true;
2237 }
2238 }
2239
2240 return false;
2241}
2242
Emilian Peev3bead5f2020-05-28 17:29:08 -07002243bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002244 ATRACE_CALL();
2245 bool ret = false;
2246
Shuzhen Wang316781a2020-08-18 18:11:01 -07002247 nsecs_t startTime = systemTime();
2248
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002249 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002250 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2251
2252 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002253 if (checkAbandonedStreamsLocked()) {
2254 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2255 __FUNCTION__);
2256 return true;
2257 }
2258
Emilian Peev3bead5f2020-05-28 17:29:08 -07002259 status_t rc = NO_ERROR;
2260 bool markClientActive = false;
2261 if (mStatus == STATUS_ACTIVE) {
2262 markClientActive = true;
2263 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002264
2265 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2266 }
2267
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002268 if (rc == NO_ERROR) {
2269 mNeedConfig = true;
2270 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2271 if (rc == NO_ERROR) {
2272 ret = true;
2273 mPauseStateNotify = false;
2274 //Moving to active state while holding 'mLock' is important.
2275 //There could be pending calls to 'create-/deleteStream' which
2276 //will trigger another stream configuration while the already
2277 //present streams end up with outstanding buffers that will
2278 //not get drained.
2279 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002280 } else if (rc == DEAD_OBJECT) {
2281 // DEAD_OBJECT can be returned if either the consumer surface is
2282 // abandoned, or the HAL has died.
2283 // - If the HAL has died, configureStreamsLocked call will set
2284 // device to error state,
2285 // - If surface is abandoned, we should not set device to error
2286 // state.
2287 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002288 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002289 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002290 }
2291 } else {
2292 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2293 }
2294
Austin Borger74fca042022-05-23 12:41:21 -07002295 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002296 ns2ms(systemTime() - startTime));
2297
Emilian Peev3bead5f2020-05-28 17:29:08 -07002298 if (markClientActive) {
2299 mStatusTracker->markComponentActive(clientStatusId);
2300 }
2301
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002302 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002303}
2304
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002305status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002306 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 ATRACE_CALL();
2308 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002310 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002311 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 return INVALID_OPERATION;
2313 }
2314
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002315 if (operatingMode < 0) {
2316 CLOGE("Invalid operating mode: %d", operatingMode);
2317 return BAD_VALUE;
2318 }
2319
2320 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002321 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002322
2323 if (mOperatingMode != operatingMode) {
2324 mNeedConfig = true;
2325 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2326 mOperatingMode = operatingMode;
2327 }
2328
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002329 // Reset min expected duration when session is reconfigured.
2330 mMinExpectedDuration = 0;
2331
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002332 // In case called from configureStreams, abort queued input buffers not belonging to
2333 // any pending requests.
2334 if (mInputStream != NULL && notifyRequestThread) {
2335 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002336 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002337 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002338 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002339 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002340 if (res != OK) {
2341 // Exhausted acquiring all input buffers.
2342 break;
2343 }
2344
Emilian Peevf4816702020-04-03 15:44:51 -07002345 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002346 res = mInputStream->returnInputBuffer(inputBuffer);
2347 if (res != OK) {
2348 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2349 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2350 }
2351 }
2352 }
2353
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002354 if (!mNeedConfig) {
2355 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2356 return OK;
2357 }
2358
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002359 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002360 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002361 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2362 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002363 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002364 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002365 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002366 }
2367
Shuzhen Wang16610a62022-12-15 22:38:07 -08002368 // Override stream use case based on "adb shell command"
2369 overrideStreamUseCaseLocked();
2370
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002372 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002374 mPreparerThread->pause();
2375
Emilian Peevf4816702020-04-03 15:44:51 -07002376 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002377 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002379 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380
Emilian Peevf4816702020-04-03 15:44:51 -07002381 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002383 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002384
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385
2386 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002387 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 inputStream = mInputStream->startConfiguration();
2389 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002390 CLOGE("Can't start input stream configuration");
2391 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 return INVALID_OPERATION;
2393 }
2394 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002395
2396 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 }
2398
Shuzhen Wang99080502021-03-07 21:08:20 -08002399 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002400 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002402
2403 // Don't configure bidi streams twice, nor add them twice to the list
2404 if (mOutputStreams[i].get() ==
2405 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2406
2407 config.num_streams--;
2408 continue;
2409 }
2410
Emilian Peevf4816702020-04-03 15:44:51 -07002411 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002412 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002414 CLOGE("Can't start output stream configuration");
2415 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002416 return INVALID_OPERATION;
2417 }
2418 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002419
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002420 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002421 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2422 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002423 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2424 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002425 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2426 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002427 } else if (outputStream->data_space ==
2428 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2429 bufferSizes[k] = outputStream->width * outputStream->height;
2430 } else {
2431 ALOGW("%s: Blob dataSpace %d not supported",
2432 __FUNCTION__, outputStream->data_space);
2433 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002434 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002435
2436 if (mOutputStreams[i]->isMultiResolution()) {
2437 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2438 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2439 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2440 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002441
2442 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2443 composerSurfacePresent = true;
2444 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002445 }
2446
2447 config.streams = streams.editArray();
2448
2449 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002450 // max_buffers, usage, and priv fields, as well as data_space and format
2451 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002452
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002453 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002454 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002455 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002456
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002457 if (res == BAD_VALUE) {
2458 // HAL rejected this set of streams as unsupported, clean up config
2459 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002460 CLOGE("Set of requested inputs/outputs not supported by HAL");
2461 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002462 return BAD_VALUE;
2463 } else if (res != OK) {
2464 // Some other kind of error from configure_streams - this is not
2465 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002466 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2467 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002468 return res;
2469 }
2470
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002471 // Finish all stream configuration immediately.
2472 // TODO: Try to relax this later back to lazy completion, which should be
2473 // faster
2474
Igor Murashkin073f8572013-05-02 14:59:28 -07002475 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002476 bool streamReConfigured = false;
2477 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002478 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002479 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002480 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002481 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002482 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2483 return DEAD_OBJECT;
2484 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002485 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002486 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002487 if (streamReConfigured) {
2488 mInterface->onStreamReConfigured(mInputStream->getId());
2489 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002490 }
2491
2492 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002493 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002494 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002495 bool streamReConfigured = false;
2496 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002497 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002498 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002499 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002500 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002501 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2502 return DEAD_OBJECT;
2503 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002505 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002506 if (streamReConfigured) {
2507 mInterface->onStreamReConfigured(outputStream->getId());
2508 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002509 }
2510 }
2511
Emilian Peeve23f1d92021-09-20 14:56:01 -07002512 mRequestThread->setComposerSurface(composerSurfacePresent);
2513
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002514 // Request thread needs to know to avoid using repeat-last-settings protocol
2515 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002516 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002517 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2518 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002519 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520
Zhijun He90f7c372016-08-16 16:19:43 -07002521 char value[PROPERTY_VALUE_MAX];
2522 property_get("camera.fifo.disable", value, "0");
2523 int32_t disableFifo = atoi(value);
2524 if (disableFifo != 1) {
2525 // Boost priority of request thread to SCHED_FIFO.
2526 pid_t requestThreadTid = mRequestThread->getTid();
2527 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002528 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002529 if (res != OK) {
2530 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2531 strerror(-res), res);
2532 } else {
2533 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2534 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002535 }
2536
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002537 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002538 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2539 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2540 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2541 sessionParams.unlock(newSessionParams);
2542 mSessionParams.unlock(currentSessionParams);
2543 if (updateSessionParams) {
2544 mSessionParams = sessionParams;
2545 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002546
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002547 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002548
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002549 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002550 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002552 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002553
Zhijun He0a210512014-07-24 13:45:15 -07002554 // tear down the deleted streams after configure streams.
2555 mDeletedStreams.clear();
2556
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002557 auto rc = mPreparerThread->resume();
2558 if (rc != OK) {
2559 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2560 return rc;
2561 }
2562
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002563 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002564 mRequestBufferSM.onStreamsConfigured();
2565 }
2566
Cliff Wu3b268182021-07-06 15:44:43 +08002567 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002568 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002569 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002570 // configure the injection streams.
2571 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002572 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002573 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2574 res = mInjectionMethods->injectCamera(config, bufferSizes);
2575 if (res != OK) {
2576 ALOGE("Can't finish inject camera process!");
2577 return res;
2578 }
Cliff Wu3b268182021-07-06 15:44:43 +08002579 } else {
2580 // First run configureStreamsLocked() and then call injectCamera() case:
2581 // If the stream configuration has been completed and camera deive is active, but the
2582 // injection camera has not been injected yet, we need to store the stream configuration of
2583 // the internal camera (because the stream configuration of the injection camera is based
2584 // on the internal camera). When injecting occurs later, this configuration can be used by
2585 // the injection camera.
2586 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2587 " injection camera has not been injected yet.", __FUNCTION__);
2588 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002589 }
2590
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002591 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002592}
2593
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002594status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002595 ATRACE_CALL();
2596 status_t res;
2597
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002598 if (mFakeStreamId != NO_STREAM) {
2599 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002600 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002601 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002602 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002603 return INVALID_OPERATION;
2604 }
2605
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002606 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002607
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002608 sp<Camera3OutputStreamInterface> fakeStream =
2609 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002610
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002611 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002612 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002613 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002614 return res;
2615 }
2616
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618 mNextStreamId++;
2619
2620 return OK;
2621}
2622
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002623status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 ATRACE_CALL();
2625 status_t res;
2626
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002627 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002628 if (mOutputStreams.size() == 1) return OK;
2629
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002630 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002631
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002632 // Ok, have a fake stream and there's at least one other output stream,
2633 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002634
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002635 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002636 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002637 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002638 return INVALID_OPERATION;
2639 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002640 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002641
2642 // Free up the stream endpoint so that it can be used by some other stream
2643 res = deletedStream->disconnect();
2644 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002645 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002646 // fall through since we want to still list the stream as deleted.
2647 }
2648 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002649 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002650
2651 return res;
2652}
2653
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002654void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002655 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002656 Mutex::Autolock l(mLock);
2657 va_list args;
2658 va_start(args, fmt);
2659
2660 setErrorStateLockedV(fmt, args);
2661
2662 va_end(args);
2663}
2664
2665void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002666 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002667 Mutex::Autolock l(mLock);
2668 setErrorStateLockedV(fmt, args);
2669}
2670
2671void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2672 va_list args;
2673 va_start(args, fmt);
2674
2675 setErrorStateLockedV(fmt, args);
2676
2677 va_end(args);
2678}
2679
2680void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002681 // Print out all error messages to log
2682 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002683 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002684
2685 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002686 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002687
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002688 mErrorCause = errorCause;
2689
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002690 if (mRequestThread != nullptr) {
2691 mRequestThread->setPaused(true);
2692 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002693 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002694
2695 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002696 sp<NotificationListener> listener = mListener.promote();
2697 if (listener != NULL) {
2698 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002699 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002700 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002701 }
2702
2703 // Save stack trace. View by dumping it later.
2704 CameraTraces::saveTrace();
2705 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002706}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002707
2708/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002709 * In-flight request management
2710 */
2711
Jianing Weicb0652e2014-03-12 18:29:36 -07002712status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002713 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002714 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002715 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002716 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002717 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002718 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002719 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002720 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002721
2722 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002723 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002724 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002725 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2726 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002727 if (res < 0) return res;
2728
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002729 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002730 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2731 // avoid a deadlock during reprocess requests.
2732 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002733 if (mStatusTracker != nullptr) {
2734 mStatusTracker->markComponentActive(mInFlightStatusId);
2735 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002736 }
2737
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002738 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002739 return OK;
2740}
2741
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002742void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002743 // Indicate idle inFlightMap to the status tracker
2744 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002745 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002746 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2747 // avoid a deadlock during reprocess requests.
2748 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002749 if (mStatusTracker != nullptr) {
2750 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2751 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002752 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002753 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002754}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002755
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002756void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002757 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002758 // something has likely gone wrong. This might still be legit only if application send in
2759 // a long burst of long exposure requests.
2760 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2761 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2762 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2763 mInFlightMap.size(), mExpectedInflightDuration);
2764 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2765 kInFlightWarnLimitHighSpeed) {
2766 CLOGW("In-flight list too large for high speed configuration: %zu,"
2767 "total inflight duration %" PRIu64,
2768 mInFlightMap.size(), mExpectedInflightDuration);
2769 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002770 }
2771}
2772
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002773void Camera3Device::onInflightMapFlushedLocked() {
2774 mExpectedInflightDuration = 0;
2775}
2776
2777void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002778 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002779 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2780 mInFlightMap.removeItemsAt(idx, 1);
2781
2782 onInflightEntryRemovedLocked(duration);
2783}
2784
2785
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002786void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002787 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002788 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002789 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002790 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002791 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002792 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002793
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002794 FlushInflightReqStates states {
2795 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002796 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002797
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002798 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002799}
2800
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002801CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002802 ALOGV("%s", __FUNCTION__);
2803
Igor Murashkin1e479c02013-09-06 16:55:14 -07002804 CameraMetadata retVal;
2805
2806 if (mRequestThread != NULL) {
2807 retVal = mRequestThread->getLatestRequest();
2808 }
2809
Igor Murashkin1e479c02013-09-06 16:55:14 -07002810 return retVal;
2811}
2812
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002813void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002814 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002815 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002816 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2817 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002818
2819 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002820 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002821}
2822
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002823void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002824 std::vector<native_handle_t*> *handles, bool closeFd) {
2825 if (handles == nullptr) {
2826 return;
2827 }
2828 if (closeFd) {
2829 for (auto& handle : *handles) {
2830 native_handle_close(handle);
2831 }
2832 }
2833 for (auto& handle : *handles) {
2834 native_handle_delete(handle);
2835 }
2836 handles->clear();
2837 return;
2838}
2839
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002840/**
2841 * HalInterface inner class methods
2842 */
2843
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002844void Camera3Device::HalInterface::getInflightBufferKeys(
2845 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002846 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002847 return;
2848}
2849
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002850void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2851 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002852 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002853 return;
2854}
2855
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002856bool Camera3Device::HalInterface::verifyBufferIds(
2857 int32_t streamId, std::vector<uint64_t>& bufIds) {
2858 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002859}
2860
2861status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002862 int32_t frameNumber, int32_t streamId,
2863 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002864 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002865}
2866
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002867status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002868 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002869 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002870}
2871
2872// Find and pop a buffer_handle_t based on bufferId
2873status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002874 uint64_t bufferId,
2875 /*out*/ buffer_handle_t** buffer,
2876 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002877 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002878}
2879
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002880std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2881 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002882 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002883}
2884
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002885uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2886 const native_handle_t* handle) {
2887 return mBufferRecords.removeOneBufferCache(streamId, handle);
2888}
2889
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002890void Camera3Device::HalInterface::onBufferFreed(
2891 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002892 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2893 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2894 if (bufferId != BUFFER_ID_NO_BUFFER) {
2895 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002896 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002897}
2898
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002899void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002900 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2901 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2902 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002903 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2904 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002905}
2906
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002907/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002908 * RequestThread inner class methods
2909 */
2910
2911Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002912 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002913 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002914 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002915 bool supportCameraMute,
2916 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002917 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002918 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002919 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002920 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002921 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002922 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002923 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002924 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002925 mReconfigured(false),
2926 mDoPause(false),
2927 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002928 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002929 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002930 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002931 mCurrentAfTriggerId(0),
2932 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002933 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00002934 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002935 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002936 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002937 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002938 mRepeatingLastFrameNumber(
2939 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002940 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002941 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002942 mRequestLatency(kRequestLatencyBinSize),
2943 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002944 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002945 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07002946 mSupportCameraMute(supportCameraMute),
2947 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002948 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002949}
2950
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002951Camera3Device::RequestThread::~RequestThread() {}
2952
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002953void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002954 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002955 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002956 Mutex::Autolock l(mRequestLock);
2957 mListener = listener;
2958}
2959
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002960void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002961 const CameraMetadata& sessionParams,
2962 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002963 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002964 Mutex::Autolock l(mRequestLock);
2965 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002966 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002967 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002968 // Prepare video stream for high speed recording.
2969 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002970 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971}
2972
Jianing Wei90e59c92014-03-12 18:29:36 -07002973status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002974 List<sp<CaptureRequest> > &requests,
2975 /*out*/
2976 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002977 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002978 Mutex::Autolock l(mRequestLock);
2979 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2980 ++it) {
2981 mRequestQueue.push_back(*it);
2982 }
2983
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002984 if (lastFrameNumber != NULL) {
2985 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2986 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2987 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2988 *lastFrameNumber);
2989 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002990
Jianing Wei90e59c92014-03-12 18:29:36 -07002991 unpauseForNewRequests();
2992
2993 return OK;
2994}
2995
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002996
2997status_t Camera3Device::RequestThread::queueTrigger(
2998 RequestTrigger trigger[],
2999 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003000 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003001 Mutex::Autolock l(mTriggerMutex);
3002 status_t ret;
3003
3004 for (size_t i = 0; i < count; ++i) {
3005 ret = queueTriggerLocked(trigger[i]);
3006
3007 if (ret != OK) {
3008 return ret;
3009 }
3010 }
3011
3012 return OK;
3013}
3014
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003015const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3016 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003017 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003018 if (d != nullptr) return d->mId;
3019 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003020}
3021
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003022status_t Camera3Device::RequestThread::queueTriggerLocked(
3023 RequestTrigger trigger) {
3024
3025 uint32_t tag = trigger.metadataTag;
3026 ssize_t index = mTriggerMap.indexOfKey(tag);
3027
3028 switch (trigger.getTagType()) {
3029 case TYPE_BYTE:
3030 // fall-through
3031 case TYPE_INT32:
3032 break;
3033 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003034 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3035 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003036 return INVALID_OPERATION;
3037 }
3038
3039 /**
3040 * Collect only the latest trigger, since we only have 1 field
3041 * in the request settings per trigger tag, and can't send more than 1
3042 * trigger per request.
3043 */
3044 if (index != NAME_NOT_FOUND) {
3045 mTriggerMap.editValueAt(index) = trigger;
3046 } else {
3047 mTriggerMap.add(tag, trigger);
3048 }
3049
3050 return OK;
3051}
3052
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003053status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003054 const RequestList &requests,
3055 /*out*/
3056 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003057 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003058 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003059 if (lastFrameNumber != NULL) {
3060 *lastFrameNumber = mRepeatingLastFrameNumber;
3061 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003062 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003063 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003064 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3065 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003066
3067 unpauseForNewRequests();
3068
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003069 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003070 return OK;
3071}
3072
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003073bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003074 if (mRepeatingRequests.empty()) {
3075 return false;
3076 }
3077 int32_t requestId = requestIn->mResultExtras.requestId;
3078 const RequestList &repeatRequests = mRepeatingRequests;
3079 // All repeating requests are guaranteed to have same id so only check first quest
3080 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3081 return (firstRequest->mResultExtras.requestId == requestId);
3082}
3083
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003084status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003085 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003086 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003087 return clearRepeatingRequestsLocked(lastFrameNumber);
3088
3089}
3090
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003091status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3092 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003093 std::vector<int32_t> streamIds;
3094 for (const auto& request : mRepeatingRequests) {
3095 for (const auto& stream : request->mOutputStreams) {
3096 streamIds.push_back(stream->getId());
3097 }
3098 }
3099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003100 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003101 if (lastFrameNumber != NULL) {
3102 *lastFrameNumber = mRepeatingLastFrameNumber;
3103 }
Emilian Peev2295df72021-11-12 18:14:10 -08003104
3105 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3106
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003107 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003108 return OK;
3109}
3110
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003111status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003112 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003113 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003114 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003115 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003116
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003117 // Send errors for all requests pending in the request queue, including
3118 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003119 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003120 if (listener != NULL) {
3121 for (RequestList::iterator it = mRequestQueue.begin();
3122 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003123 // Abort the input buffers for reprocess requests.
3124 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003125 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003126 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003127 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003128 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003129 if (res != OK) {
3130 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3131 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3132 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003133 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003134 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3135 if (res != OK) {
3136 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3137 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3138 }
3139 }
3140 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003141 // Set the frame number this request would have had, if it
3142 // had been submitted; this frame number will not be reused.
3143 // The requestId and burstId fields were set when the request was
3144 // submitted originally (in convertMetadataListToRequestListLocked)
3145 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003146 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003147 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003148 }
3149 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003150 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003151
3152 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003153 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003154 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003155 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003156 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003157 return OK;
3158}
3159
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003160status_t Camera3Device::RequestThread::flush() {
3161 ATRACE_CALL();
3162 Mutex::Autolock l(mFlushLock);
3163
Emilian Peev08dd2452017-04-06 16:55:14 +01003164 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003165}
3166
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003167void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003168 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003169 Mutex::Autolock l(mPauseLock);
3170 mDoPause = paused;
3171 mDoPauseSignal.signal();
3172}
3173
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003174status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3175 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003176 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003177 Mutex::Autolock l(mLatestRequestMutex);
3178 status_t res;
3179 while (mLatestRequestId != requestId) {
3180 nsecs_t startTime = systemTime();
3181
3182 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3183 if (res != OK) return res;
3184
3185 timeout -= (systemTime() - startTime);
3186 }
3187
3188 return OK;
3189}
3190
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003191void Camera3Device::RequestThread::requestExit() {
3192 // Call parent to set up shutdown
3193 Thread::requestExit();
3194 // The exit from any possible waits
3195 mDoPauseSignal.signal();
3196 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003197
3198 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3199 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003200}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003201
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003202void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003203 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003204 bool surfaceAbandoned = false;
3205 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003206 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003207 {
3208 Mutex::Autolock l(mRequestLock);
3209 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3210 // repeating requests.
3211 for (const auto& request : mRepeatingRequests) {
3212 for (const auto& s : request->mOutputStreams) {
3213 if (s->isAbandoned()) {
3214 surfaceAbandoned = true;
3215 clearRepeatingRequestsLocked(&lastFrameNumber);
3216 break;
3217 }
3218 }
3219 if (surfaceAbandoned) {
3220 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003221 }
3222 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003223 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003224 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003225
3226 if (listener != NULL && surfaceAbandoned) {
3227 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003228 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003229}
3230
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003231bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003232 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003233 status_t res;
3234 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003235 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003236 uint32_t numRequestProcessed = 0;
3237 for (size_t i = 0; i < batchSize; i++) {
3238 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003239 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003240 }
3241
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003242 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3243
3244 bool triggerRemoveFailed = false;
3245 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3246 for (size_t i = 0; i < numRequestProcessed; i++) {
3247 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3248 nextRequest.submitted = true;
3249
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003250 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003251
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003252 if (!triggerRemoveFailed) {
3253 // Remove any previously queued triggers (after unlock)
3254 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3255 if (removeTriggerRes != OK) {
3256 triggerRemoveFailed = true;
3257 triggerFailedRequest = nextRequest;
3258 }
3259 }
3260 }
3261
3262 if (triggerRemoveFailed) {
3263 SET_ERR("RequestThread: Unable to remove triggers "
3264 "(capture request %d, HAL device: %s (%d)",
3265 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3266 cleanUpFailedRequests(/*sendRequestError*/ false);
3267 return false;
3268 }
3269
3270 if (res != OK) {
3271 // Should only get a failure here for malformed requests or device-level
3272 // errors, so consider all errors fatal. Bad metadata failures should
3273 // come through notify.
3274 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3275 mNextRequests[numRequestProcessed].halRequest.frame_number,
3276 strerror(-res), res);
3277 cleanUpFailedRequests(/*sendRequestError*/ false);
3278 return false;
3279 }
3280 return true;
3281}
3282
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003283Camera3Device::RequestThread::ExpectedDurationInfo
3284 Camera3Device::RequestThread::calculateExpectedDurationRange(
3285 const camera_metadata_t *request) {
3286 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003287 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003288 InFlightRequest::kDefaultMaxExpectedDuration,
3289 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003290 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3291 find_camera_metadata_ro_entry(request,
3292 ANDROID_CONTROL_AE_MODE,
3293 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003294 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003295
3296 switch (e.data.u8[0]) {
3297 case ANDROID_CONTROL_AE_MODE_OFF:
3298 find_camera_metadata_ro_entry(request,
3299 ANDROID_SENSOR_EXPOSURE_TIME,
3300 &e);
3301 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003302 expectedDurationInfo.minDuration = e.data.i64[0];
3303 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003304 }
3305 find_camera_metadata_ro_entry(request,
3306 ANDROID_SENSOR_FRAME_DURATION,
3307 &e);
3308 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003309 expectedDurationInfo.minDuration =
3310 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3311 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003312 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003313 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003314 break;
3315 default:
3316 find_camera_metadata_ro_entry(request,
3317 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3318 &e);
3319 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003320 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3321 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003322 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003323 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003324 break;
3325 }
3326
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003327 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003328}
3329
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003330bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3331 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3332 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3333 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3334 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3335 return true;
3336 }
3337
3338 return false;
3339}
3340
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003341void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3342 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003343 camera_capture_request_t& halRequest = nextRequest.halRequest;
3344 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003345 Mutex::Autolock al(mLatestRequestMutex);
3346
Shuzhen Wang83bff122020-11-20 15:51:39 -08003347 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003348 mLatestRequest.acquire(cloned);
3349
3350 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003351 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3352 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3353 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003354 CameraMetadata(cloned));
3355 }
3356
3357 sp<Camera3Device> parent = mParent.promote();
3358 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003359 int32_t inputStreamId = -1;
3360 if (halRequest.input_buffer != nullptr) {
3361 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3362 }
3363
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003364 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003365 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003366 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3367 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003368 }
3369 }
3370
Shuzhen Wang83bff122020-11-20 15:51:39 -08003371 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003372 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003373 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003374 }
3375
Shuzhen Wang83bff122020-11-20 15:51:39 -08003376 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003377}
3378
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003379bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3380 ATRACE_CALL();
3381 bool updatesDetected = false;
3382
Emilian Peev4ec17882019-01-24 17:16:58 -08003383 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003384 for (auto tag : mSessionParamKeys) {
3385 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003386 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003387
3388 if (entry.count > 0) {
3389 bool isDifferent = false;
3390 if (lastEntry.count > 0) {
3391 // Have a last value, compare to see if changed
3392 if (lastEntry.type == entry.type &&
3393 lastEntry.count == entry.count) {
3394 // Same type and count, compare values
3395 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3396 size_t entryBytes = bytesPerValue * lastEntry.count;
3397 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3398 if (cmp != 0) {
3399 isDifferent = true;
3400 }
3401 } else {
3402 // Count or type has changed
3403 isDifferent = true;
3404 }
3405 } else {
3406 // No last entry, so always consider to be different
3407 isDifferent = true;
3408 }
3409
3410 if (isDifferent) {
3411 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003412 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3413 updatesDetected = true;
3414 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003415 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003416 }
3417 } else if (lastEntry.count > 0) {
3418 // Value has been removed
3419 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003420 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003421 updatesDetected = true;
3422 }
3423 }
3424
Emilian Peev4ec17882019-01-24 17:16:58 -08003425 bool reconfigureRequired;
3426 if (updatesDetected) {
3427 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3428 updatedParams);
3429 mLatestSessionParams = updatedParams;
3430 } else {
3431 reconfigureRequired = false;
3432 }
3433
3434 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003435}
3436
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003437bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003438 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003439 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003440 // Any function called from threadLoop() must not hold mInterfaceLock since
3441 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3442 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003443
3444 // Handle paused state.
3445 if (waitIfPaused()) {
3446 return true;
3447 }
3448
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003449 // Wait for the next batch of requests.
3450 waitForNextRequestBatch();
3451 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003452 return true;
3453 }
3454
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003455 // Get the latest request ID, if any
3456 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003457 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003458 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003459 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003460 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003461 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003462 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3463 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003464 }
3465
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003466 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3467 // or a single request from streaming or burst. In either case the first element
3468 // should contain the latest camera settings that we need to check for any session
3469 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003470 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003471 res = OK;
3472
3473 //Input stream buffers are already acquired at this point so an input stream
3474 //will not be able to move to idle state unless we force it.
3475 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3476 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3477 if (res != OK) {
3478 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3479 cleanUpFailedRequests(/*sendRequestError*/ false);
3480 return false;
3481 }
3482 }
3483
3484 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003485 sp<Camera3Device> parent = mParent.promote();
3486 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003487 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3488 if (statusTracker != nullptr) {
3489 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3490 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003491 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003492 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003493 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003494
3495 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3496 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3497 if (res != OK) {
3498 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3499 cleanUpFailedRequests(/*sendRequestError*/ false);
3500 return false;
3501 }
3502 }
3503 }
3504 }
3505
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003506 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003507 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003508 if (res == TIMED_OUT) {
3509 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003510 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003511 // Check if any stream is abandoned.
3512 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003513 return true;
3514 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003515 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003516 return false;
3517 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003518
Zhijun Hecc27e112013-10-03 16:12:43 -07003519 // Inform waitUntilRequestProcessed thread of a new request ID
3520 {
3521 Mutex::Autolock al(mLatestRequestMutex);
3522
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003523 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003524 mLatestRequestSignal.signal();
3525 }
3526
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003527 // Submit a batch of requests to HAL.
3528 // Use flush lock only when submitting multilple requests in a batch.
3529 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3530 // which may take a long time to finish so synchronizing flush() and
3531 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3532 // For now, only synchronize for high speed recording and we should figure something out for
3533 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003534 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003535
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003536 if (useFlushLock) {
3537 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003538 }
3539
Zhijun Hef0645c12016-08-02 00:58:11 -07003540 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003541 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003542
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003543 sp<Camera3Device> parent = mParent.promote();
3544 if (parent != nullptr) {
3545 parent->mRequestBufferSM.onSubmittingRequest();
3546 }
3547
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003548 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003549 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003550 submitRequestSuccess = sendRequestsBatch();
3551
Shuzhen Wang686f6442017-06-20 16:16:04 -07003552 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3553 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003554
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003555 if (useFlushLock) {
3556 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003557 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003558
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003559 // Unset as current request
3560 {
3561 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003562 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003563 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003564 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003565
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003566 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003567}
3568
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003569status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3570 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3571 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3572 ANDROID_SCALER_CROP_REGION_SET};
3573 if (request == nullptr) {
3574 ALOGE("%s request metadata nullptr", __FUNCTION__);
3575 return BAD_VALUE;
3576 }
3577 status_t res = OK;
3578 for (const auto &key : kFwkOnlyRegionKeys) {
3579 if (request->exists(key)) {
3580 res = request->erase(key);
3581 if (res != OK) {
3582 return res;
3583 }
3584 }
3585 }
3586 return OK;
3587}
3588
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003589status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003590 ATRACE_CALL();
3591
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003592 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003593 for (size_t i = 0; i < mNextRequests.size(); i++) {
3594 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003595 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003596 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3597 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003598
3599 // Prepare a request to HAL
3600 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3601
3602 // Insert any queued triggers (before metadata is locked)
3603 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003604 if (res < 0) {
3605 SET_ERR("RequestThread: Unable to insert triggers "
3606 "(capture request %d, HAL device: %s (%d)",
3607 halRequest->frame_number, strerror(-res), res);
3608 return INVALID_OPERATION;
3609 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003610
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003611 int triggerCount = res;
3612 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3613 mPrevTriggers = triggerCount;
3614
Emilian Peeve23f1d92021-09-20 14:56:01 -07003615 // Do not override rotate&crop for stream configurations that include
Austin Borger18b30a72022-10-27 12:20:29 -07003616 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3617 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3618 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003619 overrideAutoRotateAndCrop(captureRequest);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003620 bool autoframingChanged = overrideAutoframing(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003621 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003622
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003623 // If the request is the same as last, or we had triggers now or last time or
3624 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003625 bool newRequest =
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003626 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged ||
3627 autoframingChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003628 // Request settings are all the same within one batch, so only treat the first
3629 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003630 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003631 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003632 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003633 /**
3634 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003635 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003636 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003637 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003638 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003639 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 "(capture request %d, HAL device: %s (%d)",
3641 halRequest->frame_number, strerror(-res), res);
3642 return INVALID_OPERATION;
3643 }
3644
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003645 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003646 sp<Camera3Device> parent = mParent.promote();
3647 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003648 List<PhysicalCameraSettings>::iterator it;
3649 for (it = captureRequest->mSettingsList.begin();
3650 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003651 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3652 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003653 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3654 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3655 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3656 res);
3657 return INVALID_OPERATION;
3658 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003659 continue;
3660 }
3661
3662 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3663 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3664 updateCaptureRequest(&(it->metadata));
3665 if (res != OK) {
3666 SET_ERR("RequestThread: Unable to correct capture requests "
3667 "for scaler crop region and metering regions for request "
3668 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3669 res);
3670 return INVALID_OPERATION;
3671 }
3672 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003673 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3674 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3675 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3676 res);
3677 return INVALID_OPERATION;
3678 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003679 }
3680 }
3681
3682 // Correct metadata regions for distortion correction if enabled
3683 for (it = captureRequest->mSettingsList.begin();
3684 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003685 if (parent->mDistortionMappers.find(it->cameraId) ==
3686 parent->mDistortionMappers.end()) {
3687 continue;
3688 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003689
3690 if (!captureRequest->mDistortionCorrectionUpdated) {
3691 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3692 &(it->metadata));
3693 if (res != OK) {
3694 SET_ERR("RequestThread: Unable to correct capture requests "
3695 "for lens distortion for request %d: %s (%d)",
3696 halRequest->frame_number, strerror(-res), res);
3697 return INVALID_OPERATION;
3698 }
3699 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003700 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003701 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003702
3703 for (it = captureRequest->mSettingsList.begin();
3704 it != captureRequest->mSettingsList.end(); it++) {
3705 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3706 parent->mZoomRatioMappers.end()) {
3707 continue;
3708 }
3709
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003710 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003711 cameraIdsWithZoom.insert(it->cameraId);
3712 }
3713
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003714 if (!captureRequest->mZoomRatioUpdated) {
3715 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3716 &(it->metadata));
3717 if (res != OK) {
3718 SET_ERR("RequestThread: Unable to correct capture requests "
3719 "for zoom ratio for request %d: %s (%d)",
3720 halRequest->frame_number, strerror(-res), res);
3721 return INVALID_OPERATION;
3722 }
3723 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003724 }
3725 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003726 if (captureRequest->mRotateAndCropAuto &&
3727 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003728 for (it = captureRequest->mSettingsList.begin();
3729 it != captureRequest->mSettingsList.end(); it++) {
3730 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3731 if (mapper != parent->mRotateAndCropMappers.end()) {
3732 res = mapper->second.updateCaptureRequest(&(it->metadata));
3733 if (res != OK) {
3734 SET_ERR("RequestThread: Unable to correct capture requests "
3735 "for rotate-and-crop for request %d: %s (%d)",
3736 halRequest->frame_number, strerror(-res), res);
3737 return INVALID_OPERATION;
3738 }
3739 }
3740 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003741 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003742 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003743 }
3744 }
3745
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003746 /**
3747 * The request should be presorted so accesses in HAL
3748 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3749 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003750 captureRequest->mSettingsList.begin()->metadata.sort();
3751 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003752 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003753 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003754 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3755
3756 IF_ALOGV() {
3757 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3758 find_camera_metadata_ro_entry(
3759 halRequest->settings,
3760 ANDROID_CONTROL_AF_TRIGGER,
3761 &e
3762 );
3763 if (e.count > 0) {
3764 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3765 __FUNCTION__,
3766 halRequest->frame_number,
3767 e.data.u8[0]);
3768 }
3769 }
3770 } else {
3771 // leave request.settings NULL to indicate 'reuse latest given'
3772 ALOGVV("%s: Request settings are REUSED",
3773 __FUNCTION__);
3774 }
3775
Emilian Peevaebbe412018-01-15 13:53:24 +00003776 if (captureRequest->mSettingsList.size() > 1) {
3777 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3778 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003779 if (newRequest) {
3780 halRequest->physcam_settings =
3781 new const camera_metadata* [halRequest->num_physcam_settings];
3782 } else {
3783 halRequest->physcam_settings = nullptr;
3784 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003785 auto it = ++captureRequest->mSettingsList.begin();
3786 size_t i = 0;
3787 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3788 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003789 if (newRequest) {
3790 it->metadata.sort();
3791 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3792 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003793 }
3794 }
3795
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003796 uint32_t totalNumBuffers = 0;
3797
3798 // Fill in buffers
3799 if (captureRequest->mInputStream != NULL) {
3800 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003801
3802 halRequest->input_width = captureRequest->mInputBufferSize.width;
3803 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003804 totalNumBuffers += 1;
3805 } else {
3806 halRequest->input_buffer = NULL;
3807 }
3808
Emilian Peevf4816702020-04-03 15:44:51 -07003809 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003810 captureRequest->mOutputStreams.size());
3811 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003812 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003813
3814 sp<Camera3Device> parent = mParent.promote();
3815 if (parent == NULL) {
3816 // Should not happen, and nowhere to send errors to, so just log it
3817 CLOGE("RequestThread: Parent is gone");
3818 return INVALID_OPERATION;
3819 }
3820 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3821
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003822 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003823 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003824 sp<Camera3OutputStreamInterface> outputStream =
3825 captureRequest->mOutputStreams.editItemAt(j);
3826 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003827
3828 // Prepare video buffers for high speed recording on the first video request.
3829 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3830 // Only try to prepare video stream on the first video request.
3831 mPrepareVideoStream = false;
3832
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003833 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3834 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003835 while (res == NOT_ENOUGH_DATA) {
3836 res = outputStream->prepareNextBuffer();
3837 }
3838 if (res != OK) {
3839 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3840 __FUNCTION__, strerror(-res), res);
3841 outputStream->cancelPrepare();
3842 }
3843 }
3844
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003845 std::vector<size_t> uniqueSurfaceIds;
3846 res = outputStream->getUniqueSurfaceIds(
3847 captureRequest->mOutputSurfaces[streamId],
3848 &uniqueSurfaceIds);
3849 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3850 if (res != OK && res != INVALID_OPERATION) {
3851 ALOGE("%s: failed to query stream %d unique surface IDs",
3852 __FUNCTION__, streamId);
3853 return res;
3854 }
3855 if (res == OK) {
3856 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3857 }
3858
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003859 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003860 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003861 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003862 return TIMED_OUT;
3863 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003864 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003865 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003866 buffer.stream = outputStream->asHalStream();
3867 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003868 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003869 buffer.acquire_fence = -1;
3870 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003871 // Mark the output stream as unpreparable to block clients from calling
3872 // 'prepare' after this request reaches CameraHal and before the respective
3873 // buffers are requested.
3874 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003875 } else {
3876 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3877 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003878 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003879 if (res != OK) {
3880 // Can't get output buffer from gralloc queue - this could be due to
3881 // abandoned queue or other consumer misbehavior, so not a fatal
3882 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003883 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003884 " %s (%d)", strerror(-res), res);
3885
3886 return TIMED_OUT;
3887 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003888 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003889
3890 {
3891 sp<Camera3Device> parent = mParent.promote();
3892 if (parent != nullptr) {
3893 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3894 for (const auto& settings : captureRequest->mSettingsList) {
3895 if ((streamCameraId.isEmpty() &&
3896 parent->getId() == settings.cameraId.c_str()) ||
3897 streamCameraId == settings.cameraId.c_str()) {
3898 outputStream->fireBufferRequestForFrameNumber(
3899 captureRequest->mResultExtras.frameNumber,
3900 settings.metadata);
3901 }
3902 }
3903 }
3904 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003905
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003906 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003907 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3908 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3909 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3910 } else if (!physicalCameraId.isEmpty()) {
3911 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003912 }
3913 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003914 }
3915 totalNumBuffers += halRequest->num_output_buffers;
3916
3917 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003918 // If this request list is for constrained high speed recording (not
3919 // preview), and the current request is not the last one in the batch,
3920 // do not send callback to the app.
3921 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003922 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003923 hasCallback = false;
3924 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003925 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003926 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003927 const camera_metadata_t* settings = halRequest->settings;
3928 bool shouldUnlockSettings = false;
3929 if (settings == nullptr) {
3930 shouldUnlockSettings = true;
3931 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3932 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003933 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3934 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003935 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003936 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3937 isStillCapture = true;
3938 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3939 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003940
Emilian Peevaf8416e2021-02-04 17:52:43 -08003941 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003942 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003943 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3944 isZslCapture = true;
3945 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003946 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003947 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003948 res = parent->registerInFlight(halRequest->frame_number,
3949 totalNumBuffers, captureRequest->mResultExtras,
3950 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003951 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003952 expectedDurationInfo.minDuration,
3953 expectedDurationInfo.maxDuration,
3954 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003955 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003956 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
3957 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003958 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003959 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003960 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3961 ", burstId = %" PRId32 ".",
3962 __FUNCTION__,
3963 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3964 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003965
3966 if (shouldUnlockSettings) {
3967 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3968 }
3969
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003970 if (res != OK) {
3971 SET_ERR("RequestThread: Unable to register new in-flight request:"
3972 " %s (%d)", strerror(-res), res);
3973 return INVALID_OPERATION;
3974 }
3975 }
3976
3977 return OK;
3978}
3979
Igor Murashkin1e479c02013-09-06 16:55:14 -07003980CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003981 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003982 Mutex::Autolock al(mLatestRequestMutex);
3983
3984 ALOGV("RequestThread::%s", __FUNCTION__);
3985
3986 return mLatestRequest;
3987}
3988
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003989bool Camera3Device::RequestThread::isStreamPending(
3990 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003991 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003992 Mutex::Autolock l(mRequestLock);
3993
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003994 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003995 if (!nextRequest.submitted) {
3996 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3997 if (stream == s) return true;
3998 }
3999 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004000 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004001 }
4002
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004003 for (const auto& request : mRequestQueue) {
4004 for (const auto& s : request->mOutputStreams) {
4005 if (stream == s) return true;
4006 }
4007 if (stream == request->mInputStream) return true;
4008 }
4009
4010 for (const auto& request : mRepeatingRequests) {
4011 for (const auto& s : request->mOutputStreams) {
4012 if (stream == s) return true;
4013 }
4014 if (stream == request->mInputStream) return true;
4015 }
4016
4017 return false;
4018}
Jianing Weicb0652e2014-03-12 18:29:36 -07004019
Emilian Peev40ead602017-09-26 15:46:36 +01004020bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4021 ATRACE_CALL();
4022 Mutex::Autolock l(mRequestLock);
4023
4024 for (const auto& nextRequest : mNextRequests) {
4025 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4026 if (s.first == streamId) {
4027 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4028 if (it != s.second.end()) {
4029 return true;
4030 }
4031 }
4032 }
4033 }
4034
4035 for (const auto& request : mRequestQueue) {
4036 for (const auto& s : request->mOutputSurfaces) {
4037 if (s.first == streamId) {
4038 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4039 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004040 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004041 }
4042 }
4043 }
4044 }
4045
4046 for (const auto& request : mRepeatingRequests) {
4047 for (const auto& s : request->mOutputSurfaces) {
4048 if (s.first == streamId) {
4049 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4050 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004051 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004052 }
4053 }
4054 }
4055 }
4056
4057 return false;
4058}
4059
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004060void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4061 if (!mUseHalBufManager) {
4062 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4063 return;
4064 }
4065
4066 Mutex::Autolock pl(mPauseLock);
4067 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004068 mInterface->signalPipelineDrain(streamIds);
4069 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004070 }
4071 // If request thread is still busy, wait until paused then notify HAL
4072 mNotifyPipelineDrain = true;
4073 mStreamIdsToBeDrained = streamIds;
4074}
4075
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004076void Camera3Device::RequestThread::resetPipelineDrain() {
4077 Mutex::Autolock pl(mPauseLock);
4078 mNotifyPipelineDrain = false;
4079 mStreamIdsToBeDrained.clear();
4080}
4081
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004082void Camera3Device::RequestThread::clearPreviousRequest() {
4083 Mutex::Autolock l(mRequestLock);
4084 mPrevRequest.clear();
4085}
4086
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004087status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4088 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4089 ATRACE_CALL();
4090 Mutex::Autolock l(mTriggerMutex);
4091 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4092 return BAD_VALUE;
4093 }
4094 mRotateAndCropOverride = rotateAndCropValue;
4095 return OK;
4096}
4097
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004098status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4099 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4100 ATRACE_CALL();
4101 Mutex::Autolock l(mTriggerMutex);
4102 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
4103 return BAD_VALUE;
4104 }
4105 mAutoframingOverride = autoframingValue;
4106 return OK;
4107}
4108
Emilian Peeve23f1d92021-09-20 14:56:01 -07004109status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4110 ATRACE_CALL();
4111 Mutex::Autolock l(mTriggerMutex);
4112 mComposerOutput = composerSurfacePresent;
4113 return OK;
4114}
4115
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004116status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004117 ATRACE_CALL();
4118 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004119 if (muteMode != mCameraMute) {
4120 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004121 mCameraMuteChanged = true;
4122 }
4123 return OK;
4124}
4125
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004126nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004127 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004128 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004129 return mExpectedInflightDuration > kMinInflightDuration ?
4130 mExpectedInflightDuration : kMinInflightDuration;
4131}
4132
Emilian Peevaebbe412018-01-15 13:53:24 +00004133void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004134 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004135 if ((request == nullptr) || (halRequest == nullptr)) {
4136 ALOGE("%s: Invalid request!", __FUNCTION__);
4137 return;
4138 }
4139
4140 if (halRequest->num_physcam_settings > 0) {
4141 if (halRequest->physcam_id != nullptr) {
4142 delete [] halRequest->physcam_id;
4143 halRequest->physcam_id = nullptr;
4144 }
4145 if (halRequest->physcam_settings != nullptr) {
4146 auto it = ++(request->mSettingsList.begin());
4147 size_t i = 0;
4148 for (; it != request->mSettingsList.end(); it++, i++) {
4149 it->metadata.unlock(halRequest->physcam_settings[i]);
4150 }
4151 delete [] halRequest->physcam_settings;
4152 halRequest->physcam_settings = nullptr;
4153 }
4154 }
4155}
4156
Ravneetaeb20dc2022-03-30 05:33:03 +00004157status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4158 Mutex::Autolock il(mInterfaceLock);
4159 Mutex::Autolock l(mLock);
4160
4161 if (mCameraServiceWatchdog != NULL) {
4162 mCameraServiceWatchdog->setEnabled(enabled);
4163 }
4164
4165 return OK;
4166}
4167
Shuzhen Wang16610a62022-12-15 22:38:07 -08004168void Camera3Device::setStreamUseCaseOverrides(
4169 const std::vector<int64_t>& useCaseOverrides) {
4170 Mutex::Autolock il(mInterfaceLock);
4171 Mutex::Autolock l(mLock);
4172 mStreamUseCaseOverrides = useCaseOverrides;
4173}
4174
4175void Camera3Device::clearStreamUseCaseOverrides() {
4176 Mutex::Autolock il(mInterfaceLock);
4177 Mutex::Autolock l(mLock);
4178 mStreamUseCaseOverrides.clear();
4179}
4180
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004181void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4182 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004183 return;
4184 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004185
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004186 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004187 // Skip the ones that have been submitted successfully.
4188 if (nextRequest.submitted) {
4189 continue;
4190 }
4191
4192 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004193 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4194 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004195
4196 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004197 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004198 }
4199
Emilian Peevaebbe412018-01-15 13:53:24 +00004200 cleanupPhysicalSettings(captureRequest, halRequest);
4201
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004202 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004203 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004204 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4205 }
4206
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004207 // No output buffer can be returned when using HAL buffer manager
4208 if (!mUseHalBufManager) {
4209 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4210 //Buffers that failed processing could still have
4211 //valid acquire fence.
4212 int acquireFence = (*outputBuffers)[i].acquire_fence;
4213 if (0 <= acquireFence) {
4214 close(acquireFence);
4215 outputBuffers->editItemAt(i).acquire_fence = -1;
4216 }
Emilian Peevf4816702020-04-03 15:44:51 -07004217 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004218 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4219 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004220 /*timestampIncreasing*/true, std::vector<size_t> (),
4221 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004222 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004223 }
4224
4225 if (sendRequestError) {
4226 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004227 sp<NotificationListener> listener = mListener.promote();
4228 if (listener != NULL) {
4229 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004230 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004231 captureRequest->mResultExtras);
4232 }
4233 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004234
4235 // Remove yet-to-be submitted inflight request from inflightMap
4236 {
4237 sp<Camera3Device> parent = mParent.promote();
4238 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004239 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004240 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4241 if (idx >= 0) {
4242 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4243 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4244 parent->removeInFlightMapEntryLocked(idx);
4245 }
4246 }
4247 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004249
4250 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004251 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004252}
4253
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004254void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004255 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 // Optimized a bit for the simple steady-state case (single repeating
4257 // request), to avoid putting that request in the queue temporarily.
4258 Mutex::Autolock l(mRequestLock);
4259
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004260 assert(mNextRequests.empty());
4261
4262 NextRequest nextRequest;
4263 nextRequest.captureRequest = waitForNextRequestLocked();
4264 if (nextRequest.captureRequest == nullptr) {
4265 return;
4266 }
4267
Emilian Peevf4816702020-04-03 15:44:51 -07004268 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004269 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004270 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271
4272 // Wait for additional requests
4273 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4274
4275 for (size_t i = 1; i < batchSize; i++) {
4276 NextRequest additionalRequest;
4277 additionalRequest.captureRequest = waitForNextRequestLocked();
4278 if (additionalRequest.captureRequest == nullptr) {
4279 break;
4280 }
4281
Emilian Peevf4816702020-04-03 15:44:51 -07004282 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004283 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004284 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004285 }
4286
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004287 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004288 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004289 mNextRequests.size(), batchSize);
4290 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004291 }
4292
4293 return;
4294}
4295
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004296void Camera3Device::RequestThread::setRequestClearing() {
4297 Mutex::Autolock l(mRequestLock);
4298 mRequestClearing = true;
4299}
4300
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004301sp<Camera3Device::CaptureRequest>
4302 Camera3Device::RequestThread::waitForNextRequestLocked() {
4303 status_t res;
4304 sp<CaptureRequest> nextRequest;
4305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004306 while (mRequestQueue.empty()) {
4307 if (!mRepeatingRequests.empty()) {
4308 // Always atomically enqueue all requests in a repeating request
4309 // list. Guarantees a complete in-sequence set of captures to
4310 // application.
4311 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004312 if (mFirstRepeating) {
4313 mFirstRepeating = false;
4314 } else {
4315 for (auto& request : requests) {
4316 // For repeating requests, override timestamp request using
4317 // the time a request is inserted into the request queue,
4318 // because the original repeating request will have an old
4319 // fixed timestamp.
4320 request->mRequestTimeNs = systemTime();
4321 }
4322 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 RequestList::const_iterator firstRequest =
4324 requests.begin();
4325 nextRequest = *firstRequest;
4326 mRequestQueue.insert(mRequestQueue.end(),
4327 ++firstRequest,
4328 requests.end());
4329 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004330
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004331 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004332
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 break;
4334 }
4335
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004336 if (!mRequestClearing) {
4337 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4338 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004339
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004340 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4341 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 Mutex::Autolock pl(mPauseLock);
4343 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004344 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004346 if (mNotifyPipelineDrain) {
4347 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4348 mNotifyPipelineDrain = false;
4349 mStreamIdsToBeDrained.clear();
4350 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004351 // Let the tracker know
4352 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4353 if (statusTracker != 0) {
4354 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4355 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004356 sp<Camera3Device> parent = mParent.promote();
4357 if (parent != nullptr) {
4358 parent->mRequestBufferSM.onRequestThreadPaused();
4359 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004360 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004361 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004362 // Stop waiting for now and let thread management happen
4363 return NULL;
4364 }
4365 }
4366
4367 if (nextRequest == NULL) {
4368 // Don't have a repeating request already in hand, so queue
4369 // must have an entry now.
4370 RequestList::iterator firstRequest =
4371 mRequestQueue.begin();
4372 nextRequest = *firstRequest;
4373 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004374 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4375 sp<NotificationListener> listener = mListener.promote();
4376 if (listener != NULL) {
4377 listener->notifyRequestQueueEmpty();
4378 }
4379 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004380 }
4381
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004382 // In case we've been unpaused by setPaused clearing mDoPause, need to
4383 // update internal pause state (capture/setRepeatingRequest unpause
4384 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004385 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004386 if (mPaused) {
4387 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4388 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4389 if (statusTracker != 0) {
4390 statusTracker->markComponentActive(mStatusId);
4391 }
4392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004393 mPaused = false;
4394
4395 // Check if we've reconfigured since last time, and reset the preview
4396 // request if so. Can't use 'NULL request == repeat' across configure calls.
4397 if (mReconfigured) {
4398 mPrevRequest.clear();
4399 mReconfigured = false;
4400 }
4401
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004402 if (nextRequest != NULL) {
4403 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004404 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4405 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004406
4407 // Since RequestThread::clear() removes buffers from the input stream,
4408 // get the right buffer here before unlocking mRequestLock
4409 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004410 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4411 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004412 if (res != OK) {
4413 // Can't get input buffer from gralloc queue - this could be due to
4414 // disconnected queue or other producer misbehavior, so not a fatal
4415 // error
4416 ALOGE("%s: Can't get input buffer, skipping request:"
4417 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004418
4419 sp<NotificationListener> listener = mListener.promote();
4420 if (listener != NULL) {
4421 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004422 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004423 nextRequest->mResultExtras);
4424 }
4425 return NULL;
4426 }
4427 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004428 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004429
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004430 return nextRequest;
4431}
4432
4433bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004434 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004435 status_t res;
4436 Mutex::Autolock l(mPauseLock);
4437 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004438 if (mPaused == false) {
4439 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004440 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004441 if (mNotifyPipelineDrain) {
4442 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4443 mNotifyPipelineDrain = false;
4444 mStreamIdsToBeDrained.clear();
4445 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004446 // Let the tracker know
4447 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4448 if (statusTracker != 0) {
4449 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4450 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004451 sp<Camera3Device> parent = mParent.promote();
4452 if (parent != nullptr) {
4453 parent->mRequestBufferSM.onRequestThreadPaused();
4454 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004455 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004458 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004459 return true;
4460 }
4461 }
4462 // We don't set mPaused to false here, because waitForNextRequest needs
4463 // to further manage the paused state in case of starvation.
4464 return false;
4465}
4466
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004467void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004468 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004469 // With work to do, mark thread as unpaused.
4470 // If paused by request (setPaused), don't resume, to avoid
4471 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004472 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004473 Mutex::Autolock p(mPauseLock);
4474 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004475 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4476 if (mPaused) {
4477 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4478 if (statusTracker != 0) {
4479 statusTracker->markComponentActive(mStatusId);
4480 }
4481 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004482 mPaused = false;
4483 }
4484}
4485
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004486void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4487 sp<Camera3Device> parent = mParent.promote();
4488 if (parent != NULL) {
4489 va_list args;
4490 va_start(args, fmt);
4491
4492 parent->setErrorStateV(fmt, args);
4493
4494 va_end(args);
4495 }
4496}
4497
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004498status_t Camera3Device::RequestThread::insertTriggers(
4499 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004500 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004501 Mutex::Autolock al(mTriggerMutex);
4502
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004503 sp<Camera3Device> parent = mParent.promote();
4504 if (parent == NULL) {
4505 CLOGE("RequestThread: Parent is gone");
4506 return DEAD_OBJECT;
4507 }
4508
Emilian Peevaebbe412018-01-15 13:53:24 +00004509 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004510 size_t count = mTriggerMap.size();
4511
4512 for (size_t i = 0; i < count; ++i) {
4513 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004514 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004515
4516 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4517 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4518 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004519 if (isAeTrigger) {
4520 request->mResultExtras.precaptureTriggerId = triggerId;
4521 mCurrentPreCaptureTriggerId = triggerId;
4522 } else {
4523 request->mResultExtras.afTriggerId = triggerId;
4524 mCurrentAfTriggerId = triggerId;
4525 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004526 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004527 }
4528
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004529 camera_metadata_entry entry = metadata.find(tag);
4530
4531 if (entry.count > 0) {
4532 /**
4533 * Already has an entry for this trigger in the request.
4534 * Rewrite it with our requested trigger value.
4535 */
4536 RequestTrigger oldTrigger = trigger;
4537
4538 oldTrigger.entryValue = entry.data.u8[0];
4539
4540 mTriggerReplacedMap.add(tag, oldTrigger);
4541 } else {
4542 /**
4543 * More typical, no trigger entry, so we just add it
4544 */
4545 mTriggerRemovedMap.add(tag, trigger);
4546 }
4547
4548 status_t res;
4549
4550 switch (trigger.getTagType()) {
4551 case TYPE_BYTE: {
4552 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4553 res = metadata.update(tag,
4554 &entryValue,
4555 /*count*/1);
4556 break;
4557 }
4558 case TYPE_INT32:
4559 res = metadata.update(tag,
4560 &trigger.entryValue,
4561 /*count*/1);
4562 break;
4563 default:
4564 ALOGE("%s: Type not supported: 0x%x",
4565 __FUNCTION__,
4566 trigger.getTagType());
4567 return INVALID_OPERATION;
4568 }
4569
4570 if (res != OK) {
4571 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4572 ", value %d", __FUNCTION__, trigger.getTagName(),
4573 trigger.entryValue);
4574 return res;
4575 }
4576
4577 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4578 trigger.getTagName(),
4579 trigger.entryValue);
4580 }
4581
4582 mTriggerMap.clear();
4583
4584 return count;
4585}
4586
4587status_t Camera3Device::RequestThread::removeTriggers(
4588 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004589 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004590 Mutex::Autolock al(mTriggerMutex);
4591
Emilian Peevaebbe412018-01-15 13:53:24 +00004592 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004593
4594 /**
4595 * Replace all old entries with their old values.
4596 */
4597 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4598 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4599
4600 status_t res;
4601
4602 uint32_t tag = trigger.metadataTag;
4603 switch (trigger.getTagType()) {
4604 case TYPE_BYTE: {
4605 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4606 res = metadata.update(tag,
4607 &entryValue,
4608 /*count*/1);
4609 break;
4610 }
4611 case TYPE_INT32:
4612 res = metadata.update(tag,
4613 &trigger.entryValue,
4614 /*count*/1);
4615 break;
4616 default:
4617 ALOGE("%s: Type not supported: 0x%x",
4618 __FUNCTION__,
4619 trigger.getTagType());
4620 return INVALID_OPERATION;
4621 }
4622
4623 if (res != OK) {
4624 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4625 ", trigger value %d", __FUNCTION__,
4626 trigger.getTagName(), trigger.entryValue);
4627 return res;
4628 }
4629 }
4630 mTriggerReplacedMap.clear();
4631
4632 /**
4633 * Remove all new entries.
4634 */
4635 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4636 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4637 status_t res = metadata.erase(trigger.metadataTag);
4638
4639 if (res != OK) {
4640 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4641 ", trigger value %d", __FUNCTION__,
4642 trigger.getTagName(), trigger.entryValue);
4643 return res;
4644 }
4645 }
4646 mTriggerRemovedMap.clear();
4647
4648 return OK;
4649}
4650
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004651status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004652 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004653 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004654 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004655 status_t res;
4656
Emilian Peevaebbe412018-01-15 13:53:24 +00004657 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004658
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004659 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004660 // exists
4661 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4662 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4663 if (afTrigger.count > 0 &&
4664 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4665 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004666 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004667 if (res != OK) return res;
4668 }
4669
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004670 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004671 // if none already exists
4672 camera_metadata_entry pcTrigger =
4673 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4674 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4675 if (pcTrigger.count > 0 &&
4676 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4677 pcId.count == 0) {
4678 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004679 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004680 if (res != OK) return res;
4681 }
4682
4683 return OK;
4684}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004685
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004686bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4687 const sp<CaptureRequest> &request) {
4688 ATRACE_CALL();
4689
Austin Borger18b30a72022-10-27 12:20:29 -07004690 if (mOverrideToPortrait) {
4691 Mutex::Autolock l(mTriggerMutex);
4692 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4693 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4694 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4695 &rotateAndCrop_u8, 1);
4696 return true;
4697 }
4698
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004699 if (request->mRotateAndCropAuto) {
4700 Mutex::Autolock l(mTriggerMutex);
4701 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4702
4703 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4704 if (rotateAndCropEntry.count > 0) {
4705 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4706 return false;
4707 } else {
4708 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4709 return true;
4710 }
4711 } else {
4712 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4713 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4714 &rotateAndCrop_u8, 1);
4715 return true;
4716 }
4717 }
4718 return false;
4719}
4720
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004721bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4722 ATRACE_CALL();
4723
4724 if (request->mAutoframingAuto) {
4725 Mutex::Autolock l(mTriggerMutex);
4726 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4727
4728 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4729 if (autoframingEntry.count > 0) {
4730 if (autoframingEntry.data.u8[0] == mAutoframingOverride) {
4731 return false;
4732 } else {
4733 autoframingEntry.data.u8[0] = mAutoframingOverride;
4734 return true;
4735 }
4736 } else {
4737 uint8_t autoframing_u8 = mAutoframingOverride;
4738 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4739 &autoframing_u8, 1);
4740 return true;
4741 }
4742 }
4743 return false;
4744}
4745
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004746bool Camera3Device::RequestThread::overrideTestPattern(
4747 const sp<CaptureRequest> &request) {
4748 ATRACE_CALL();
4749
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004750 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004751
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004752 Mutex::Autolock l(mTriggerMutex);
4753
4754 bool changed = false;
4755
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004756 // For a multi-camera, the physical cameras support the same set of
4757 // test pattern modes as the logical camera.
4758 for (auto& settings : request->mSettingsList) {
4759 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004760
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004761 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4762 int32_t testPatternData[4] = {
4763 settings.mOriginalTestPatternData[0],
4764 settings.mOriginalTestPatternData[1],
4765 settings.mOriginalTestPatternData[2],
4766 settings.mOriginalTestPatternData[3]
4767 };
4768 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4769 testPatternMode = mCameraMute;
4770 testPatternData[0] = 0;
4771 testPatternData[1] = 0;
4772 testPatternData[2] = 0;
4773 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004774 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004775
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004776 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4777 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4778 if (testPatternEntry.count > 0) {
4779 if (testPatternEntry.data.i32[0] != testPatternMode) {
4780 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004781 changed = true;
4782 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004783 } else if (supportTestPatternModeKey) {
4784 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4785 &testPatternMode, 1);
4786 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004787 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004788
4789 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4790 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4791 if (testPatternColor.count >= 4) {
4792 for (size_t i = 0; i < 4; i++) {
4793 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4794 testPatternColor.data.i32[i] = testPatternData[i];
4795 changed = true;
4796 }
4797 }
4798 } else if (supportTestPatternDataKey) {
4799 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4800 testPatternData, 4);
4801 changed = true;
4802 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004803 }
4804
4805 return changed;
4806}
4807
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004808status_t Camera3Device::RequestThread::setHalInterface(
4809 sp<HalInterface> newHalInterface) {
4810 if (newHalInterface.get() == nullptr) {
4811 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4812 return DEAD_OBJECT;
4813 }
4814
4815 mInterface = newHalInterface;
4816
4817 return OK;
4818}
4819
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004820/**
4821 * PreparerThread inner class methods
4822 */
4823
4824Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004825 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004826 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004827}
4828
4829Camera3Device::PreparerThread::~PreparerThread() {
4830 Thread::requestExitAndWait();
4831 if (mCurrentStream != nullptr) {
4832 mCurrentStream->cancelPrepare();
4833 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4834 mCurrentStream.clear();
4835 }
4836 clear();
4837}
4838
Ruben Brunkc78ac262015-08-13 17:58:46 -07004839status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004840 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004841 status_t res;
4842
4843 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004844 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004845
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004846 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004847 if (res == OK) {
4848 // No preparation needed, fire listener right off
4849 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004850 if (listener != NULL) {
4851 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004852 }
4853 return OK;
4854 } else if (res != NOT_ENOUGH_DATA) {
4855 return res;
4856 }
4857
4858 // Need to prepare, start up thread if necessary
4859 if (!mActive) {
4860 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4861 // isn't running
4862 Thread::requestExitAndWait();
4863 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4864 if (res != OK) {
4865 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004866 if (listener != NULL) {
4867 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004868 }
4869 return res;
4870 }
4871 mCancelNow = false;
4872 mActive = true;
4873 ALOGV("%s: Preparer stream started", __FUNCTION__);
4874 }
4875
4876 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004877 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004878 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4879
4880 return OK;
4881}
4882
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004883void Camera3Device::PreparerThread::pause() {
4884 ATRACE_CALL();
4885
4886 Mutex::Autolock l(mLock);
4887
4888 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4889 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4890 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4891 int currentMaxCount = mCurrentMaxCount;
4892 mPendingStreams.clear();
4893 mCancelNow = true;
4894 while (mActive) {
4895 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4896 if (res == TIMED_OUT) {
4897 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4898 return;
4899 } else if (res != OK) {
4900 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4901 return;
4902 }
4903 }
4904
4905 //Check whether the prepare thread was able to complete the current
4906 //stream. In case work is still pending emplace it along with the rest
4907 //of the streams in the pending list.
4908 if (currentStream != nullptr) {
4909 if (!mCurrentPrepareComplete) {
4910 pendingStreams.emplace(currentMaxCount, currentStream);
4911 }
4912 }
4913
4914 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4915 for (const auto& it : mPendingStreams) {
4916 it.second->cancelPrepare();
4917 }
4918}
4919
4920status_t Camera3Device::PreparerThread::resume() {
4921 ATRACE_CALL();
4922 status_t res;
4923
4924 Mutex::Autolock l(mLock);
4925 sp<NotificationListener> listener = mListener.promote();
4926
4927 if (mActive) {
4928 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4929 return NO_INIT;
4930 }
4931
4932 auto it = mPendingStreams.begin();
4933 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004934 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004935 if (res == OK) {
4936 if (listener != NULL) {
4937 listener->notifyPrepared(it->second->getId());
4938 }
4939 it = mPendingStreams.erase(it);
4940 } else if (res != NOT_ENOUGH_DATA) {
4941 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4942 res, strerror(-res));
4943 it = mPendingStreams.erase(it);
4944 } else {
4945 it++;
4946 }
4947 }
4948
4949 if (mPendingStreams.empty()) {
4950 return OK;
4951 }
4952
4953 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4954 if (res != OK) {
4955 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4956 __FUNCTION__, res, strerror(-res));
4957 return res;
4958 }
4959 mCancelNow = false;
4960 mActive = true;
4961 ALOGV("%s: Preparer stream started", __FUNCTION__);
4962
4963 return OK;
4964}
4965
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004966status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004967 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004968 Mutex::Autolock l(mLock);
4969
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004970 for (const auto& it : mPendingStreams) {
4971 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004972 }
4973 mPendingStreams.clear();
4974 mCancelNow = true;
4975
4976 return OK;
4977}
4978
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004979void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004980 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004981 Mutex::Autolock l(mLock);
4982 mListener = listener;
4983}
4984
4985bool Camera3Device::PreparerThread::threadLoop() {
4986 status_t res;
4987 {
4988 Mutex::Autolock l(mLock);
4989 if (mCurrentStream == nullptr) {
4990 // End thread if done with work
4991 if (mPendingStreams.empty()) {
4992 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4993 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4994 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4995 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004996 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004997 return false;
4998 }
4999
5000 // Get next stream to prepare
5001 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005002 mCurrentStream = it->second;
5003 mCurrentMaxCount = it->first;
5004 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005005 mPendingStreams.erase(it);
5006 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5007 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5008 } else if (mCancelNow) {
5009 mCurrentStream->cancelPrepare();
5010 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5011 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5012 mCurrentStream.clear();
5013 mCancelNow = false;
5014 return true;
5015 }
5016 }
5017
5018 res = mCurrentStream->prepareNextBuffer();
5019 if (res == NOT_ENOUGH_DATA) return true;
5020 if (res != OK) {
5021 // Something bad happened; try to recover by cancelling prepare and
5022 // signalling listener anyway
5023 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5024 mCurrentStream->getId(), res, strerror(-res));
5025 mCurrentStream->cancelPrepare();
5026 }
5027
5028 // This stream has finished, notify listener
5029 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005030 sp<NotificationListener> listener = mListener.promote();
5031 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005032 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5033 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005034 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005035 }
5036
5037 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5038 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005039 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005040
5041 return true;
5042}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005043
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005044status_t Camera3Device::RequestBufferStateMachine::initialize(
5045 sp<camera3::StatusTracker> statusTracker) {
5046 if (statusTracker == nullptr) {
5047 ALOGE("%s: statusTracker is null", __FUNCTION__);
5048 return BAD_VALUE;
5049 }
5050
5051 std::lock_guard<std::mutex> lock(mLock);
5052 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005053 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005054 return OK;
5055}
5056
5057bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5058 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005059 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005060 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005061 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005062 return true;
5063 }
5064 return false;
5065}
5066
5067void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5068 std::lock_guard<std::mutex> lock(mLock);
5069 if (!mRequestBufferOngoing) {
5070 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5071 return;
5072 }
5073 mRequestBufferOngoing = false;
5074 if (mStatus == RB_STATUS_PENDING_STOP) {
5075 checkSwitchToStopLocked();
5076 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005077 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005078}
5079
5080void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5081 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005082 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005083 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005084 return;
5085}
5086
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005087void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005088 std::lock_guard<std::mutex> lock(mLock);
5089 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005090 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5091 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005092 mInflightMapEmpty = false;
5093 if (mStatus == RB_STATUS_STOPPED) {
5094 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005095 }
5096 return;
5097}
5098
5099void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5100 std::lock_guard<std::mutex> lock(mLock);
5101 mRequestThreadPaused = true;
5102 if (mStatus == RB_STATUS_PENDING_STOP) {
5103 checkSwitchToStopLocked();
5104 }
5105 return;
5106}
5107
5108void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5109 std::lock_guard<std::mutex> lock(mLock);
5110 mInflightMapEmpty = true;
5111 if (mStatus == RB_STATUS_PENDING_STOP) {
5112 checkSwitchToStopLocked();
5113 }
5114 return;
5115}
5116
5117void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5118 std::lock_guard<std::mutex> lock(mLock);
5119 if (!checkSwitchToStopLocked()) {
5120 mStatus = RB_STATUS_PENDING_STOP;
5121 }
5122 return;
5123}
5124
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005125bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5126 std::lock_guard<std::mutex> lock(mLock);
5127 if (mRequestBufferOngoing) {
5128 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5129 __FUNCTION__);
5130 return false;
5131 }
5132 mSwitchedToOffline = true;
5133 mInflightMapEmpty = true;
5134 mRequestThreadPaused = true;
5135 mStatus = RB_STATUS_STOPPED;
5136 return true;
5137}
5138
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005139void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5140 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5141 if (statusTracker != nullptr) {
5142 if (active) {
5143 statusTracker->markComponentActive(mRequestBufferStatusId);
5144 } else {
5145 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5146 }
5147 }
5148}
5149
5150bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5151 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5152 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005153 return true;
5154 }
5155 return false;
5156}
5157
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005158bool Camera3Device::startRequestBuffer() {
5159 return mRequestBufferSM.startRequestBuffer();
5160}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005161
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005162void Camera3Device::endRequestBuffer() {
5163 mRequestBufferSM.endRequestBuffer();
5164}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005165
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005166nsecs_t Camera3Device::getWaitDuration() {
5167 return kBaseGetBufferWait + getExpectedInFlightDuration();
5168}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005169
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005170void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5171 mInterface->getInflightBufferKeys(out);
5172}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005173
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005174void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5175 mInterface->getInflightRequestBufferKeys(out);
5176}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005177
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005178std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5179 std::vector<sp<Camera3StreamInterface>> ret;
5180 bool hasInputStream = mInputStream != nullptr;
5181 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5182 if (hasInputStream) {
5183 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005184 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005185 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5186 ret.push_back(mOutputStreams[i]);
5187 }
5188 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5189 ret.push_back(mDeletedStreams[i]);
5190 }
5191 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005192}
5193
Emilian Peevcc0b7952020-01-07 13:54:47 -08005194void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5195 ATRACE_CALL();
5196
5197 if (offlineStreamIds == nullptr) {
5198 return;
5199 }
5200
5201 Mutex::Autolock il(mInterfaceLock);
5202
5203 auto streamIds = mOutputStreams.getStreamIds();
5204 bool hasInputStream = mInputStream != nullptr;
5205 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5206 offlineStreamIds->push_back(mInputStream->getId());
5207 }
5208
5209 for (const auto & streamId : streamIds) {
5210 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5211 // Streams that use the camera buffer manager are currently not supported in
5212 // offline mode
5213 if (stream->getOfflineProcessingSupport() &&
5214 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5215 offlineStreamIds->push_back(streamId);
5216 }
5217 }
5218}
5219
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005220status_t Camera3Device::setRotateAndCropAutoBehavior(
5221 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5222 ATRACE_CALL();
5223 Mutex::Autolock il(mInterfaceLock);
5224 Mutex::Autolock l(mLock);
5225 if (mRequestThread == nullptr) {
5226 return INVALID_OPERATION;
5227 }
5228 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5229}
5230
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005231status_t Camera3Device::setAutoframingAutoBehavior(
5232 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5233 ATRACE_CALL();
5234 Mutex::Autolock il(mInterfaceLock);
5235 Mutex::Autolock l(mLock);
5236 if (mRequestThread == nullptr) {
5237 return INVALID_OPERATION;
5238 }
5239 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5240}
5241
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005242bool Camera3Device::supportsCameraMute() {
5243 Mutex::Autolock il(mInterfaceLock);
5244 Mutex::Autolock l(mLock);
5245
5246 return mSupportCameraMute;
5247}
5248
5249status_t Camera3Device::setCameraMute(bool enabled) {
5250 ATRACE_CALL();
5251 Mutex::Autolock il(mInterfaceLock);
5252 Mutex::Autolock l(mLock);
5253
5254 if (mRequestThread == nullptr || !mSupportCameraMute) {
5255 return INVALID_OPERATION;
5256 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005257 int32_t muteMode =
5258 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5259 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5260 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5261 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005262}
5263
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005264status_t Camera3Device::injectCamera(const String8& injectedCamId,
5265 sp<CameraProviderManager> manager) {
5266 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5267 ATRACE_CALL();
5268 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005269 // When the camera device is active, injectCamera() and stopInjection() will call
5270 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5271 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5272 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5273 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5274 // waitUntilStateThenRelock().
5275 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005276
5277 status_t res = NO_ERROR;
5278 if (mInjectionMethods->isInjecting()) {
5279 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5280 return OK;
5281 } else {
5282 res = mInjectionMethods->stopInjection();
5283 if (res != OK) {
5284 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5285 __FUNCTION__, res);
5286 return res;
5287 }
5288 }
5289 }
5290
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005291 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005292 if (res != OK) {
5293 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5294 __FUNCTION__, res);
5295 return res;
5296 }
5297
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005298 // When the second display of android is cast to the remote device, and the opened camera is
5299 // also cast to the second display, in this case, because the camera has configured the streams
5300 // at this time, we can directly call injectCamera() to replace the internal camera with
5301 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005302 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5303 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5304
5305 camera3::camera_stream_configuration injectionConfig;
5306 std::vector<uint32_t> injectionBufferSizes;
5307 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5308 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5309 || injectionBufferSizes.size() <= 0) {
5310 ALOGE("Failed to inject camera due to abandoned configuration! "
5311 "mOperatingMode: %d injectionConfig.num_streams: %d "
5312 "injectionBufferSizes.size(): %zu", mOperatingMode,
5313 injectionConfig.num_streams, injectionBufferSizes.size());
5314 return DEAD_OBJECT;
5315 }
5316
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005317 res = mInjectionMethods->injectCamera(
5318 injectionConfig, injectionBufferSizes);
5319 if (res != OK) {
5320 ALOGE("Can't finish inject camera process!");
5321 return res;
5322 }
5323 }
5324
5325 return OK;
5326}
5327
5328status_t Camera3Device::stopInjection() {
5329 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5330 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005331 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005332 return mInjectionMethods->stopInjection();
5333}
5334
Shuzhen Wang16610a62022-12-15 22:38:07 -08005335void Camera3Device::overrideStreamUseCaseLocked() {
5336 if (mStreamUseCaseOverrides.size() == 0) {
5337 return;
5338 }
5339
5340 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5341 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5342 // Refer to CameraService::printHelp for details.
5343 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5344 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5345 outputStreamsIndices[i] = i;
5346 }
5347
5348 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5349 [&](int a, int b) -> bool {
5350
5351 auto formatScore = [](int format) {
5352 switch (format) {
5353 case HAL_PIXEL_FORMAT_BLOB:
5354 return 4;
5355 case HAL_PIXEL_FORMAT_RAW16:
5356 case HAL_PIXEL_FORMAT_RAW10:
5357 case HAL_PIXEL_FORMAT_RAW12:
5358 return 3;
5359 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5360 return 2;
5361 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5362 return 1;
5363 default:
5364 return 0;
5365 }
5366 };
5367
5368 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5369 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5370 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5371 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5372 if (sizeA > sizeB ||
5373 (sizeA == sizeB && formatAScore >= formatBScore)) {
5374 return true;
5375 } else {
5376 return false;
5377 }
5378 });
5379
5380 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5381 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5382 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5383 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5384 }
5385}
5386
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005387}; // namespace android