blob: d189de283b7aeb25a353ab12a49a0e8a904b44ba [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,
76 const String8 &id, bool overrideForPerfClass, bool legacyClient):
77 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),
98 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080099{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
104Camera3Device::~Camera3Device()
105{
106 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800107 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700108 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800109}
110
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800112 return mId;
113}
114
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115status_t Camera3Device::initializeCommonLocked() {
116
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700117 /** Start up status tracker thread */
118 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700120 if (res != OK) {
121 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
122 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700124 mStatusTracker.clear();
125 return res;
126 }
127
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700128 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700129 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700130
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700131 if (mUseHalBufManager) {
132 res = mRequestBufferSM.initialize(mStatusTracker);
133 if (res != OK) {
134 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
135 strerror(-res), res);
136 mInterface->close();
137 mStatusTracker.clear();
138 return res;
139 }
140 }
141
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800142 /** Create buffer manager */
143 mBufferManager = new Camera3BufferManager();
144
145 Vector<int32_t> sessionParamKeys;
146 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
147 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
148 if (sessionKeysEntry.count > 0) {
149 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
150 }
151
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700152 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
153 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
154 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
155 if (availableTestPatternModes.data.i32[i] ==
156 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
157 mSupportCameraMute = true;
158 mSupportTestPatternSolidColor = true;
159 break;
160 } else if (availableTestPatternModes.data.i32[i] ==
161 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
162 mSupportCameraMute = true;
163 mSupportTestPatternSolidColor = false;
164 }
165 }
166
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700167 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800168 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700169 this, mStatusTracker, mInterface, sessionParamKeys,
170 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800171 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800172 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700173 SET_ERR_L("Unable to start request queue thread: %s (%d)",
174 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800175 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800176 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800177 return res;
178 }
179
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700180 mPreparerThread = new PreparerThread();
181
Ruben Brunk183f0562015-08-12 12:55:02 -0700182 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800183 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400184 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700185 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700186 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800187 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800188
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800189 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800190 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800191 camera_metadata_entry timestampSource =
192 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
193 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
194 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800195 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800196 }
197
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700198 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100199 camera_metadata_entry partialResultsCount =
200 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
201 if (partialResultsCount.count > 0) {
202 mNumPartialResults = partialResultsCount.data.i32[0];
203 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700204 }
205
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800206 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
207 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700208 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700209 if (res != OK) {
210 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
211 return res;
212 }
213 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800214
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800215 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800216 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700218 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
219 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
220 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
221 }
222
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800223 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
224 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
225 }
226
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800227 // Hidl/AidlCamera3DeviceInjectionMethods
228 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800229
Ravneetaeb20dc2022-03-30 05:33:03 +0000230 /** Start watchdog thread */
231 mCameraServiceWatchdog = new CameraServiceWatchdog();
Austin Borger7b129542022-06-09 13:23:06 -0700232 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
233 if (res != OK) {
234 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
235 strerror(-res), res);
236 return res;
237 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000238
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 return OK;
240}
241
242status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700243 return disconnectImpl();
244}
245
246status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800247 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700248 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800249
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700250 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700251 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700252 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800253 Mutex::Autolock il(mInterfaceLock);
254 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
255 {
256 Mutex::Autolock l(mLock);
257 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700258
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000259 if (mRequestThread != NULL) {
260 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
261 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800262 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000263 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800264 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000265 } else {
266 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
267 if (res != OK) {
268 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
269 maxExpectedDuration);
270 // Continue to close device even in case of error
271 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800272 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000274 // Signal to request thread that we're not expecting any
275 // more requests. This will be true since once we're in
276 // disconnect and we've cleared off the request queue, the
277 // request thread can't receive any new requests through
278 // binder calls - since disconnect holds
279 // mBinderSerialization lock.
280 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700281 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800282
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800283 if (mStatus == STATUS_ERROR) {
284 CLOGE("Shutting down in an error state");
285 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700286
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800287 if (mStatusTracker != NULL) {
288 mStatusTracker->requestExit();
289 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800291 if (mRequestThread != NULL) {
292 mRequestThread->requestExit();
293 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800295 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
296 for (size_t i = 0; i < mOutputStreams.size(); i++) {
297 streams.push_back(mOutputStreams[i]);
298 }
299 if (mInputStream != nullptr) {
300 streams.push_back(mInputStream);
301 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700303 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800304 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
305 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
307 // HAL may be in a bad state, so waiting for request thread
308 // (which may be stuck in the HAL processCaptureRequest call)
309 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800310 // give up mInterfaceLock here and then lock it again. Could this lead
311 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 mRequestThread->join();
313 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800315 Mutex::Autolock il(mInterfaceLock);
316 if (mStatusTracker != NULL) {
317 mStatusTracker->join();
318 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800319
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800320 if (mInjectionMethods->isInjecting()) {
321 mInjectionMethods->stopInjection();
322 }
323
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800324 HalInterface* interface;
325 {
326 Mutex::Autolock l(mLock);
327 mRequestThread.clear();
328 Mutex::Autolock stLock(mTrackerLock);
329 mStatusTracker.clear();
330 interface = mInterface.get();
331 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700332
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800333 // Call close without internal mutex held, as the HAL close may need to
334 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000335 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700336
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800337 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800338
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800339 {
340 Mutex::Autolock l(mLock);
341 mInterface->clear();
342 mOutputStreams.clear();
343 mInputStream.clear();
344 mDeletedStreams.clear();
345 mBufferManager.clear();
346 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
347 }
348
349 for (auto& weakStream : streams) {
350 sp<Camera3StreamInterface> stream = weakStream.promote();
351 if (stream != nullptr) {
352 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
353 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
354 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700355 }
356 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700357 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000358
359 if (mCameraServiceWatchdog != NULL) {
360 mCameraServiceWatchdog->requestExit();
361 mCameraServiceWatchdog.clear();
362 }
363
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700364 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800365}
366
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367// For dumping/debugging only -
368// try to acquire a lock a few times, eventually give up to proceed with
369// debug/dump operations
370bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
371 bool gotLock = false;
372 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
373 if (lock.tryLock() == NO_ERROR) {
374 gotLock = true;
375 break;
376 } else {
377 usleep(kDumpSleepDuration);
378 }
379 }
380 return gotLock;
381}
382
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800383nsecs_t Camera3Device::getMonoToBoottimeOffset() {
384 // try three times to get the clock offset, choose the one
385 // with the minimum gap in measurements.
386 const int tries = 3;
387 nsecs_t bestGap, measured;
388 for (int i = 0; i < tries; ++i) {
389 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
390 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
391 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
392 const nsecs_t gap = tmono2 - tmono;
393 if (i == 0 || gap < bestGap) {
394 bestGap = gap;
395 measured = tbase - ((tmono + tmono2) >> 1);
396 }
397 }
398 return measured;
399}
400
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800401ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
402 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700403 // Get max jpeg size (area-wise) for default sensor pixel mode
404 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800405 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700406 /*isUltraHighResolutionSensor*/false);
407 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
408 // not ultra high res sensor
409 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800410 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411 /*isUltraHighResolution*/true);
412 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800413 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
414 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700415 return BAD_VALUE;
416 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700417 bool useMaxSensorPixelModeThreshold = false;
418 if (uhrMaxJpegResolution.width != 0 &&
419 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
420 // Use the ultra high res max jpeg size and max jpeg buffer size
421 useMaxSensorPixelModeThreshold = true;
422 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700423
Zhijun Hef7da0962014-04-24 13:27:56 -0700424 // Get max jpeg buffer size
425 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800426 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700427 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800428 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
429 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 return BAD_VALUE;
431 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700433
434 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
435 if (useMaxSensorPixelModeThreshold) {
436 maxJpegBufferSize =
437 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
438 maxDefaultJpegResolution, maxJpegBufferSize);
439 chosenMaxJpegResolution = uhrMaxJpegResolution;
440 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800441 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700442
443 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700444 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700445 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800446 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
447 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700448 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800449 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
450 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700451 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700452 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700453 return jpegBufferSize;
454}
455
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800456ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700457 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800458 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700459 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800460 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
461 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700462 return BAD_VALUE;
463 }
464 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
465 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
466 return maxBytesForPointCloud;
467}
468
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800469ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
470 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800471 const int PER_CONFIGURATION_SIZE = 3;
472 const int WIDTH_OFFSET = 0;
473 const int HEIGHT_OFFSET = 1;
474 const int SIZE_OFFSET = 2;
475 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800476 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800477 camera3::SessionConfigurationUtils::getAppropriateModeTag(
478 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
479 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800480 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800481 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800482 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
483 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800484 return BAD_VALUE;
485 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700486
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800487 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
488 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
489 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
490 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
491 }
492 }
493
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800494 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
495 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800496 return BAD_VALUE;
497}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700498
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800499status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
500 ATRACE_CALL();
501 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700502
503 // Try to lock, but continue in case of failure (to avoid blocking in
504 // deadlocks)
505 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
506 bool gotLock = tryLockSpinRightRound(mLock);
507
508 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800509 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
510 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700511 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
513 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700514
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800515 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700516
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800517 String16 templatesOption("-t");
518 int n = args.size();
519 for (int i = 0; i < n; i++) {
520 if (args[i] == templatesOption) {
521 dumpTemplates = true;
522 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000523 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700524 if (i + 1 < n) {
525 String8 monitorTags = String8(args[i + 1]);
526 if (monitorTags == "off") {
527 mTagMonitor.disableMonitoring();
528 } else {
529 mTagMonitor.parseTagsToMonitor(monitorTags);
530 }
531 } else {
532 mTagMonitor.disableMonitoring();
533 }
534 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800535 }
536
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800537 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800538
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800539 const char *status =
540 mStatus == STATUS_ERROR ? "ERROR" :
541 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700542 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
543 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800544 mStatus == STATUS_ACTIVE ? "ACTIVE" :
545 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700546
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800547 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700548 if (mStatus == STATUS_ERROR) {
549 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
550 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800551 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800552 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000553 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
554 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
555 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800556 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800557
558 if (mInputStream != NULL) {
559 write(fd, lines.string(), lines.size());
560 mInputStream->dump(fd, args);
561 } else {
562 lines.appendFormat(" No input stream.\n");
563 write(fd, lines.string(), lines.size());
564 }
565 for (size_t i = 0; i < mOutputStreams.size(); i++) {
566 mOutputStreams[i]->dump(fd,args);
567 }
568
Zhijun He431503c2016-03-07 17:30:16 -0800569 if (mBufferManager != NULL) {
570 lines = String8(" Camera3 Buffer Manager:\n");
571 write(fd, lines.string(), lines.size());
572 mBufferManager->dump(fd, args);
573 }
Zhijun He125684a2015-12-26 15:07:30 -0800574
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700575 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700576 if (mInFlightLock.try_lock()) {
577 if (mInFlightMap.size() == 0) {
578 lines.append(" None\n");
579 } else {
580 for (size_t i = 0; i < mInFlightMap.size(); i++) {
581 InFlightRequest r = mInFlightMap.valueAt(i);
582 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
583 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
584 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
585 r.numBuffersLeft);
586 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700587 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700588 mInFlightLock.unlock();
589 } else {
590 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700591 }
592 write(fd, lines.string(), lines.size());
593
Shuzhen Wang686f6442017-06-20 16:16:04 -0700594 if (mRequestThread != NULL) {
595 mRequestThread->dumpCaptureRequestLatency(fd,
596 " ProcessCaptureRequest latency histogram:");
597 }
598
Igor Murashkin1e479c02013-09-06 16:55:14 -0700599 {
600 lines = String8(" Last request sent:\n");
601 write(fd, lines.string(), lines.size());
602
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700603 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700604 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
605 }
606
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800607 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700608 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800609 "TEMPLATE_PREVIEW",
610 "TEMPLATE_STILL_CAPTURE",
611 "TEMPLATE_VIDEO_RECORD",
612 "TEMPLATE_VIDEO_SNAPSHOT",
613 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800614 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800615 };
616
Emilian Peevf4816702020-04-03 15:44:51 -0700617 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 camera_metadata_t *templateRequest = nullptr;
619 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700620 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800621 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800622 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800623 lines.append(" Not supported\n");
624 write(fd, lines.string(), lines.size());
625 } else {
626 write(fd, lines.string(), lines.size());
627 dump_indented_camera_metadata(templateRequest,
628 fd, /*verbosity*/2, /*indentation*/8);
629 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800630 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800631 }
632 }
633
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700634 mTagMonitor.dumpMonitoredMetadata(fd);
635
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800636 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800637 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800638 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800641
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700642 if (gotLock) mLock.unlock();
643 if (gotInterfaceLock) mInterfaceLock.unlock();
644
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800645 return OK;
646}
647
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700648status_t Camera3Device::startWatchingTags(const String8 &tags) {
649 mTagMonitor.parseTagsToMonitor(tags);
650 return OK;
651}
652
653status_t Camera3Device::stopWatchingTags() {
654 mTagMonitor.disableMonitoring();
655 return OK;
656}
657
658status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
659 mTagMonitor.getLatestMonitoredTagEvents(out);
660 return OK;
661}
662
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800663const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800664 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800665 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
666 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700667 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 mStatus == STATUS_ERROR ?
669 "when in error state" : "before init");
670 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700671 if (physicalId.isEmpty()) {
672 return mDeviceInfo;
673 } else {
674 std::string id(physicalId.c_str());
675 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
676 return mPhysicalDeviceInfoMap.at(id);
677 } else {
678 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
679 return mDeviceInfo;
680 }
681 }
682}
683
684const CameraMetadata& Camera3Device::info() const {
685 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800686 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800687}
688
Jianing Wei90e59c92014-03-12 18:29:36 -0700689status_t Camera3Device::checkStatusOkToCaptureLocked() {
690 switch (mStatus) {
691 case STATUS_ERROR:
692 CLOGE("Device has encountered a serious error");
693 return INVALID_OPERATION;
694 case STATUS_UNINITIALIZED:
695 CLOGE("Device not initialized");
696 return INVALID_OPERATION;
697 case STATUS_UNCONFIGURED:
698 case STATUS_CONFIGURED:
699 case STATUS_ACTIVE:
700 // OK
701 break;
702 default:
703 SET_ERR_L("Unexpected status: %d", mStatus);
704 return INVALID_OPERATION;
705 }
706 return OK;
707}
708
709status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000710 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700711 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700712 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700713 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700714 if (requestList == NULL) {
715 CLOGE("requestList cannot be NULL.");
716 return BAD_VALUE;
717 }
718
Jianing Weicb0652e2014-03-12 18:29:36 -0700719 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000720 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700721 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
722 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
723 ++metadataIt, ++surfaceMapIt) {
724 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700725 if (newRequest == 0) {
726 CLOGE("Can't create capture request");
727 return BAD_VALUE;
728 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700729
Shuzhen Wang9d066012016-09-30 11:30:20 -0700730 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700731 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700732
Jianing Weicb0652e2014-03-12 18:29:36 -0700733 // Setup burst Id and request Id
734 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800735 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
736 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700737 CLOGE("RequestID does not exist in metadata");
738 return BAD_VALUE;
739 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800740 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700741
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700743
744 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700745 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700746 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
747 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
748 return BAD_VALUE;
749 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700750
751 // Setup batch size if this is a high speed video recording request.
752 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
753 auto firstRequest = requestList->begin();
754 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
755 if (outputStream->isVideoStream()) {
756 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800757 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700758 break;
759 }
760 }
761 }
762
Jianing Wei90e59c92014-03-12 18:29:36 -0700763 return OK;
764}
765
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800766status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800767 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800768
Emilian Peevaebbe412018-01-15 13:53:24 +0000769 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700770 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000771 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700772
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800773 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774}
775
Emilian Peevaebbe412018-01-15 13:53:24 +0000776void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777 std::list<const SurfaceMap>& surfaceMaps,
778 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000779 PhysicalCameraSettingsList requestList;
780 requestList.push_back({std::string(getId().string()), request});
781 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700782
783 SurfaceMap surfaceMap;
784 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
785 // With no surface list passed in, stream and surface will have 1-to-1
786 // mapping. So the surface index is 0 for each stream in the surfaceMap.
787 for (size_t i = 0; i < streams.count; i++) {
788 surfaceMap[streams.data.i32[i]].push_back(0);
789 }
790 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800791}
792
Jianing Wei90e59c92014-03-12 18:29:36 -0700793status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000794 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700795 const std::list<const SurfaceMap> &surfaceMaps,
796 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700797 /*out*/
798 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700800 nsecs_t requestTimeNs = systemTime();
801
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 Mutex::Autolock il(mInterfaceLock);
803 Mutex::Autolock l(mLock);
804
805 status_t res = checkStatusOkToCaptureLocked();
806 if (res != OK) {
807 // error logged by previous call
808 return res;
809 }
810
811 RequestList requestList;
812
Shuzhen Wang0129d522016-10-30 22:43:41 -0700813 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700814 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700815 if (res != OK) {
816 // error logged by previous call
817 return res;
818 }
819
820 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700821 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700822 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700823 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 }
825
826 if (res == OK) {
827 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
828 if (res != OK) {
829 SET_ERR_L("Can't transition to active in %f seconds!",
830 kActiveTimeout/1e9);
831 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800832 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700833 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 } else {
835 CLOGE("Cannot queue request. Impossible.");
836 return BAD_VALUE;
837 }
838
839 return res;
840}
841
Emilian Peevaebbe412018-01-15 13:53:24 +0000842status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700843 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700844 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700845 ATRACE_CALL();
846
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700848}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800849
Jianing Weicb0652e2014-03-12 18:29:36 -0700850status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
851 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800853
Emilian Peevaebbe412018-01-15 13:53:24 +0000854 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700855 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700857
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800860}
861
Emilian Peevaebbe412018-01-15 13:53:24 +0000862status_t Camera3Device::setStreamingRequestList(
863 const List<const PhysicalCameraSettingsList> &requestsList,
864 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 ATRACE_CALL();
866
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700868}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800869
870sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872 status_t res;
873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700874 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800875 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
876 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000877 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700878 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700879 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800880 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700881 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800882 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700883 } else if (mStatus == STATUS_UNCONFIGURED) {
884 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 CLOGE("No streams configured");
886 return NULL;
887 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800888 }
889
Shuzhen Wang0129d522016-10-30 22:43:41 -0700890 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800892}
893
Jianing Weicb0652e2014-03-12 18:29:36 -0700894status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800895 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700896 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800897 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800898
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800899 switch (mStatus) {
900 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700901 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 return INVALID_OPERATION;
903 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700904 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800905 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700906 case STATUS_UNCONFIGURED:
907 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800908 case STATUS_ACTIVE:
909 // OK
910 break;
911 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700912 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800913 return INVALID_OPERATION;
914 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800915 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700916
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700917 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800918}
919
920status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
921 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700922 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800923
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700924 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925}
926
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700927status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800928 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700929 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700930 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700931 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800933 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
934 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700935
936 status_t res;
937 bool wasActive = false;
938
939 switch (mStatus) {
940 case STATUS_ERROR:
941 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
942 return INVALID_OPERATION;
943 case STATUS_UNINITIALIZED:
944 ALOGE("%s: Device not initialized", __FUNCTION__);
945 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700946 case STATUS_UNCONFIGURED:
947 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700948 // OK
949 break;
950 case STATUS_ACTIVE:
951 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700952 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700953 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700954 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955 return res;
956 }
957 wasActive = true;
958 break;
959 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700960 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700961 return INVALID_OPERATION;
962 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700963 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700964
965 if (mInputStream != 0) {
966 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
967 return INVALID_OPERATION;
968 }
969
970 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
971 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700972 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700973
974 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800975 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700976
977 *id = mNextStreamId++;
978
979 // Continue captures if active at start
980 if (wasActive) {
981 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100982 // Reuse current operating mode and session parameters for new stream config
983 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700984 if (res != OK) {
985 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
986 __FUNCTION__, mNextStreamId, strerror(-res), res);
987 return res;
988 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700989 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700990 }
991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800992 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700993 return OK;
994}
995
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700996status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700997 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700998 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800999 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001000 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1001 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001002 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001003 int timestampBase, int mirrorMode, int32_t colorSpace) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001004 ATRACE_CALL();
1005
1006 if (consumer == nullptr) {
1007 ALOGE("%s: consumer must not be null", __FUNCTION__);
1008 return BAD_VALUE;
1009 }
1010
1011 std::vector<sp<Surface>> consumers;
1012 consumers.push_back(consumer);
1013
1014 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001015 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001016 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001017 streamUseCase, timestampBase, mirrorMode, colorSpace);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001018}
1019
1020static bool isRawFormat(int format) {
1021 switch (format) {
1022 case HAL_PIXEL_FORMAT_RAW16:
1023 case HAL_PIXEL_FORMAT_RAW12:
1024 case HAL_PIXEL_FORMAT_RAW10:
1025 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1026 return true;
1027 default:
1028 return false;
1029 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001030}
1031
1032status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1033 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001034 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001035 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001036 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001037 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001038 int timestampBase, int mirrorMode, int32_t colorSpace) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001039 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001040
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001041 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001042 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001043 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001044 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001045 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001046 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Austin Borger9e2b27c2022-07-15 11:27:24 -07001047 " mirrorMode %d colorSpace %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001048 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001049 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001050 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001051
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001052 status_t res;
1053 bool wasActive = false;
1054
1055 switch (mStatus) {
1056 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001057 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058 return INVALID_OPERATION;
1059 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001060 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001061 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001062 case STATUS_UNCONFIGURED:
1063 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 // OK
1065 break;
1066 case STATUS_ACTIVE:
1067 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001068 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001070 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 return res;
1072 }
1073 wasActive = true;
1074 break;
1075 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001076 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 return INVALID_OPERATION;
1078 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001079 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080
1081 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001082
Shuzhen Wang0129d522016-10-30 22:43:41 -07001083 if (consumers.size() == 0 && !hasDeferredConsumer) {
1084 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1085 return BAD_VALUE;
1086 }
Zhijun He5d677d12016-05-29 16:52:39 -07001087
Shuzhen Wang0129d522016-10-30 22:43:41 -07001088 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001089 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1090 return BAD_VALUE;
1091 }
1092
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001093 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1094 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1095 // be found in only one sensor pixel mode.
1096 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1097 return BAD_VALUE;
1098 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001099 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001100 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001101 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001102 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001103 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001104 if (blobBufferSize <= 0) {
1105 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1106 return BAD_VALUE;
1107 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001108 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1109 blobBufferSize = width * height;
1110 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001111 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001112 if (blobBufferSize <= 0) {
1113 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1114 return BAD_VALUE;
1115 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001116 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001117 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001118 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001119 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001120 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001121 timestampBase, mirrorMode, colorSpace);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001122 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001123 bool maxResolution =
1124 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1125 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001126 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1127 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001128 if (rawOpaqueBufferSize <= 0) {
1129 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1130 return BAD_VALUE;
1131 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001132 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001133 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001134 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001135 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001136 timestampBase, mirrorMode, colorSpace);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001137 } else if (isShared) {
1138 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1139 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001140 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001141 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001142 timestampBase, mirrorMode, colorSpace);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001143 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001144 newStream = new Camera3OutputStream(mNextStreamId,
1145 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001146 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001147 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001148 timestampBase, mirrorMode, colorSpace);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001150 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001151 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001152 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001153 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -07001154 timestampBase, mirrorMode, colorSpace);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001155 }
Emilian Peev40ead602017-09-26 15:46:36 +01001156
1157 size_t consumerCount = consumers.size();
1158 for (size_t i = 0; i < consumerCount; i++) {
1159 int id = newStream->getSurfaceId(consumers[i]);
1160 if (id < 0) {
1161 SET_ERR_L("Invalid surface id");
1162 return BAD_VALUE;
1163 }
1164 if (surfaceIds != nullptr) {
1165 surfaceIds->push_back(id);
1166 }
1167 }
1168
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001169 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001170
Emilian Peev08dd2452017-04-06 16:55:14 +01001171 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001172
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001173 newStream->setImageDumpMask(mImageDumpMask);
1174
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 res = mOutputStreams.add(mNextStreamId, newStream);
1176 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001177 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 return res;
1179 }
1180
Shuzhen Wang316781a2020-08-18 18:11:01 -07001181 mSessionStatsBuilder.addStream(mNextStreamId);
1182
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001184 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185
1186 // Continue captures if active at start
1187 if (wasActive) {
1188 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001189 // Reuse current operating mode and session parameters for new stream config
1190 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001192 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1193 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 return res;
1195 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001196 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001198 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001200}
1201
Emilian Peev710c1422017-08-30 11:19:38 +01001202status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001203 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001204 if (nullptr == streamInfo) {
1205 return BAD_VALUE;
1206 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001207 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 switch (mStatus) {
1211 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001212 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 return INVALID_OPERATION;
1214 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001215 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 case STATUS_UNCONFIGURED:
1218 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 case STATUS_ACTIVE:
1220 // OK
1221 break;
1222 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001223 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 return INVALID_OPERATION;
1225 }
1226
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001227 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1228 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001230 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 }
1232
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001233 streamInfo->width = stream->getWidth();
1234 streamInfo->height = stream->getHeight();
1235 streamInfo->format = stream->getFormat();
1236 streamInfo->dataSpace = stream->getDataSpace();
1237 streamInfo->formatOverridden = stream->isFormatOverridden();
1238 streamInfo->originalFormat = stream->getOriginalFormat();
1239 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1240 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001241 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001242 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244}
1245
1246status_t Camera3Device::setStreamTransform(int id,
1247 int transform) {
1248 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 switch (mStatus) {
1253 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001254 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 return INVALID_OPERATION;
1256 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 case STATUS_UNCONFIGURED:
1260 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 case STATUS_ACTIVE:
1262 // OK
1263 break;
1264 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001265 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return INVALID_OPERATION;
1267 }
1268
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001269 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1270 if (stream == nullptr) {
1271 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 return BAD_VALUE;
1273 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001274 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275}
1276
1277status_t Camera3Device::deleteStream(int id) {
1278 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001280 Mutex::Autolock l(mLock);
1281 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001282
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001283 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001284
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 // CameraDevice semantics require device to already be idle before
1286 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001288 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001289 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 }
1291
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001292 if (mStatus == STATUS_ERROR) {
1293 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1294 __FUNCTION__, mId.string());
1295 return -EBUSY;
1296 }
1297
Igor Murashkin2fba5842013-04-22 14:03:54 -07001298 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001299 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001300 if (mInputStream != NULL && id == mInputStream->getId()) {
1301 deletedStream = mInputStream;
1302 mInputStream.clear();
1303 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001304 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001305 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001306 return BAD_VALUE;
1307 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001308 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001309 }
1310
1311 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001312 if (stream != nullptr) {
1313 deletedStream = stream;
1314 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001315 }
1316
1317 // Free up the stream endpoint so that it can be used by some other stream
1318 res = deletedStream->disconnect();
1319 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001320 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001321 // fall through since we want to still list the stream as deleted.
1322 }
1323 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001324 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001325
1326 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001327}
1328
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001329status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001330 ATRACE_CALL();
1331 ALOGV("%s: E", __FUNCTION__);
1332
1333 Mutex::Autolock il(mInterfaceLock);
1334 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001335
Emilian Peev811d2952018-05-25 11:08:40 +01001336 // In case the client doesn't include any session parameter, try a
1337 // speculative configuration using the values from the last cached
1338 // default request.
1339 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001340 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001341 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1342 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1343 mLastTemplateId);
1344 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1345 operatingMode);
1346 }
1347
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001348 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1349}
1350
1351status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1352 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001353 //Filter out any incoming session parameters
1354 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001355 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1356 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001357 CameraMetadata filteredParams(availableSessionKeys.count);
1358 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1359 filteredParams.getAndLock());
1360 set_camera_metadata_vendor_id(meta, mVendorTagId);
1361 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001362 if (availableSessionKeys.count > 0) {
1363 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1364 camera_metadata_ro_entry entry = params.find(
1365 availableSessionKeys.data.i32[i]);
1366 if (entry.count > 0) {
1367 filteredParams.update(entry);
1368 }
1369 }
1370 }
1371
1372 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001373}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001374
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001375status_t Camera3Device::getInputBufferProducer(
1376 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001377 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001378 Mutex::Autolock il(mInterfaceLock);
1379 Mutex::Autolock l(mLock);
1380
1381 if (producer == NULL) {
1382 return BAD_VALUE;
1383 } else if (mInputStream == NULL) {
1384 return INVALID_OPERATION;
1385 }
1386
1387 return mInputStream->getInputBufferProducer(producer);
1388}
1389
Emilian Peevf4816702020-04-03 15:44:51 -07001390status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001391 CameraMetadata *request) {
1392 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001393 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001394
Emilian Peevf4816702020-04-03 15:44:51 -07001395 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001396 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001397 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001398 return BAD_VALUE;
1399 }
1400
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001401 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001403 {
1404 Mutex::Autolock l(mLock);
1405 switch (mStatus) {
1406 case STATUS_ERROR:
1407 CLOGE("Device has encountered a serious error");
1408 return INVALID_OPERATION;
1409 case STATUS_UNINITIALIZED:
1410 CLOGE("Device is not initialized!");
1411 return INVALID_OPERATION;
1412 case STATUS_UNCONFIGURED:
1413 case STATUS_CONFIGURED:
1414 case STATUS_ACTIVE:
1415 // OK
1416 break;
1417 default:
1418 SET_ERR_L("Unexpected status: %d", mStatus);
1419 return INVALID_OPERATION;
1420 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001421
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001422 if (!mRequestTemplateCache[templateId].isEmpty()) {
1423 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001424 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001425 return OK;
1426 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001427 }
1428
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001429 camera_metadata_t *rawRequest;
1430 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001431 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001432
1433 {
1434 Mutex::Autolock l(mLock);
1435 if (res == BAD_VALUE) {
1436 ALOGI("%s: template %d is not supported on this camera device",
1437 __FUNCTION__, templateId);
1438 return res;
1439 } else if (res != OK) {
1440 CLOGE("Unable to construct request template %d: %s (%d)",
1441 templateId, strerror(-res), res);
1442 return res;
1443 }
1444
1445 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1446 mRequestTemplateCache[templateId].acquire(rawRequest);
1447
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001448 // Override the template request with zoomRatioMapper
1449 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1450 &mRequestTemplateCache[templateId]);
1451 if (res != OK) {
1452 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1453 templateId, strerror(-res), res);
1454 return res;
1455 }
1456
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001457 // Fill in JPEG_QUALITY if not available
1458 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1459 static const uint8_t kDefaultJpegQuality = 95;
1460 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1461 &kDefaultJpegQuality, 1);
1462 }
1463
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001464 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001465 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001466 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467 return OK;
1468}
1469
1470status_t Camera3Device::waitUntilDrained() {
1471 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001472 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001473 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001476 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001477}
1478
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001479status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 switch (mStatus) {
1481 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 ALOGV("%s: Already idle", __FUNCTION__);
1484 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001485 case STATUS_CONFIGURED:
1486 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 case STATUS_ERROR:
1488 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001489 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 break;
1491 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001492 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 return INVALID_OPERATION;
1494 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001495 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1496 maxExpectedDuration);
1497 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001498 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001499 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001500 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1501 res);
1502 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001503 return res;
1504}
1505
Ruben Brunk183f0562015-08-12 12:55:02 -07001506void Camera3Device::internalUpdateStatusLocked(Status status) {
1507 mStatus = status;
1508 mRecentStatusUpdates.add(mStatus);
1509 mStatusChanged.broadcast();
1510}
1511
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001512// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001513status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001514 if (mRequestThread.get() != nullptr) {
1515 mRequestThread->setPaused(true);
1516 } else {
1517 return NO_INIT;
1518 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001519
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001520 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1521 maxExpectedDuration);
1522 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001524 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001526 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 }
1528
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001529 return res;
1530}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532// Resume after internalPauseAndWaitLocked
1533status_t Camera3Device::internalResumeLocked() {
1534 status_t res;
1535
1536 mRequestThread->setPaused(false);
1537
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001538 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1539 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1541 if (res != OK) {
1542 SET_ERR_L("Can't transition to active in %f seconds!",
1543 kActiveTimeout/1e9);
1544 }
1545 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547}
1548
Ruben Brunk183f0562015-08-12 12:55:02 -07001549status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001551
1552 size_t startIndex = 0;
1553 if (mStatusWaiters == 0) {
1554 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1555 // this status list
1556 mRecentStatusUpdates.clear();
1557 } else {
1558 // If other threads are waiting on updates to this status list, set the position of the
1559 // first element that this list will check rather than clearing the list.
1560 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 }
1562
Ruben Brunk183f0562015-08-12 12:55:02 -07001563 mStatusWaiters++;
1564
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001565 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001566 if (!active && mUseHalBufManager) {
1567 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001568 if (mStatus == STATUS_ACTIVE) {
1569 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001570 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001571 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001572 mRequestBufferSM.onWaitUntilIdle();
1573 }
1574
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001576 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001577 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001578 if (active == (mStatus == STATUS_ACTIVE)) {
1579 // Desired state is current
1580 break;
1581 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001583 nsecs_t timeElapsed = systemTime() - startTime;
1584 nsecs_t timeToWait = timeout - timeElapsed;
1585 if (timeToWait <= 0) {
1586 // Thread woke up spuriously but has timed out since.
1587 // Force out of loop with TIMED_OUT result.
1588 res = TIMED_OUT;
1589 break;
1590 }
1591 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 if (res != OK) break;
1593
Ruben Brunk183f0562015-08-12 12:55:02 -07001594 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1595 // transitions.
1596 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1597 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1598 __FUNCTION__);
1599
1600 // Encountered desired state since we began waiting
1601 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1603 stateSeen = true;
1604 break;
1605 }
1606 }
1607 } while (!stateSeen);
1608
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001609 if (signalPipelineDrain) {
1610 mRequestThread->resetPipelineDrain();
1611 }
1612
Ruben Brunk183f0562015-08-12 12:55:02 -07001613 mStatusWaiters--;
1614
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001615 return res;
1616}
1617
1618
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001619status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001620 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001621 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001622
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001623 if (listener != NULL && mListener != NULL) {
1624 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1625 }
1626 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001627 mRequestThread->setNotificationListener(listener);
1628 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001629
1630 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631}
1632
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001633bool Camera3Device::willNotify3A() {
1634 return false;
1635}
1636
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001637status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001638 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001639 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001640
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001641 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001642 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1643 if (st == std::cv_status::timeout) {
1644 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001645 }
1646 }
1647 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648}
1649
Jianing Weicb0652e2014-03-12 18:29:36 -07001650status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001652 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001654 if (mResultQueue.empty()) {
1655 return NOT_ENOUGH_DATA;
1656 }
1657
Jianing Weicb0652e2014-03-12 18:29:36 -07001658 if (frame == NULL) {
1659 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1660 return BAD_VALUE;
1661 }
1662
1663 CaptureResult &result = *(mResultQueue.begin());
1664 frame->mResultExtras = result.mResultExtras;
1665 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001666 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001667 mResultQueue.erase(mResultQueue.begin());
1668
1669 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001670}
1671
1672status_t Camera3Device::triggerAutofocus(uint32_t id) {
1673 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001674 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001676 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1677 // Mix-in this trigger into the next request and only the next request.
1678 RequestTrigger trigger[] = {
1679 {
1680 ANDROID_CONTROL_AF_TRIGGER,
1681 ANDROID_CONTROL_AF_TRIGGER_START
1682 },
1683 {
1684 ANDROID_CONTROL_AF_TRIGGER_ID,
1685 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001686 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 };
1688
1689 return mRequestThread->queueTrigger(trigger,
1690 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001691}
1692
1693status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1694 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1698 // Mix-in this trigger into the next request and only the next request.
1699 RequestTrigger trigger[] = {
1700 {
1701 ANDROID_CONTROL_AF_TRIGGER,
1702 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1703 },
1704 {
1705 ANDROID_CONTROL_AF_TRIGGER_ID,
1706 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001707 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001708 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001709
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001710 return mRequestThread->queueTrigger(trigger,
1711 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001712}
1713
1714status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1715 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001716 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001717
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001718 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1719 // Mix-in this trigger into the next request and only the next request.
1720 RequestTrigger trigger[] = {
1721 {
1722 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1723 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1724 },
1725 {
1726 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1727 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001728 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001729 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001730
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001731 return mRequestThread->queueTrigger(trigger,
1732 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733}
1734
Jianing Weicb0652e2014-03-12 18:29:36 -07001735status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001736 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001737 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001738 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001739
Zhijun He7ef20392014-04-21 16:04:17 -07001740 {
1741 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001742
1743 // b/116514106 "disconnect()" can get called twice for the same device. The
1744 // camera device will not be initialized during the second run.
1745 if (mStatus == STATUS_UNINITIALIZED) {
1746 return OK;
1747 }
1748
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001749 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001750
1751 // Stop session and stream counter
1752 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001753 }
1754
Ravneetdbd5b242022-03-02 07:22:46 +00001755 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001756 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001757 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1758 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1759
1760 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001761}
1762
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001763status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001764 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1765}
1766
1767status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001768 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001769 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001770 Mutex::Autolock il(mInterfaceLock);
1771 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001772
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001773 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1774 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001775 CLOGE("Stream %d does not exist", streamId);
1776 return BAD_VALUE;
1777 }
1778
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001779 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001780 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001781 return BAD_VALUE;
1782 }
1783
1784 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001785 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001786 return BAD_VALUE;
1787 }
1788
Ruben Brunkc78ac262015-08-13 17:58:46 -07001789 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001790}
1791
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001792status_t Camera3Device::tearDown(int streamId) {
1793 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001794 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001795 Mutex::Autolock il(mInterfaceLock);
1796 Mutex::Autolock l(mLock);
1797
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001798 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1799 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001800 CLOGE("Stream %d does not exist", streamId);
1801 return BAD_VALUE;
1802 }
1803
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001804 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1805 CLOGE("Stream %d is a target of a in-progress request", streamId);
1806 return BAD_VALUE;
1807 }
1808
1809 return stream->tearDown();
1810}
1811
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001812status_t Camera3Device::addBufferListenerForStream(int streamId,
1813 wp<Camera3StreamBufferListener> listener) {
1814 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001815 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001816 Mutex::Autolock il(mInterfaceLock);
1817 Mutex::Autolock l(mLock);
1818
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001819 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1820 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001821 CLOGE("Stream %d does not exist", streamId);
1822 return BAD_VALUE;
1823 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001824 stream->addBufferListener(listener);
1825
1826 return OK;
1827}
1828
Austin Borger4a870a32022-02-25 01:48:41 +00001829float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1830 camera_metadata_entry minDurations =
1831 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1832 for (size_t i = 0; i < minDurations.count; i += 4) {
1833 if (minDurations.data.i64[i] == stream->getFormat()
1834 && minDurations.data.i64[i+1] == stream->getWidth()
1835 && minDurations.data.i64[i+2] == stream->getHeight()) {
1836 int64_t minFrameDuration = minDurations.data.i64[i+3];
1837 return 1e9f / minFrameDuration;
1838 }
1839 }
1840 return 0.0f;
1841}
1842
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 * Methods called by subclasses
1845 */
1846
1847void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001848 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001849 std::vector<int> streamIds;
1850 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001851 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853 {
1854 // Need mLock to safely update state and synchronize to current
1855 // state of methods in flight.
1856 Mutex::Autolock l(mLock);
1857 // We can get various system-idle notices from the status tracker
1858 // while starting up. Only care about them if we've actually sent
1859 // in some requests recently.
1860 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1861 return;
1862 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001863 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1864 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001865 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866
1867 // Skip notifying listener if we're doing some user-transparent
1868 // state changes
1869 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001870
Austin Borger4a870a32022-02-25 01:48:41 +00001871 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1872 auto stream = mOutputStreams[i];
1873 if (stream.get() == nullptr) continue;
1874
1875 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1876 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1877
1878 // Populate stream statistics in case of Idle
1879 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001880 streamIds.push_back(stream->getId());
1881 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1882 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001883 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001884 if (camera3Stream != nullptr) {
1885 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001886 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001887 }
1888 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001889 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001890 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001891 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001892 stream->getDynamicRangeProfile(), streamUseCase,
1893 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001894 }
1895 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001896 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001897
1898 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001900 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001901 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001902 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001903 status_t res = OK;
1904 if (listener != nullptr) {
1905 if (idle) {
1906 // Get session stats from the builder, and notify the listener.
1907 int64_t requestCount, resultErrorCount;
1908 bool deviceError;
1909 std::map<int, StreamStats> streamStatsMap;
1910 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1911 &deviceError, &streamStatsMap);
1912 for (size_t i = 0; i < streamIds.size(); i++) {
1913 int streamId = streamIds[i];
1914 auto stats = streamStatsMap.find(streamId);
1915 if (stats != streamStatsMap.end()) {
1916 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1917 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1918 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1919 streamStats[i].mHistogramType =
1920 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1921 streamStats[i].mHistogramBins.assign(
1922 stats->second.mCaptureLatencyBins.begin(),
1923 stats->second.mCaptureLatencyBins.end());
1924 streamStats[i].mHistogramCounts.assign(
1925 stats->second.mCaptureLatencyHistogram.begin(),
1926 stats->second.mCaptureLatencyHistogram.end());
1927 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001928 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001929 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1930 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001931 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001932 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001933 }
1934 if (res != OK) {
1935 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1936 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001937 }
1938}
1939
Shuzhen Wang758c2152017-01-10 18:26:18 -08001940status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001941 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001942 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001943 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1944 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001945
1946 if (surfaceIds == nullptr) {
1947 return BAD_VALUE;
1948 }
1949
Zhijun He5d677d12016-05-29 16:52:39 -07001950 Mutex::Autolock il(mInterfaceLock);
1951 Mutex::Autolock l(mLock);
1952
Shuzhen Wang758c2152017-01-10 18:26:18 -08001953 if (consumers.size() == 0) {
1954 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001955 return BAD_VALUE;
1956 }
1957
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001958 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1959 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001960 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001961 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001962 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001963
1964 // isConsumerConfigurationDeferred will be off after setConsumers
1965 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001966 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001967 if (res != OK) {
1968 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1969 return res;
1970 }
1971
Emilian Peev40ead602017-09-26 15:46:36 +01001972 for (auto &consumer : consumers) {
1973 int id = stream->getSurfaceId(consumer);
1974 if (id < 0) {
1975 CLOGE("Invalid surface id!");
1976 return BAD_VALUE;
1977 }
1978 surfaceIds->push_back(id);
1979 }
1980
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001981 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001982 if (!stream->isConfiguring()) {
1983 CLOGE("Stream %d was already fully configured.", streamId);
1984 return INVALID_OPERATION;
1985 }
Zhijun He5d677d12016-05-29 16:52:39 -07001986
Shuzhen Wang0129d522016-10-30 22:43:41 -07001987 res = stream->finishConfiguration();
1988 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001989 // If finishConfiguration fails due to abandoned surface, do not set
1990 // device to error state.
1991 bool isSurfaceAbandoned =
1992 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1993 if (!isSurfaceAbandoned) {
1994 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1995 stream->getId(), strerror(-res), res);
1996 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001997 return res;
1998 }
Zhijun He5d677d12016-05-29 16:52:39 -07001999 }
2000
2001 return OK;
2002}
2003
Emilian Peev40ead602017-09-26 15:46:36 +01002004status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2005 const std::vector<OutputStreamInfo> &outputInfo,
2006 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2007 Mutex::Autolock il(mInterfaceLock);
2008 Mutex::Autolock l(mLock);
2009
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002010 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2011 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002012 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002013 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002014 }
2015
2016 for (const auto &it : removedSurfaceIds) {
2017 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2018 CLOGE("Shared surface still part of a pending request!");
2019 return -EBUSY;
2020 }
2021 }
2022
Emilian Peev40ead602017-09-26 15:46:36 +01002023 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2024 if (res != OK) {
2025 CLOGE("Stream %d failed to update stream (error %d %s) ",
2026 streamId, res, strerror(-res));
2027 if (res == UNKNOWN_ERROR) {
2028 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2029 __FUNCTION__);
2030 }
2031 return res;
2032 }
2033
2034 return res;
2035}
2036
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002037status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2038 Mutex::Autolock il(mInterfaceLock);
2039 Mutex::Autolock l(mLock);
2040
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002041 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2042 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002043 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2044 return BAD_VALUE;
2045 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002046
2047 if (dropping) {
2048 mSessionStatsBuilder.stopCounter(streamId);
2049 } else {
2050 mSessionStatsBuilder.startCounter(streamId);
2051 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002052 return stream->dropBuffers(dropping);
2053}
2054
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002055/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 * Camera3Device private methods
2057 */
2058
2059sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002060 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002063 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002064 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065
2066 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002067 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002068 if (inputStreams.count > 0) {
2069 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002070 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002071 CLOGE("Request references unknown input stream %d",
2072 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073 return NULL;
2074 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002075
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002077 SET_ERR_L("%s: input stream %d is not configured!",
2078 __FUNCTION__, mInputStream->getId());
2079 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002081 // Check if stream prepare is blocking requests.
2082 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002083 CLOGE("Request references an input stream that's being prepared!");
2084 return NULL;
2085 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002086
2087 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002088 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002089 }
2090
2091 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002092 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002094 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002095 return NULL;
2096 }
2097
2098 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002099 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2100 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002101 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002102 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103 return NULL;
2104 }
Zhijun He5d677d12016-05-29 16:52:39 -07002105 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002106 auto iter = surfaceMap.find(streams.data.i32[i]);
2107 if (iter != surfaceMap.end()) {
2108 const std::vector<size_t>& surfaces = iter->second;
2109 for (const auto& surface : surfaces) {
2110 if (stream->isConsumerConfigurationDeferred(surface)) {
2111 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2112 "due to deferred consumer", stream->getId(), surface);
2113 return NULL;
2114 }
2115 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002116 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002117 }
2118
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002120 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2121 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002123 // Check if stream prepare is blocking requests.
2124 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002125 CLOGE("Request references an output stream that's being prepared!");
2126 return NULL;
2127 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128
2129 newRequest->mOutputStreams.push(stream);
2130 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002131 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002132 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002134 auto rotateAndCropEntry =
2135 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2136 if (rotateAndCropEntry.count > 0 &&
2137 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2138 newRequest->mRotateAndCropAuto = true;
2139 } else {
2140 newRequest->mRotateAndCropAuto = false;
2141 }
2142
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002143 auto zoomRatioEntry =
2144 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2145 if (zoomRatioEntry.count > 0 &&
2146 zoomRatioEntry.data.f[0] == 1.0f) {
2147 newRequest->mZoomRatioIs1x = true;
2148 } else {
2149 newRequest->mZoomRatioIs1x = false;
2150 }
2151
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002152 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002153 for (auto& settings : newRequest->mSettingsList) {
2154 auto testPatternModeEntry =
2155 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2156 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2157 testPatternModeEntry.data.i32[0] :
2158 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002159
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002160 auto testPatternDataEntry =
2161 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2162 if (testPatternDataEntry.count >= 4) {
2163 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2164 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2165 } else {
2166 settings.mOriginalTestPatternData[0] = 0;
2167 settings.mOriginalTestPatternData[1] = 0;
2168 settings.mOriginalTestPatternData[2] = 0;
2169 settings.mOriginalTestPatternData[3] = 0;
2170 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002171 }
2172 }
2173
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002174 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002175}
2176
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002177void Camera3Device::cancelStreamsConfigurationLocked() {
2178 int res = OK;
2179 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2180 res = mInputStream->cancelConfiguration();
2181 if (res != OK) {
2182 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2183 mInputStream->getId(), strerror(-res), res);
2184 }
2185 }
2186
2187 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002188 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002189 if (outputStream->isConfiguring()) {
2190 res = outputStream->cancelConfiguration();
2191 if (res != OK) {
2192 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2193 outputStream->getId(), strerror(-res), res);
2194 }
2195 }
2196 }
2197
2198 // Return state to that at start of call, so that future configures
2199 // properly clean things up
2200 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2201 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002202
2203 res = mPreparerThread->resume();
2204 if (res != OK) {
2205 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2206 }
2207}
2208
Emilian Peev0d0191e2020-04-21 17:01:18 -07002209bool Camera3Device::checkAbandonedStreamsLocked() {
2210 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2211 return true;
2212 }
2213
2214 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2215 auto stream = mOutputStreams[i];
2216 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2217 return true;
2218 }
2219 }
2220
2221 return false;
2222}
2223
Emilian Peev3bead5f2020-05-28 17:29:08 -07002224bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002225 ATRACE_CALL();
2226 bool ret = false;
2227
Shuzhen Wang316781a2020-08-18 18:11:01 -07002228 nsecs_t startTime = systemTime();
2229
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002230 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002231 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2232
2233 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002234 if (checkAbandonedStreamsLocked()) {
2235 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2236 __FUNCTION__);
2237 return true;
2238 }
2239
Emilian Peev3bead5f2020-05-28 17:29:08 -07002240 status_t rc = NO_ERROR;
2241 bool markClientActive = false;
2242 if (mStatus == STATUS_ACTIVE) {
2243 markClientActive = true;
2244 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002245
2246 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2247 }
2248
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002249 if (rc == NO_ERROR) {
2250 mNeedConfig = true;
2251 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2252 if (rc == NO_ERROR) {
2253 ret = true;
2254 mPauseStateNotify = false;
2255 //Moving to active state while holding 'mLock' is important.
2256 //There could be pending calls to 'create-/deleteStream' which
2257 //will trigger another stream configuration while the already
2258 //present streams end up with outstanding buffers that will
2259 //not get drained.
2260 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002261 } else if (rc == DEAD_OBJECT) {
2262 // DEAD_OBJECT can be returned if either the consumer surface is
2263 // abandoned, or the HAL has died.
2264 // - If the HAL has died, configureStreamsLocked call will set
2265 // device to error state,
2266 // - If surface is abandoned, we should not set device to error
2267 // state.
2268 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002269 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002270 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002271 }
2272 } else {
2273 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2274 }
2275
Austin Borger74fca042022-05-23 12:41:21 -07002276 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002277 ns2ms(systemTime() - startTime));
2278
Emilian Peev3bead5f2020-05-28 17:29:08 -07002279 if (markClientActive) {
2280 mStatusTracker->markComponentActive(clientStatusId);
2281 }
2282
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002283 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002284}
2285
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002286status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002287 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288 ATRACE_CALL();
2289 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002290
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002291 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002292 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293 return INVALID_OPERATION;
2294 }
2295
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002296 if (operatingMode < 0) {
2297 CLOGE("Invalid operating mode: %d", operatingMode);
2298 return BAD_VALUE;
2299 }
2300
2301 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002302 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002303
2304 if (mOperatingMode != operatingMode) {
2305 mNeedConfig = true;
2306 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2307 mOperatingMode = operatingMode;
2308 }
2309
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002310 // Reset min expected duration when session is reconfigured.
2311 mMinExpectedDuration = 0;
2312
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002313 // In case called from configureStreams, abort queued input buffers not belonging to
2314 // any pending requests.
2315 if (mInputStream != NULL && notifyRequestThread) {
2316 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002317 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002318 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002319 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002320 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002321 if (res != OK) {
2322 // Exhausted acquiring all input buffers.
2323 break;
2324 }
2325
Emilian Peevf4816702020-04-03 15:44:51 -07002326 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002327 res = mInputStream->returnInputBuffer(inputBuffer);
2328 if (res != OK) {
2329 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2330 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2331 }
2332 }
2333 }
2334
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002335 if (!mNeedConfig) {
2336 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2337 return OK;
2338 }
2339
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002340 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002341 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002342 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2343 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002344 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002345 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002346 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002347 }
2348
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002349 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002350 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002352 mPreparerThread->pause();
2353
Emilian Peevf4816702020-04-03 15:44:51 -07002354 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002355 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002357 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002358
Emilian Peevf4816702020-04-03 15:44:51 -07002359 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002361 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002362
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363
2364 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002365 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366 inputStream = mInputStream->startConfiguration();
2367 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002368 CLOGE("Can't start input stream configuration");
2369 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370 return INVALID_OPERATION;
2371 }
2372 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002373
2374 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375 }
2376
Shuzhen Wang99080502021-03-07 21:08:20 -08002377 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002378 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002380
2381 // Don't configure bidi streams twice, nor add them twice to the list
2382 if (mOutputStreams[i].get() ==
2383 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2384
2385 config.num_streams--;
2386 continue;
2387 }
2388
Emilian Peevf4816702020-04-03 15:44:51 -07002389 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002390 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002392 CLOGE("Can't start output stream configuration");
2393 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 return INVALID_OPERATION;
2395 }
2396 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002397
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002398 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002399 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2400 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002401 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2402 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002403 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2404 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002405 } else if (outputStream->data_space ==
2406 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2407 bufferSizes[k] = outputStream->width * outputStream->height;
2408 } else {
2409 ALOGW("%s: Blob dataSpace %d not supported",
2410 __FUNCTION__, outputStream->data_space);
2411 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002412 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002413
2414 if (mOutputStreams[i]->isMultiResolution()) {
2415 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2416 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2417 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2418 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002419
2420 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2421 composerSurfacePresent = true;
2422 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423 }
2424
2425 config.streams = streams.editArray();
2426
2427 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002428 // max_buffers, usage, and priv fields, as well as data_space and format
2429 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002430
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002431 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002432 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002433 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002435 if (res == BAD_VALUE) {
2436 // HAL rejected this set of streams as unsupported, clean up config
2437 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002438 CLOGE("Set of requested inputs/outputs not supported by HAL");
2439 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002440 return BAD_VALUE;
2441 } else if (res != OK) {
2442 // Some other kind of error from configure_streams - this is not
2443 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002444 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2445 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 return res;
2447 }
2448
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002449 // Finish all stream configuration immediately.
2450 // TODO: Try to relax this later back to lazy completion, which should be
2451 // faster
2452
Igor Murashkin073f8572013-05-02 14:59:28 -07002453 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002454 bool streamReConfigured = false;
2455 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002456 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002458 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002459 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002460 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2461 return DEAD_OBJECT;
2462 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002463 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002464 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002465 if (streamReConfigured) {
2466 mInterface->onStreamReConfigured(mInputStream->getId());
2467 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002468 }
2469
2470 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002471 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002472 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002473 bool streamReConfigured = false;
2474 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002475 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002476 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002477 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002478 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002479 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2480 return DEAD_OBJECT;
2481 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002482 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002483 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002484 if (streamReConfigured) {
2485 mInterface->onStreamReConfigured(outputStream->getId());
2486 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002487 }
2488 }
2489
Emilian Peeve23f1d92021-09-20 14:56:01 -07002490 mRequestThread->setComposerSurface(composerSurfacePresent);
2491
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002492 // Request thread needs to know to avoid using repeat-last-settings protocol
2493 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002494 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002495 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2496 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002497 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002498
Zhijun He90f7c372016-08-16 16:19:43 -07002499 char value[PROPERTY_VALUE_MAX];
2500 property_get("camera.fifo.disable", value, "0");
2501 int32_t disableFifo = atoi(value);
2502 if (disableFifo != 1) {
2503 // Boost priority of request thread to SCHED_FIFO.
2504 pid_t requestThreadTid = mRequestThread->getTid();
2505 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002506 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002507 if (res != OK) {
2508 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2509 strerror(-res), res);
2510 } else {
2511 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2512 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002513 }
2514
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002515 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002516 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2517 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2518 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2519 sessionParams.unlock(newSessionParams);
2520 mSessionParams.unlock(currentSessionParams);
2521 if (updateSessionParams) {
2522 mSessionParams = sessionParams;
2523 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002525 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002527 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002528 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002529
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002530 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002531
Zhijun He0a210512014-07-24 13:45:15 -07002532 // tear down the deleted streams after configure streams.
2533 mDeletedStreams.clear();
2534
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002535 auto rc = mPreparerThread->resume();
2536 if (rc != OK) {
2537 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2538 return rc;
2539 }
2540
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002541 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002542 mRequestBufferSM.onStreamsConfigured();
2543 }
2544
Cliff Wu3b268182021-07-06 15:44:43 +08002545 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002546 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002547 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002548 // configure the injection streams.
2549 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002550 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002551 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2552 res = mInjectionMethods->injectCamera(config, bufferSizes);
2553 if (res != OK) {
2554 ALOGE("Can't finish inject camera process!");
2555 return res;
2556 }
Cliff Wu3b268182021-07-06 15:44:43 +08002557 } else {
2558 // First run configureStreamsLocked() and then call injectCamera() case:
2559 // If the stream configuration has been completed and camera deive is active, but the
2560 // injection camera has not been injected yet, we need to store the stream configuration of
2561 // the internal camera (because the stream configuration of the injection camera is based
2562 // on the internal camera). When injecting occurs later, this configuration can be used by
2563 // the injection camera.
2564 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2565 " injection camera has not been injected yet.", __FUNCTION__);
2566 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002567 }
2568
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002569 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002570}
2571
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002572status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002573 ATRACE_CALL();
2574 status_t res;
2575
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002576 if (mFakeStreamId != NO_STREAM) {
2577 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002578 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002579 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002580 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002581 return INVALID_OPERATION;
2582 }
2583
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002584 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002585
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002586 sp<Camera3OutputStreamInterface> fakeStream =
2587 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002588
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002589 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002590 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002591 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002592 return res;
2593 }
2594
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002595 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002596 mNextStreamId++;
2597
2598 return OK;
2599}
2600
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002601status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002602 ATRACE_CALL();
2603 status_t res;
2604
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002605 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002606 if (mOutputStreams.size() == 1) return OK;
2607
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002608 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002609
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002610 // Ok, have a fake stream and there's at least one other output stream,
2611 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002612
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002613 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002614 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002615 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616 return INVALID_OPERATION;
2617 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002618 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619
2620 // Free up the stream endpoint so that it can be used by some other stream
2621 res = deletedStream->disconnect();
2622 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002623 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 // fall through since we want to still list the stream as deleted.
2625 }
2626 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002627 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002628
2629 return res;
2630}
2631
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002632void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002633 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002634 Mutex::Autolock l(mLock);
2635 va_list args;
2636 va_start(args, fmt);
2637
2638 setErrorStateLockedV(fmt, args);
2639
2640 va_end(args);
2641}
2642
2643void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002644 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002645 Mutex::Autolock l(mLock);
2646 setErrorStateLockedV(fmt, args);
2647}
2648
2649void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2650 va_list args;
2651 va_start(args, fmt);
2652
2653 setErrorStateLockedV(fmt, args);
2654
2655 va_end(args);
2656}
2657
2658void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002659 // Print out all error messages to log
2660 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002661 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002662
2663 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002664 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002665
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002666 mErrorCause = errorCause;
2667
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002668 if (mRequestThread != nullptr) {
2669 mRequestThread->setPaused(true);
2670 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002671 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002672
2673 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002674 sp<NotificationListener> listener = mListener.promote();
2675 if (listener != NULL) {
2676 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002677 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002678 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002679 }
2680
2681 // Save stack trace. View by dumping it later.
2682 CameraTraces::saveTrace();
2683 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002684}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002685
2686/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002687 * In-flight request management
2688 */
2689
Jianing Weicb0652e2014-03-12 18:29:36 -07002690status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002691 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002692 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002693 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002694 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2695 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002696 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002697 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002698 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002699
2700 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002701 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002702 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002703 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2704 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002705 if (res < 0) return res;
2706
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002707 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002708 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2709 // avoid a deadlock during reprocess requests.
2710 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002711 if (mStatusTracker != nullptr) {
2712 mStatusTracker->markComponentActive(mInFlightStatusId);
2713 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002714 }
2715
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002716 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002717 return OK;
2718}
2719
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002720void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002721 // Indicate idle inFlightMap to the status tracker
2722 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002723 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002724 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2725 // avoid a deadlock during reprocess requests.
2726 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002727 if (mStatusTracker != nullptr) {
2728 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2729 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002730 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002731 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002732}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002733
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002734void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002735 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002736 // something has likely gone wrong. This might still be legit only if application send in
2737 // a long burst of long exposure requests.
2738 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2739 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2740 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2741 mInFlightMap.size(), mExpectedInflightDuration);
2742 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2743 kInFlightWarnLimitHighSpeed) {
2744 CLOGW("In-flight list too large for high speed configuration: %zu,"
2745 "total inflight duration %" PRIu64,
2746 mInFlightMap.size(), mExpectedInflightDuration);
2747 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002748 }
2749}
2750
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002751void Camera3Device::onInflightMapFlushedLocked() {
2752 mExpectedInflightDuration = 0;
2753}
2754
2755void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002756 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002757 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2758 mInFlightMap.removeItemsAt(idx, 1);
2759
2760 onInflightEntryRemovedLocked(duration);
2761}
2762
2763
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002764void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002765 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002766 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002767 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002768 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002769 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002770 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002771
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002772 FlushInflightReqStates states {
2773 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002774 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002775
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002776 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002777}
2778
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002779CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002780 ALOGV("%s", __FUNCTION__);
2781
Igor Murashkin1e479c02013-09-06 16:55:14 -07002782 CameraMetadata retVal;
2783
2784 if (mRequestThread != NULL) {
2785 retVal = mRequestThread->getLatestRequest();
2786 }
2787
Igor Murashkin1e479c02013-09-06 16:55:14 -07002788 return retVal;
2789}
2790
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002791void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002792 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002793 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002794 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2795 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002796
2797 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002798 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002799}
2800
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002801void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002802 std::vector<native_handle_t*> *handles, bool closeFd) {
2803 if (handles == nullptr) {
2804 return;
2805 }
2806 if (closeFd) {
2807 for (auto& handle : *handles) {
2808 native_handle_close(handle);
2809 }
2810 }
2811 for (auto& handle : *handles) {
2812 native_handle_delete(handle);
2813 }
2814 handles->clear();
2815 return;
2816}
2817
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002818/**
2819 * HalInterface inner class methods
2820 */
2821
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002822void Camera3Device::HalInterface::getInflightBufferKeys(
2823 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002824 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002825 return;
2826}
2827
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002828void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2829 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002830 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002831 return;
2832}
2833
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002834bool Camera3Device::HalInterface::verifyBufferIds(
2835 int32_t streamId, std::vector<uint64_t>& bufIds) {
2836 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002837}
2838
2839status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002840 int32_t frameNumber, int32_t streamId,
2841 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002842 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002843}
2844
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002845status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002846 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002847 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002848}
2849
2850// Find and pop a buffer_handle_t based on bufferId
2851status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002852 uint64_t bufferId,
2853 /*out*/ buffer_handle_t** buffer,
2854 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002855 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002856}
2857
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002858std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2859 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002860 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002861}
2862
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002863uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2864 const native_handle_t* handle) {
2865 return mBufferRecords.removeOneBufferCache(streamId, handle);
2866}
2867
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002868void Camera3Device::HalInterface::onBufferFreed(
2869 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002870 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2871 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2872 if (bufferId != BUFFER_ID_NO_BUFFER) {
2873 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002874 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002875}
2876
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002877void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002878 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2879 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2880 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002881 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2882 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002883}
2884
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002885/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886 * RequestThread inner class methods
2887 */
2888
2889Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002890 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002891 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002892 bool useHalBufManager,
2893 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002894 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002895 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002896 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002897 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002898 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002899 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002900 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002901 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002902 mReconfigured(false),
2903 mDoPause(false),
2904 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002905 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002906 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002907 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002908 mCurrentAfTriggerId(0),
2909 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002910 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002911 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002912 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002913 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002914 mRepeatingLastFrameNumber(
2915 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002916 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002917 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002918 mRequestLatency(kRequestLatencyBinSize),
2919 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002920 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002921 mUseHalBufManager(useHalBufManager),
2922 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002923 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002924}
2925
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002926Camera3Device::RequestThread::~RequestThread() {}
2927
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002928void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002929 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002930 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002931 Mutex::Autolock l(mRequestLock);
2932 mListener = listener;
2933}
2934
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002935void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002936 const CameraMetadata& sessionParams,
2937 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002938 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002939 Mutex::Autolock l(mRequestLock);
2940 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002941 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002942 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002943 // Prepare video stream for high speed recording.
2944 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002945 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002946}
2947
Jianing Wei90e59c92014-03-12 18:29:36 -07002948status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002949 List<sp<CaptureRequest> > &requests,
2950 /*out*/
2951 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002952 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002953 Mutex::Autolock l(mRequestLock);
2954 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2955 ++it) {
2956 mRequestQueue.push_back(*it);
2957 }
2958
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002959 if (lastFrameNumber != NULL) {
2960 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2961 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2962 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2963 *lastFrameNumber);
2964 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002965
Jianing Wei90e59c92014-03-12 18:29:36 -07002966 unpauseForNewRequests();
2967
2968 return OK;
2969}
2970
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002971
2972status_t Camera3Device::RequestThread::queueTrigger(
2973 RequestTrigger trigger[],
2974 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002975 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002976 Mutex::Autolock l(mTriggerMutex);
2977 status_t ret;
2978
2979 for (size_t i = 0; i < count; ++i) {
2980 ret = queueTriggerLocked(trigger[i]);
2981
2982 if (ret != OK) {
2983 return ret;
2984 }
2985 }
2986
2987 return OK;
2988}
2989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2991 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002992 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002993 if (d != nullptr) return d->mId;
2994 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002995}
2996
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002997status_t Camera3Device::RequestThread::queueTriggerLocked(
2998 RequestTrigger trigger) {
2999
3000 uint32_t tag = trigger.metadataTag;
3001 ssize_t index = mTriggerMap.indexOfKey(tag);
3002
3003 switch (trigger.getTagType()) {
3004 case TYPE_BYTE:
3005 // fall-through
3006 case TYPE_INT32:
3007 break;
3008 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003009 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3010 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003011 return INVALID_OPERATION;
3012 }
3013
3014 /**
3015 * Collect only the latest trigger, since we only have 1 field
3016 * in the request settings per trigger tag, and can't send more than 1
3017 * trigger per request.
3018 */
3019 if (index != NAME_NOT_FOUND) {
3020 mTriggerMap.editValueAt(index) = trigger;
3021 } else {
3022 mTriggerMap.add(tag, trigger);
3023 }
3024
3025 return OK;
3026}
3027
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003028status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003029 const RequestList &requests,
3030 /*out*/
3031 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003032 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003033 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003034 if (lastFrameNumber != NULL) {
3035 *lastFrameNumber = mRepeatingLastFrameNumber;
3036 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003037 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003038 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003039 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3040 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003041
3042 unpauseForNewRequests();
3043
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003044 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003045 return OK;
3046}
3047
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003048bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003049 if (mRepeatingRequests.empty()) {
3050 return false;
3051 }
3052 int32_t requestId = requestIn->mResultExtras.requestId;
3053 const RequestList &repeatRequests = mRepeatingRequests;
3054 // All repeating requests are guaranteed to have same id so only check first quest
3055 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3056 return (firstRequest->mResultExtras.requestId == requestId);
3057}
3058
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003059status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003061 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003062 return clearRepeatingRequestsLocked(lastFrameNumber);
3063
3064}
3065
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003066status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3067 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003068 std::vector<int32_t> streamIds;
3069 for (const auto& request : mRepeatingRequests) {
3070 for (const auto& stream : request->mOutputStreams) {
3071 streamIds.push_back(stream->getId());
3072 }
3073 }
3074
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003075 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003076 if (lastFrameNumber != NULL) {
3077 *lastFrameNumber = mRepeatingLastFrameNumber;
3078 }
Emilian Peev2295df72021-11-12 18:14:10 -08003079
3080 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003083 return OK;
3084}
3085
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003086status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003087 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003088 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003089 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003090 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003091
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003092 // Send errors for all requests pending in the request queue, including
3093 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003094 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003095 if (listener != NULL) {
3096 for (RequestList::iterator it = mRequestQueue.begin();
3097 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003098 // Abort the input buffers for reprocess requests.
3099 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003100 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003101 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003102 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003103 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003104 if (res != OK) {
3105 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3106 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3107 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003108 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003109 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3110 if (res != OK) {
3111 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3112 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3113 }
3114 }
3115 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003116 // Set the frame number this request would have had, if it
3117 // had been submitted; this frame number will not be reused.
3118 // The requestId and burstId fields were set when the request was
3119 // submitted originally (in convertMetadataListToRequestListLocked)
3120 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003121 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003122 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003123 }
3124 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003125 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003126
3127 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003128 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003129 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003130 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003131 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003132 return OK;
3133}
3134
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003135status_t Camera3Device::RequestThread::flush() {
3136 ATRACE_CALL();
3137 Mutex::Autolock l(mFlushLock);
3138
Emilian Peev08dd2452017-04-06 16:55:14 +01003139 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003140}
3141
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003142void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003143 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003144 Mutex::Autolock l(mPauseLock);
3145 mDoPause = paused;
3146 mDoPauseSignal.signal();
3147}
3148
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003149status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3150 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003151 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003152 Mutex::Autolock l(mLatestRequestMutex);
3153 status_t res;
3154 while (mLatestRequestId != requestId) {
3155 nsecs_t startTime = systemTime();
3156
3157 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3158 if (res != OK) return res;
3159
3160 timeout -= (systemTime() - startTime);
3161 }
3162
3163 return OK;
3164}
3165
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003166void Camera3Device::RequestThread::requestExit() {
3167 // Call parent to set up shutdown
3168 Thread::requestExit();
3169 // The exit from any possible waits
3170 mDoPauseSignal.signal();
3171 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003172
3173 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3174 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003175}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003176
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003177void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003178 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003179 bool surfaceAbandoned = false;
3180 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003181 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003182 {
3183 Mutex::Autolock l(mRequestLock);
3184 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3185 // repeating requests.
3186 for (const auto& request : mRepeatingRequests) {
3187 for (const auto& s : request->mOutputStreams) {
3188 if (s->isAbandoned()) {
3189 surfaceAbandoned = true;
3190 clearRepeatingRequestsLocked(&lastFrameNumber);
3191 break;
3192 }
3193 }
3194 if (surfaceAbandoned) {
3195 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003196 }
3197 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003198 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003199 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003200
3201 if (listener != NULL && surfaceAbandoned) {
3202 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003203 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003204}
3205
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003206bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003207 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003208 status_t res;
3209 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003210 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003211 uint32_t numRequestProcessed = 0;
3212 for (size_t i = 0; i < batchSize; i++) {
3213 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003214 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003215 }
3216
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003217 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3218
3219 bool triggerRemoveFailed = false;
3220 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3221 for (size_t i = 0; i < numRequestProcessed; i++) {
3222 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3223 nextRequest.submitted = true;
3224
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003225 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003226
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003227 if (!triggerRemoveFailed) {
3228 // Remove any previously queued triggers (after unlock)
3229 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3230 if (removeTriggerRes != OK) {
3231 triggerRemoveFailed = true;
3232 triggerFailedRequest = nextRequest;
3233 }
3234 }
3235 }
3236
3237 if (triggerRemoveFailed) {
3238 SET_ERR("RequestThread: Unable to remove triggers "
3239 "(capture request %d, HAL device: %s (%d)",
3240 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3241 cleanUpFailedRequests(/*sendRequestError*/ false);
3242 return false;
3243 }
3244
3245 if (res != OK) {
3246 // Should only get a failure here for malformed requests or device-level
3247 // errors, so consider all errors fatal. Bad metadata failures should
3248 // come through notify.
3249 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3250 mNextRequests[numRequestProcessed].halRequest.frame_number,
3251 strerror(-res), res);
3252 cleanUpFailedRequests(/*sendRequestError*/ false);
3253 return false;
3254 }
3255 return true;
3256}
3257
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003258Camera3Device::RequestThread::ExpectedDurationInfo
3259 Camera3Device::RequestThread::calculateExpectedDurationRange(
3260 const camera_metadata_t *request) {
3261 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003262 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003263 InFlightRequest::kDefaultMaxExpectedDuration,
3264 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003265 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3266 find_camera_metadata_ro_entry(request,
3267 ANDROID_CONTROL_AE_MODE,
3268 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003269 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003270
3271 switch (e.data.u8[0]) {
3272 case ANDROID_CONTROL_AE_MODE_OFF:
3273 find_camera_metadata_ro_entry(request,
3274 ANDROID_SENSOR_EXPOSURE_TIME,
3275 &e);
3276 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003277 expectedDurationInfo.minDuration = e.data.i64[0];
3278 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003279 }
3280 find_camera_metadata_ro_entry(request,
3281 ANDROID_SENSOR_FRAME_DURATION,
3282 &e);
3283 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003284 expectedDurationInfo.minDuration =
3285 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3286 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003287 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003288 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003289 break;
3290 default:
3291 find_camera_metadata_ro_entry(request,
3292 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3293 &e);
3294 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003295 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3296 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003297 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003298 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003299 break;
3300 }
3301
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003302 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003303}
3304
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003305bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3306 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3307 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3308 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3309 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3310 return true;
3311 }
3312
3313 return false;
3314}
3315
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003316void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3317 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003318 camera_capture_request_t& halRequest = nextRequest.halRequest;
3319 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003320 Mutex::Autolock al(mLatestRequestMutex);
3321
Shuzhen Wang83bff122020-11-20 15:51:39 -08003322 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003323 mLatestRequest.acquire(cloned);
3324
3325 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003326 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3327 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3328 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003329 CameraMetadata(cloned));
3330 }
3331
3332 sp<Camera3Device> parent = mParent.promote();
3333 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003334 int32_t inputStreamId = -1;
3335 if (halRequest.input_buffer != nullptr) {
3336 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3337 }
3338
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003339 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003340 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003341 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3342 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003343 }
3344 }
3345
Shuzhen Wang83bff122020-11-20 15:51:39 -08003346 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003347 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003348 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003349 }
3350
Shuzhen Wang83bff122020-11-20 15:51:39 -08003351 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003352}
3353
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003354bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3355 ATRACE_CALL();
3356 bool updatesDetected = false;
3357
Emilian Peev4ec17882019-01-24 17:16:58 -08003358 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003359 for (auto tag : mSessionParamKeys) {
3360 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003361 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003362
3363 if (entry.count > 0) {
3364 bool isDifferent = false;
3365 if (lastEntry.count > 0) {
3366 // Have a last value, compare to see if changed
3367 if (lastEntry.type == entry.type &&
3368 lastEntry.count == entry.count) {
3369 // Same type and count, compare values
3370 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3371 size_t entryBytes = bytesPerValue * lastEntry.count;
3372 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3373 if (cmp != 0) {
3374 isDifferent = true;
3375 }
3376 } else {
3377 // Count or type has changed
3378 isDifferent = true;
3379 }
3380 } else {
3381 // No last entry, so always consider to be different
3382 isDifferent = true;
3383 }
3384
3385 if (isDifferent) {
3386 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003387 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3388 updatesDetected = true;
3389 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003390 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003391 }
3392 } else if (lastEntry.count > 0) {
3393 // Value has been removed
3394 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003395 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003396 updatesDetected = true;
3397 }
3398 }
3399
Emilian Peev4ec17882019-01-24 17:16:58 -08003400 bool reconfigureRequired;
3401 if (updatesDetected) {
3402 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3403 updatedParams);
3404 mLatestSessionParams = updatedParams;
3405 } else {
3406 reconfigureRequired = false;
3407 }
3408
3409 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003410}
3411
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003412bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003413 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003414 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003415 // Any function called from threadLoop() must not hold mInterfaceLock since
3416 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3417 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003418
3419 // Handle paused state.
3420 if (waitIfPaused()) {
3421 return true;
3422 }
3423
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003424 // Wait for the next batch of requests.
3425 waitForNextRequestBatch();
3426 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003427 return true;
3428 }
3429
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003430 // Get the latest request ID, if any
3431 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003432 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003433 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003434 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003435 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003436 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003437 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3438 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003439 }
3440
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003441 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3442 // or a single request from streaming or burst. In either case the first element
3443 // should contain the latest camera settings that we need to check for any session
3444 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003445 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003446 res = OK;
3447
3448 //Input stream buffers are already acquired at this point so an input stream
3449 //will not be able to move to idle state unless we force it.
3450 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3451 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3452 if (res != OK) {
3453 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3454 cleanUpFailedRequests(/*sendRequestError*/ false);
3455 return false;
3456 }
3457 }
3458
3459 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003460 sp<Camera3Device> parent = mParent.promote();
3461 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003462 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3463 if (statusTracker != nullptr) {
3464 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3465 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003466 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003467 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003468 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003469
3470 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3471 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3472 if (res != OK) {
3473 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3474 cleanUpFailedRequests(/*sendRequestError*/ false);
3475 return false;
3476 }
3477 }
3478 }
3479 }
3480
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003481 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003482 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003483 if (res == TIMED_OUT) {
3484 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003485 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003486 // Check if any stream is abandoned.
3487 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003488 return true;
3489 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003490 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003491 return false;
3492 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003493
Zhijun Hecc27e112013-10-03 16:12:43 -07003494 // Inform waitUntilRequestProcessed thread of a new request ID
3495 {
3496 Mutex::Autolock al(mLatestRequestMutex);
3497
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003498 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003499 mLatestRequestSignal.signal();
3500 }
3501
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003502 // Submit a batch of requests to HAL.
3503 // Use flush lock only when submitting multilple requests in a batch.
3504 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3505 // which may take a long time to finish so synchronizing flush() and
3506 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3507 // For now, only synchronize for high speed recording and we should figure something out for
3508 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003509 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003510
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003511 if (useFlushLock) {
3512 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003513 }
3514
Zhijun Hef0645c12016-08-02 00:58:11 -07003515 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003516 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003517
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003518 sp<Camera3Device> parent = mParent.promote();
3519 if (parent != nullptr) {
3520 parent->mRequestBufferSM.onSubmittingRequest();
3521 }
3522
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003523 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003524 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003525 submitRequestSuccess = sendRequestsBatch();
3526
Shuzhen Wang686f6442017-06-20 16:16:04 -07003527 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3528 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003529
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003530 if (useFlushLock) {
3531 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003532 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003533
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003534 // Unset as current request
3535 {
3536 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003537 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003538 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003539 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003540
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003541 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003542}
3543
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003544status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3545 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3546 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3547 ANDROID_SCALER_CROP_REGION_SET};
3548 if (request == nullptr) {
3549 ALOGE("%s request metadata nullptr", __FUNCTION__);
3550 return BAD_VALUE;
3551 }
3552 status_t res = OK;
3553 for (const auto &key : kFwkOnlyRegionKeys) {
3554 if (request->exists(key)) {
3555 res = request->erase(key);
3556 if (res != OK) {
3557 return res;
3558 }
3559 }
3560 }
3561 return OK;
3562}
3563
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003564status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003565 ATRACE_CALL();
3566
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003567 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003568 for (size_t i = 0; i < mNextRequests.size(); i++) {
3569 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003570 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003571 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3572 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003573
3574 // Prepare a request to HAL
3575 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3576
3577 // Insert any queued triggers (before metadata is locked)
3578 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003579 if (res < 0) {
3580 SET_ERR("RequestThread: Unable to insert triggers "
3581 "(capture request %d, HAL device: %s (%d)",
3582 halRequest->frame_number, strerror(-res), res);
3583 return INVALID_OPERATION;
3584 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003585
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003586 int triggerCount = res;
3587 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3588 mPrevTriggers = triggerCount;
3589
Emilian Peeve23f1d92021-09-20 14:56:01 -07003590 // Do not override rotate&crop for stream configurations that include
3591 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3592 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3593 bool rotateAndCropChanged = mComposerOutput ? false :
3594 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003595 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003596
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003597 // If the request is the same as last, or we had triggers now or last time or
3598 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003599 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003600 (mPrevRequest != captureRequest || triggersMixedIn ||
3601 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003602 // Request settings are all the same within one batch, so only treat the first
3603 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003604 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003605 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003606 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003607 /**
3608 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003609 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003610 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003611 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003612 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003613 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003614 "(capture request %d, HAL device: %s (%d)",
3615 halRequest->frame_number, strerror(-res), res);
3616 return INVALID_OPERATION;
3617 }
3618
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003619 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003620 sp<Camera3Device> parent = mParent.promote();
3621 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003622 List<PhysicalCameraSettings>::iterator it;
3623 for (it = captureRequest->mSettingsList.begin();
3624 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003625 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3626 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003627 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3628 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3629 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3630 res);
3631 return INVALID_OPERATION;
3632 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003633 continue;
3634 }
3635
3636 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3637 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3638 updateCaptureRequest(&(it->metadata));
3639 if (res != OK) {
3640 SET_ERR("RequestThread: Unable to correct capture requests "
3641 "for scaler crop region and metering regions for request "
3642 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3643 res);
3644 return INVALID_OPERATION;
3645 }
3646 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003647 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3648 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3649 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3650 res);
3651 return INVALID_OPERATION;
3652 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003653 }
3654 }
3655
3656 // Correct metadata regions for distortion correction if enabled
3657 for (it = captureRequest->mSettingsList.begin();
3658 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003659 if (parent->mDistortionMappers.find(it->cameraId) ==
3660 parent->mDistortionMappers.end()) {
3661 continue;
3662 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003663
3664 if (!captureRequest->mDistortionCorrectionUpdated) {
3665 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3666 &(it->metadata));
3667 if (res != OK) {
3668 SET_ERR("RequestThread: Unable to correct capture requests "
3669 "for lens distortion for request %d: %s (%d)",
3670 halRequest->frame_number, strerror(-res), res);
3671 return INVALID_OPERATION;
3672 }
3673 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003674 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003675 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003676
3677 for (it = captureRequest->mSettingsList.begin();
3678 it != captureRequest->mSettingsList.end(); it++) {
3679 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3680 parent->mZoomRatioMappers.end()) {
3681 continue;
3682 }
3683
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003684 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003685 cameraIdsWithZoom.insert(it->cameraId);
3686 }
3687
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003688 if (!captureRequest->mZoomRatioUpdated) {
3689 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3690 &(it->metadata));
3691 if (res != OK) {
3692 SET_ERR("RequestThread: Unable to correct capture requests "
3693 "for zoom ratio for request %d: %s (%d)",
3694 halRequest->frame_number, strerror(-res), res);
3695 return INVALID_OPERATION;
3696 }
3697 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003698 }
3699 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003700 if (captureRequest->mRotateAndCropAuto &&
3701 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003702 for (it = captureRequest->mSettingsList.begin();
3703 it != captureRequest->mSettingsList.end(); it++) {
3704 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3705 if (mapper != parent->mRotateAndCropMappers.end()) {
3706 res = mapper->second.updateCaptureRequest(&(it->metadata));
3707 if (res != OK) {
3708 SET_ERR("RequestThread: Unable to correct capture requests "
3709 "for rotate-and-crop for request %d: %s (%d)",
3710 halRequest->frame_number, strerror(-res), res);
3711 return INVALID_OPERATION;
3712 }
3713 }
3714 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003715 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003716 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003717 }
3718 }
3719
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003720 /**
3721 * The request should be presorted so accesses in HAL
3722 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3723 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003724 captureRequest->mSettingsList.begin()->metadata.sort();
3725 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003726 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003727 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003728 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3729
3730 IF_ALOGV() {
3731 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3732 find_camera_metadata_ro_entry(
3733 halRequest->settings,
3734 ANDROID_CONTROL_AF_TRIGGER,
3735 &e
3736 );
3737 if (e.count > 0) {
3738 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3739 __FUNCTION__,
3740 halRequest->frame_number,
3741 e.data.u8[0]);
3742 }
3743 }
3744 } else {
3745 // leave request.settings NULL to indicate 'reuse latest given'
3746 ALOGVV("%s: Request settings are REUSED",
3747 __FUNCTION__);
3748 }
3749
Emilian Peevaebbe412018-01-15 13:53:24 +00003750 if (captureRequest->mSettingsList.size() > 1) {
3751 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3752 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003753 if (newRequest) {
3754 halRequest->physcam_settings =
3755 new const camera_metadata* [halRequest->num_physcam_settings];
3756 } else {
3757 halRequest->physcam_settings = nullptr;
3758 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003759 auto it = ++captureRequest->mSettingsList.begin();
3760 size_t i = 0;
3761 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3762 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003763 if (newRequest) {
3764 it->metadata.sort();
3765 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3766 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003767 }
3768 }
3769
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003770 uint32_t totalNumBuffers = 0;
3771
3772 // Fill in buffers
3773 if (captureRequest->mInputStream != NULL) {
3774 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003775
3776 halRequest->input_width = captureRequest->mInputBufferSize.width;
3777 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003778 totalNumBuffers += 1;
3779 } else {
3780 halRequest->input_buffer = NULL;
3781 }
3782
Emilian Peevf4816702020-04-03 15:44:51 -07003783 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003784 captureRequest->mOutputStreams.size());
3785 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003786 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003787
3788 sp<Camera3Device> parent = mParent.promote();
3789 if (parent == NULL) {
3790 // Should not happen, and nowhere to send errors to, so just log it
3791 CLOGE("RequestThread: Parent is gone");
3792 return INVALID_OPERATION;
3793 }
3794 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3795
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003796 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003797 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003798 sp<Camera3OutputStreamInterface> outputStream =
3799 captureRequest->mOutputStreams.editItemAt(j);
3800 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003801
3802 // Prepare video buffers for high speed recording on the first video request.
3803 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3804 // Only try to prepare video stream on the first video request.
3805 mPrepareVideoStream = false;
3806
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003807 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3808 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003809 while (res == NOT_ENOUGH_DATA) {
3810 res = outputStream->prepareNextBuffer();
3811 }
3812 if (res != OK) {
3813 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3814 __FUNCTION__, strerror(-res), res);
3815 outputStream->cancelPrepare();
3816 }
3817 }
3818
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003819 std::vector<size_t> uniqueSurfaceIds;
3820 res = outputStream->getUniqueSurfaceIds(
3821 captureRequest->mOutputSurfaces[streamId],
3822 &uniqueSurfaceIds);
3823 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3824 if (res != OK && res != INVALID_OPERATION) {
3825 ALOGE("%s: failed to query stream %d unique surface IDs",
3826 __FUNCTION__, streamId);
3827 return res;
3828 }
3829 if (res == OK) {
3830 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3831 }
3832
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003833 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003834 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003835 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003836 return TIMED_OUT;
3837 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003838 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003839 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003840 buffer.stream = outputStream->asHalStream();
3841 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003842 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003843 buffer.acquire_fence = -1;
3844 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003845 // Mark the output stream as unpreparable to block clients from calling
3846 // 'prepare' after this request reaches CameraHal and before the respective
3847 // buffers are requested.
3848 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003849 } else {
3850 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3851 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003852 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003853 if (res != OK) {
3854 // Can't get output buffer from gralloc queue - this could be due to
3855 // abandoned queue or other consumer misbehavior, so not a fatal
3856 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003857 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003858 " %s (%d)", strerror(-res), res);
3859
3860 return TIMED_OUT;
3861 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003862 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003863
3864 {
3865 sp<Camera3Device> parent = mParent.promote();
3866 if (parent != nullptr) {
3867 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3868 for (const auto& settings : captureRequest->mSettingsList) {
3869 if ((streamCameraId.isEmpty() &&
3870 parent->getId() == settings.cameraId.c_str()) ||
3871 streamCameraId == settings.cameraId.c_str()) {
3872 outputStream->fireBufferRequestForFrameNumber(
3873 captureRequest->mResultExtras.frameNumber,
3874 settings.metadata);
3875 }
3876 }
3877 }
3878 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003879
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003880 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003881 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3882 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3883 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3884 } else if (!physicalCameraId.isEmpty()) {
3885 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003886 }
3887 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003888 }
3889 totalNumBuffers += halRequest->num_output_buffers;
3890
3891 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003892 // If this request list is for constrained high speed recording (not
3893 // preview), and the current request is not the last one in the batch,
3894 // do not send callback to the app.
3895 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003896 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003897 hasCallback = false;
3898 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003899 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003900 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003901 const camera_metadata_t* settings = halRequest->settings;
3902 bool shouldUnlockSettings = false;
3903 if (settings == nullptr) {
3904 shouldUnlockSettings = true;
3905 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3906 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003907 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3908 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003909 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003910 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3911 isStillCapture = true;
3912 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3913 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003914
Emilian Peevaf8416e2021-02-04 17:52:43 -08003915 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003916 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003917 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3918 isZslCapture = true;
3919 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003920 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003921 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003922 res = parent->registerInFlight(halRequest->frame_number,
3923 totalNumBuffers, captureRequest->mResultExtras,
3924 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003925 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003926 expectedDurationInfo.minDuration,
3927 expectedDurationInfo.maxDuration,
3928 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003929 requestedPhysicalCameras, isStillCapture, isZslCapture,
3930 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003931 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003932 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003933 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3934 ", burstId = %" PRId32 ".",
3935 __FUNCTION__,
3936 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3937 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003938
3939 if (shouldUnlockSettings) {
3940 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3941 }
3942
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003943 if (res != OK) {
3944 SET_ERR("RequestThread: Unable to register new in-flight request:"
3945 " %s (%d)", strerror(-res), res);
3946 return INVALID_OPERATION;
3947 }
3948 }
3949
3950 return OK;
3951}
3952
Igor Murashkin1e479c02013-09-06 16:55:14 -07003953CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003954 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003955 Mutex::Autolock al(mLatestRequestMutex);
3956
3957 ALOGV("RequestThread::%s", __FUNCTION__);
3958
3959 return mLatestRequest;
3960}
3961
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003962bool Camera3Device::RequestThread::isStreamPending(
3963 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003964 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003965 Mutex::Autolock l(mRequestLock);
3966
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003967 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003968 if (!nextRequest.submitted) {
3969 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3970 if (stream == s) return true;
3971 }
3972 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003973 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003974 }
3975
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003976 for (const auto& request : mRequestQueue) {
3977 for (const auto& s : request->mOutputStreams) {
3978 if (stream == s) return true;
3979 }
3980 if (stream == request->mInputStream) return true;
3981 }
3982
3983 for (const auto& request : mRepeatingRequests) {
3984 for (const auto& s : request->mOutputStreams) {
3985 if (stream == s) return true;
3986 }
3987 if (stream == request->mInputStream) return true;
3988 }
3989
3990 return false;
3991}
Jianing Weicb0652e2014-03-12 18:29:36 -07003992
Emilian Peev40ead602017-09-26 15:46:36 +01003993bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3994 ATRACE_CALL();
3995 Mutex::Autolock l(mRequestLock);
3996
3997 for (const auto& nextRequest : mNextRequests) {
3998 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3999 if (s.first == streamId) {
4000 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4001 if (it != s.second.end()) {
4002 return true;
4003 }
4004 }
4005 }
4006 }
4007
4008 for (const auto& request : mRequestQueue) {
4009 for (const auto& s : request->mOutputSurfaces) {
4010 if (s.first == streamId) {
4011 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4012 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004013 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004014 }
4015 }
4016 }
4017 }
4018
4019 for (const auto& request : mRepeatingRequests) {
4020 for (const auto& s : request->mOutputSurfaces) {
4021 if (s.first == streamId) {
4022 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4023 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004024 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004025 }
4026 }
4027 }
4028 }
4029
4030 return false;
4031}
4032
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004033void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4034 if (!mUseHalBufManager) {
4035 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4036 return;
4037 }
4038
4039 Mutex::Autolock pl(mPauseLock);
4040 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004041 mInterface->signalPipelineDrain(streamIds);
4042 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004043 }
4044 // If request thread is still busy, wait until paused then notify HAL
4045 mNotifyPipelineDrain = true;
4046 mStreamIdsToBeDrained = streamIds;
4047}
4048
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004049void Camera3Device::RequestThread::resetPipelineDrain() {
4050 Mutex::Autolock pl(mPauseLock);
4051 mNotifyPipelineDrain = false;
4052 mStreamIdsToBeDrained.clear();
4053}
4054
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004055void Camera3Device::RequestThread::clearPreviousRequest() {
4056 Mutex::Autolock l(mRequestLock);
4057 mPrevRequest.clear();
4058}
4059
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004060status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4061 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4062 ATRACE_CALL();
4063 Mutex::Autolock l(mTriggerMutex);
4064 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4065 return BAD_VALUE;
4066 }
4067 mRotateAndCropOverride = rotateAndCropValue;
4068 return OK;
4069}
4070
Emilian Peeve23f1d92021-09-20 14:56:01 -07004071status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4072 ATRACE_CALL();
4073 Mutex::Autolock l(mTriggerMutex);
4074 mComposerOutput = composerSurfacePresent;
4075 return OK;
4076}
4077
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004078status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004079 ATRACE_CALL();
4080 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004081 if (muteMode != mCameraMute) {
4082 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004083 mCameraMuteChanged = true;
4084 }
4085 return OK;
4086}
4087
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004088nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004089 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004090 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004091 return mExpectedInflightDuration > kMinInflightDuration ?
4092 mExpectedInflightDuration : kMinInflightDuration;
4093}
4094
Emilian Peevaebbe412018-01-15 13:53:24 +00004095void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004096 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004097 if ((request == nullptr) || (halRequest == nullptr)) {
4098 ALOGE("%s: Invalid request!", __FUNCTION__);
4099 return;
4100 }
4101
4102 if (halRequest->num_physcam_settings > 0) {
4103 if (halRequest->physcam_id != nullptr) {
4104 delete [] halRequest->physcam_id;
4105 halRequest->physcam_id = nullptr;
4106 }
4107 if (halRequest->physcam_settings != nullptr) {
4108 auto it = ++(request->mSettingsList.begin());
4109 size_t i = 0;
4110 for (; it != request->mSettingsList.end(); it++, i++) {
4111 it->metadata.unlock(halRequest->physcam_settings[i]);
4112 }
4113 delete [] halRequest->physcam_settings;
4114 halRequest->physcam_settings = nullptr;
4115 }
4116 }
4117}
4118
Ravneetaeb20dc2022-03-30 05:33:03 +00004119status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4120 Mutex::Autolock il(mInterfaceLock);
4121 Mutex::Autolock l(mLock);
4122
4123 if (mCameraServiceWatchdog != NULL) {
4124 mCameraServiceWatchdog->setEnabled(enabled);
4125 }
4126
4127 return OK;
4128}
4129
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004130void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4131 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132 return;
4133 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004134
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004135 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004136 // Skip the ones that have been submitted successfully.
4137 if (nextRequest.submitted) {
4138 continue;
4139 }
4140
4141 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004142 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4143 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004144
4145 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004146 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004147 }
4148
Emilian Peevaebbe412018-01-15 13:53:24 +00004149 cleanupPhysicalSettings(captureRequest, halRequest);
4150
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004151 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004152 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004153 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4154 }
4155
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004156 // No output buffer can be returned when using HAL buffer manager
4157 if (!mUseHalBufManager) {
4158 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4159 //Buffers that failed processing could still have
4160 //valid acquire fence.
4161 int acquireFence = (*outputBuffers)[i].acquire_fence;
4162 if (0 <= acquireFence) {
4163 close(acquireFence);
4164 outputBuffers->editItemAt(i).acquire_fence = -1;
4165 }
Emilian Peevf4816702020-04-03 15:44:51 -07004166 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004167 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4168 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004169 /*timestampIncreasing*/true, std::vector<size_t> (),
4170 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004171 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004172 }
4173
4174 if (sendRequestError) {
4175 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004176 sp<NotificationListener> listener = mListener.promote();
4177 if (listener != NULL) {
4178 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004179 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004180 captureRequest->mResultExtras);
4181 }
4182 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004183
4184 // Remove yet-to-be submitted inflight request from inflightMap
4185 {
4186 sp<Camera3Device> parent = mParent.promote();
4187 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004188 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004189 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4190 if (idx >= 0) {
4191 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4192 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4193 parent->removeInFlightMapEntryLocked(idx);
4194 }
4195 }
4196 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004198
4199 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004200 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004201}
4202
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004203void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004204 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 // Optimized a bit for the simple steady-state case (single repeating
4206 // request), to avoid putting that request in the queue temporarily.
4207 Mutex::Autolock l(mRequestLock);
4208
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004209 assert(mNextRequests.empty());
4210
4211 NextRequest nextRequest;
4212 nextRequest.captureRequest = waitForNextRequestLocked();
4213 if (nextRequest.captureRequest == nullptr) {
4214 return;
4215 }
4216
Emilian Peevf4816702020-04-03 15:44:51 -07004217 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004218 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004219 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004220
4221 // Wait for additional requests
4222 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4223
4224 for (size_t i = 1; i < batchSize; i++) {
4225 NextRequest additionalRequest;
4226 additionalRequest.captureRequest = waitForNextRequestLocked();
4227 if (additionalRequest.captureRequest == nullptr) {
4228 break;
4229 }
4230
Emilian Peevf4816702020-04-03 15:44:51 -07004231 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004232 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004233 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004234 }
4235
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004236 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004237 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004238 mNextRequests.size(), batchSize);
4239 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004240 }
4241
4242 return;
4243}
4244
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004245void Camera3Device::RequestThread::setRequestClearing() {
4246 Mutex::Autolock l(mRequestLock);
4247 mRequestClearing = true;
4248}
4249
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004250sp<Camera3Device::CaptureRequest>
4251 Camera3Device::RequestThread::waitForNextRequestLocked() {
4252 status_t res;
4253 sp<CaptureRequest> nextRequest;
4254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255 while (mRequestQueue.empty()) {
4256 if (!mRepeatingRequests.empty()) {
4257 // Always atomically enqueue all requests in a repeating request
4258 // list. Guarantees a complete in-sequence set of captures to
4259 // application.
4260 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004261 if (mFirstRepeating) {
4262 mFirstRepeating = false;
4263 } else {
4264 for (auto& request : requests) {
4265 // For repeating requests, override timestamp request using
4266 // the time a request is inserted into the request queue,
4267 // because the original repeating request will have an old
4268 // fixed timestamp.
4269 request->mRequestTimeNs = systemTime();
4270 }
4271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 RequestList::const_iterator firstRequest =
4273 requests.begin();
4274 nextRequest = *firstRequest;
4275 mRequestQueue.insert(mRequestQueue.end(),
4276 ++firstRequest,
4277 requests.end());
4278 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004279
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004280 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004281
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004282 break;
4283 }
4284
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004285 if (!mRequestClearing) {
4286 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4287 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004288
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004289 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4290 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004291 Mutex::Autolock pl(mPauseLock);
4292 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004293 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004294 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004295 if (mNotifyPipelineDrain) {
4296 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4297 mNotifyPipelineDrain = false;
4298 mStreamIdsToBeDrained.clear();
4299 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004300 // Let the tracker know
4301 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4302 if (statusTracker != 0) {
4303 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4304 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004305 sp<Camera3Device> parent = mParent.promote();
4306 if (parent != nullptr) {
4307 parent->mRequestBufferSM.onRequestThreadPaused();
4308 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004310 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 // Stop waiting for now and let thread management happen
4312 return NULL;
4313 }
4314 }
4315
4316 if (nextRequest == NULL) {
4317 // Don't have a repeating request already in hand, so queue
4318 // must have an entry now.
4319 RequestList::iterator firstRequest =
4320 mRequestQueue.begin();
4321 nextRequest = *firstRequest;
4322 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004323 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4324 sp<NotificationListener> listener = mListener.promote();
4325 if (listener != NULL) {
4326 listener->notifyRequestQueueEmpty();
4327 }
4328 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329 }
4330
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004331 // In case we've been unpaused by setPaused clearing mDoPause, need to
4332 // update internal pause state (capture/setRepeatingRequest unpause
4333 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004335 if (mPaused) {
4336 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4337 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4338 if (statusTracker != 0) {
4339 statusTracker->markComponentActive(mStatusId);
4340 }
4341 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 mPaused = false;
4343
4344 // Check if we've reconfigured since last time, and reset the preview
4345 // request if so. Can't use 'NULL request == repeat' across configure calls.
4346 if (mReconfigured) {
4347 mPrevRequest.clear();
4348 mReconfigured = false;
4349 }
4350
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004351 if (nextRequest != NULL) {
4352 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004353 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4354 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004355
4356 // Since RequestThread::clear() removes buffers from the input stream,
4357 // get the right buffer here before unlocking mRequestLock
4358 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004359 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4360 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004361 if (res != OK) {
4362 // Can't get input buffer from gralloc queue - this could be due to
4363 // disconnected queue or other producer misbehavior, so not a fatal
4364 // error
4365 ALOGE("%s: Can't get input buffer, skipping request:"
4366 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004367
4368 sp<NotificationListener> listener = mListener.promote();
4369 if (listener != NULL) {
4370 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004371 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004372 nextRequest->mResultExtras);
4373 }
4374 return NULL;
4375 }
4376 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004377 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004378
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004379 return nextRequest;
4380}
4381
4382bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004383 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004384 status_t res;
4385 Mutex::Autolock l(mPauseLock);
4386 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004387 if (mPaused == false) {
4388 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004389 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004390 if (mNotifyPipelineDrain) {
4391 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4392 mNotifyPipelineDrain = false;
4393 mStreamIdsToBeDrained.clear();
4394 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004395 // Let the tracker know
4396 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4397 if (statusTracker != 0) {
4398 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4399 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004400 sp<Camera3Device> parent = mParent.promote();
4401 if (parent != nullptr) {
4402 parent->mRequestBufferSM.onRequestThreadPaused();
4403 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004405
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004406 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004407 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408 return true;
4409 }
4410 }
4411 // We don't set mPaused to false here, because waitForNextRequest needs
4412 // to further manage the paused state in case of starvation.
4413 return false;
4414}
4415
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004416void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004417 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004418 // With work to do, mark thread as unpaused.
4419 // If paused by request (setPaused), don't resume, to avoid
4420 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004421 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004422 Mutex::Autolock p(mPauseLock);
4423 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004424 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4425 if (mPaused) {
4426 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4427 if (statusTracker != 0) {
4428 statusTracker->markComponentActive(mStatusId);
4429 }
4430 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004431 mPaused = false;
4432 }
4433}
4434
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004435void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4436 sp<Camera3Device> parent = mParent.promote();
4437 if (parent != NULL) {
4438 va_list args;
4439 va_start(args, fmt);
4440
4441 parent->setErrorStateV(fmt, args);
4442
4443 va_end(args);
4444 }
4445}
4446
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004447status_t Camera3Device::RequestThread::insertTriggers(
4448 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004449 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004450 Mutex::Autolock al(mTriggerMutex);
4451
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004452 sp<Camera3Device> parent = mParent.promote();
4453 if (parent == NULL) {
4454 CLOGE("RequestThread: Parent is gone");
4455 return DEAD_OBJECT;
4456 }
4457
Emilian Peevaebbe412018-01-15 13:53:24 +00004458 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004459 size_t count = mTriggerMap.size();
4460
4461 for (size_t i = 0; i < count; ++i) {
4462 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004463 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004464
4465 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4466 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4467 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004468 if (isAeTrigger) {
4469 request->mResultExtras.precaptureTriggerId = triggerId;
4470 mCurrentPreCaptureTriggerId = triggerId;
4471 } else {
4472 request->mResultExtras.afTriggerId = triggerId;
4473 mCurrentAfTriggerId = triggerId;
4474 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004475 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004476 }
4477
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004478 camera_metadata_entry entry = metadata.find(tag);
4479
4480 if (entry.count > 0) {
4481 /**
4482 * Already has an entry for this trigger in the request.
4483 * Rewrite it with our requested trigger value.
4484 */
4485 RequestTrigger oldTrigger = trigger;
4486
4487 oldTrigger.entryValue = entry.data.u8[0];
4488
4489 mTriggerReplacedMap.add(tag, oldTrigger);
4490 } else {
4491 /**
4492 * More typical, no trigger entry, so we just add it
4493 */
4494 mTriggerRemovedMap.add(tag, trigger);
4495 }
4496
4497 status_t res;
4498
4499 switch (trigger.getTagType()) {
4500 case TYPE_BYTE: {
4501 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4502 res = metadata.update(tag,
4503 &entryValue,
4504 /*count*/1);
4505 break;
4506 }
4507 case TYPE_INT32:
4508 res = metadata.update(tag,
4509 &trigger.entryValue,
4510 /*count*/1);
4511 break;
4512 default:
4513 ALOGE("%s: Type not supported: 0x%x",
4514 __FUNCTION__,
4515 trigger.getTagType());
4516 return INVALID_OPERATION;
4517 }
4518
4519 if (res != OK) {
4520 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4521 ", value %d", __FUNCTION__, trigger.getTagName(),
4522 trigger.entryValue);
4523 return res;
4524 }
4525
4526 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4527 trigger.getTagName(),
4528 trigger.entryValue);
4529 }
4530
4531 mTriggerMap.clear();
4532
4533 return count;
4534}
4535
4536status_t Camera3Device::RequestThread::removeTriggers(
4537 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004538 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004539 Mutex::Autolock al(mTriggerMutex);
4540
Emilian Peevaebbe412018-01-15 13:53:24 +00004541 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004542
4543 /**
4544 * Replace all old entries with their old values.
4545 */
4546 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4547 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4548
4549 status_t res;
4550
4551 uint32_t tag = trigger.metadataTag;
4552 switch (trigger.getTagType()) {
4553 case TYPE_BYTE: {
4554 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4555 res = metadata.update(tag,
4556 &entryValue,
4557 /*count*/1);
4558 break;
4559 }
4560 case TYPE_INT32:
4561 res = metadata.update(tag,
4562 &trigger.entryValue,
4563 /*count*/1);
4564 break;
4565 default:
4566 ALOGE("%s: Type not supported: 0x%x",
4567 __FUNCTION__,
4568 trigger.getTagType());
4569 return INVALID_OPERATION;
4570 }
4571
4572 if (res != OK) {
4573 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4574 ", trigger value %d", __FUNCTION__,
4575 trigger.getTagName(), trigger.entryValue);
4576 return res;
4577 }
4578 }
4579 mTriggerReplacedMap.clear();
4580
4581 /**
4582 * Remove all new entries.
4583 */
4584 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4585 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4586 status_t res = metadata.erase(trigger.metadataTag);
4587
4588 if (res != OK) {
4589 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4590 ", trigger value %d", __FUNCTION__,
4591 trigger.getTagName(), trigger.entryValue);
4592 return res;
4593 }
4594 }
4595 mTriggerRemovedMap.clear();
4596
4597 return OK;
4598}
4599
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004600status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004601 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004602 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004603 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004604 status_t res;
4605
Emilian Peevaebbe412018-01-15 13:53:24 +00004606 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004607
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004608 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004609 // exists
4610 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4611 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4612 if (afTrigger.count > 0 &&
4613 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4614 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004615 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004616 if (res != OK) return res;
4617 }
4618
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004619 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004620 // if none already exists
4621 camera_metadata_entry pcTrigger =
4622 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4623 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4624 if (pcTrigger.count > 0 &&
4625 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4626 pcId.count == 0) {
4627 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004628 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004629 if (res != OK) return res;
4630 }
4631
4632 return OK;
4633}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004634
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004635bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4636 const sp<CaptureRequest> &request) {
4637 ATRACE_CALL();
4638
4639 if (request->mRotateAndCropAuto) {
4640 Mutex::Autolock l(mTriggerMutex);
4641 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4642
4643 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4644 if (rotateAndCropEntry.count > 0) {
4645 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4646 return false;
4647 } else {
4648 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4649 return true;
4650 }
4651 } else {
4652 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4653 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4654 &rotateAndCrop_u8, 1);
4655 return true;
4656 }
4657 }
4658 return false;
4659}
4660
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004661bool Camera3Device::RequestThread::overrideTestPattern(
4662 const sp<CaptureRequest> &request) {
4663 ATRACE_CALL();
4664
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004665 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004666
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004667 Mutex::Autolock l(mTriggerMutex);
4668
4669 bool changed = false;
4670
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004671 // For a multi-camera, the physical cameras support the same set of
4672 // test pattern modes as the logical camera.
4673 for (auto& settings : request->mSettingsList) {
4674 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004675
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004676 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4677 int32_t testPatternData[4] = {
4678 settings.mOriginalTestPatternData[0],
4679 settings.mOriginalTestPatternData[1],
4680 settings.mOriginalTestPatternData[2],
4681 settings.mOriginalTestPatternData[3]
4682 };
4683 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4684 testPatternMode = mCameraMute;
4685 testPatternData[0] = 0;
4686 testPatternData[1] = 0;
4687 testPatternData[2] = 0;
4688 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004689 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004690
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004691 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4692 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4693 if (testPatternEntry.count > 0) {
4694 if (testPatternEntry.data.i32[0] != testPatternMode) {
4695 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004696 changed = true;
4697 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004698 } else if (supportTestPatternModeKey) {
4699 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4700 &testPatternMode, 1);
4701 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004702 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004703
4704 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4705 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4706 if (testPatternColor.count >= 4) {
4707 for (size_t i = 0; i < 4; i++) {
4708 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4709 testPatternColor.data.i32[i] = testPatternData[i];
4710 changed = true;
4711 }
4712 }
4713 } else if (supportTestPatternDataKey) {
4714 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4715 testPatternData, 4);
4716 changed = true;
4717 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004718 }
4719
4720 return changed;
4721}
4722
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004723status_t Camera3Device::RequestThread::setHalInterface(
4724 sp<HalInterface> newHalInterface) {
4725 if (newHalInterface.get() == nullptr) {
4726 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4727 return DEAD_OBJECT;
4728 }
4729
4730 mInterface = newHalInterface;
4731
4732 return OK;
4733}
4734
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004735/**
4736 * PreparerThread inner class methods
4737 */
4738
4739Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004740 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004741 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004742}
4743
4744Camera3Device::PreparerThread::~PreparerThread() {
4745 Thread::requestExitAndWait();
4746 if (mCurrentStream != nullptr) {
4747 mCurrentStream->cancelPrepare();
4748 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4749 mCurrentStream.clear();
4750 }
4751 clear();
4752}
4753
Ruben Brunkc78ac262015-08-13 17:58:46 -07004754status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004755 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004756 status_t res;
4757
4758 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004759 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004760
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004761 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004762 if (res == OK) {
4763 // No preparation needed, fire listener right off
4764 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004765 if (listener != NULL) {
4766 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004767 }
4768 return OK;
4769 } else if (res != NOT_ENOUGH_DATA) {
4770 return res;
4771 }
4772
4773 // Need to prepare, start up thread if necessary
4774 if (!mActive) {
4775 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4776 // isn't running
4777 Thread::requestExitAndWait();
4778 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4779 if (res != OK) {
4780 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004781 if (listener != NULL) {
4782 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004783 }
4784 return res;
4785 }
4786 mCancelNow = false;
4787 mActive = true;
4788 ALOGV("%s: Preparer stream started", __FUNCTION__);
4789 }
4790
4791 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004792 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004793 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4794
4795 return OK;
4796}
4797
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004798void Camera3Device::PreparerThread::pause() {
4799 ATRACE_CALL();
4800
4801 Mutex::Autolock l(mLock);
4802
4803 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4804 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4805 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4806 int currentMaxCount = mCurrentMaxCount;
4807 mPendingStreams.clear();
4808 mCancelNow = true;
4809 while (mActive) {
4810 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4811 if (res == TIMED_OUT) {
4812 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4813 return;
4814 } else if (res != OK) {
4815 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4816 return;
4817 }
4818 }
4819
4820 //Check whether the prepare thread was able to complete the current
4821 //stream. In case work is still pending emplace it along with the rest
4822 //of the streams in the pending list.
4823 if (currentStream != nullptr) {
4824 if (!mCurrentPrepareComplete) {
4825 pendingStreams.emplace(currentMaxCount, currentStream);
4826 }
4827 }
4828
4829 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4830 for (const auto& it : mPendingStreams) {
4831 it.second->cancelPrepare();
4832 }
4833}
4834
4835status_t Camera3Device::PreparerThread::resume() {
4836 ATRACE_CALL();
4837 status_t res;
4838
4839 Mutex::Autolock l(mLock);
4840 sp<NotificationListener> listener = mListener.promote();
4841
4842 if (mActive) {
4843 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4844 return NO_INIT;
4845 }
4846
4847 auto it = mPendingStreams.begin();
4848 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004849 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004850 if (res == OK) {
4851 if (listener != NULL) {
4852 listener->notifyPrepared(it->second->getId());
4853 }
4854 it = mPendingStreams.erase(it);
4855 } else if (res != NOT_ENOUGH_DATA) {
4856 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4857 res, strerror(-res));
4858 it = mPendingStreams.erase(it);
4859 } else {
4860 it++;
4861 }
4862 }
4863
4864 if (mPendingStreams.empty()) {
4865 return OK;
4866 }
4867
4868 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4869 if (res != OK) {
4870 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4871 __FUNCTION__, res, strerror(-res));
4872 return res;
4873 }
4874 mCancelNow = false;
4875 mActive = true;
4876 ALOGV("%s: Preparer stream started", __FUNCTION__);
4877
4878 return OK;
4879}
4880
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004881status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004882 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004883 Mutex::Autolock l(mLock);
4884
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004885 for (const auto& it : mPendingStreams) {
4886 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004887 }
4888 mPendingStreams.clear();
4889 mCancelNow = true;
4890
4891 return OK;
4892}
4893
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004894void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004895 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004896 Mutex::Autolock l(mLock);
4897 mListener = listener;
4898}
4899
4900bool Camera3Device::PreparerThread::threadLoop() {
4901 status_t res;
4902 {
4903 Mutex::Autolock l(mLock);
4904 if (mCurrentStream == nullptr) {
4905 // End thread if done with work
4906 if (mPendingStreams.empty()) {
4907 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4908 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4909 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4910 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004911 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004912 return false;
4913 }
4914
4915 // Get next stream to prepare
4916 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004917 mCurrentStream = it->second;
4918 mCurrentMaxCount = it->first;
4919 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004920 mPendingStreams.erase(it);
4921 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4922 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4923 } else if (mCancelNow) {
4924 mCurrentStream->cancelPrepare();
4925 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4926 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4927 mCurrentStream.clear();
4928 mCancelNow = false;
4929 return true;
4930 }
4931 }
4932
4933 res = mCurrentStream->prepareNextBuffer();
4934 if (res == NOT_ENOUGH_DATA) return true;
4935 if (res != OK) {
4936 // Something bad happened; try to recover by cancelling prepare and
4937 // signalling listener anyway
4938 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4939 mCurrentStream->getId(), res, strerror(-res));
4940 mCurrentStream->cancelPrepare();
4941 }
4942
4943 // This stream has finished, notify listener
4944 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004945 sp<NotificationListener> listener = mListener.promote();
4946 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004947 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4948 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004949 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004950 }
4951
4952 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4953 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004954 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004955
4956 return true;
4957}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004958
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004959status_t Camera3Device::RequestBufferStateMachine::initialize(
4960 sp<camera3::StatusTracker> statusTracker) {
4961 if (statusTracker == nullptr) {
4962 ALOGE("%s: statusTracker is null", __FUNCTION__);
4963 return BAD_VALUE;
4964 }
4965
4966 std::lock_guard<std::mutex> lock(mLock);
4967 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004968 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004969 return OK;
4970}
4971
4972bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4973 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004974 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004975 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004976 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004977 return true;
4978 }
4979 return false;
4980}
4981
4982void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4983 std::lock_guard<std::mutex> lock(mLock);
4984 if (!mRequestBufferOngoing) {
4985 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4986 return;
4987 }
4988 mRequestBufferOngoing = false;
4989 if (mStatus == RB_STATUS_PENDING_STOP) {
4990 checkSwitchToStopLocked();
4991 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004992 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004993}
4994
4995void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4996 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004997 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004998 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004999 return;
5000}
5001
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005002void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005003 std::lock_guard<std::mutex> lock(mLock);
5004 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005005 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5006 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005007 mInflightMapEmpty = false;
5008 if (mStatus == RB_STATUS_STOPPED) {
5009 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005010 }
5011 return;
5012}
5013
5014void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5015 std::lock_guard<std::mutex> lock(mLock);
5016 mRequestThreadPaused = true;
5017 if (mStatus == RB_STATUS_PENDING_STOP) {
5018 checkSwitchToStopLocked();
5019 }
5020 return;
5021}
5022
5023void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5024 std::lock_guard<std::mutex> lock(mLock);
5025 mInflightMapEmpty = true;
5026 if (mStatus == RB_STATUS_PENDING_STOP) {
5027 checkSwitchToStopLocked();
5028 }
5029 return;
5030}
5031
5032void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5033 std::lock_guard<std::mutex> lock(mLock);
5034 if (!checkSwitchToStopLocked()) {
5035 mStatus = RB_STATUS_PENDING_STOP;
5036 }
5037 return;
5038}
5039
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005040bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5041 std::lock_guard<std::mutex> lock(mLock);
5042 if (mRequestBufferOngoing) {
5043 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5044 __FUNCTION__);
5045 return false;
5046 }
5047 mSwitchedToOffline = true;
5048 mInflightMapEmpty = true;
5049 mRequestThreadPaused = true;
5050 mStatus = RB_STATUS_STOPPED;
5051 return true;
5052}
5053
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005054void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5055 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5056 if (statusTracker != nullptr) {
5057 if (active) {
5058 statusTracker->markComponentActive(mRequestBufferStatusId);
5059 } else {
5060 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5061 }
5062 }
5063}
5064
5065bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5066 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5067 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005068 return true;
5069 }
5070 return false;
5071}
5072
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005073bool Camera3Device::startRequestBuffer() {
5074 return mRequestBufferSM.startRequestBuffer();
5075}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005076
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005077void Camera3Device::endRequestBuffer() {
5078 mRequestBufferSM.endRequestBuffer();
5079}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005080
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005081nsecs_t Camera3Device::getWaitDuration() {
5082 return kBaseGetBufferWait + getExpectedInFlightDuration();
5083}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005084
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005085void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5086 mInterface->getInflightBufferKeys(out);
5087}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005088
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005089void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5090 mInterface->getInflightRequestBufferKeys(out);
5091}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005092
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005093std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5094 std::vector<sp<Camera3StreamInterface>> ret;
5095 bool hasInputStream = mInputStream != nullptr;
5096 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5097 if (hasInputStream) {
5098 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005099 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005100 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5101 ret.push_back(mOutputStreams[i]);
5102 }
5103 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5104 ret.push_back(mDeletedStreams[i]);
5105 }
5106 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005107}
5108
Emilian Peevcc0b7952020-01-07 13:54:47 -08005109void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5110 ATRACE_CALL();
5111
5112 if (offlineStreamIds == nullptr) {
5113 return;
5114 }
5115
5116 Mutex::Autolock il(mInterfaceLock);
5117
5118 auto streamIds = mOutputStreams.getStreamIds();
5119 bool hasInputStream = mInputStream != nullptr;
5120 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5121 offlineStreamIds->push_back(mInputStream->getId());
5122 }
5123
5124 for (const auto & streamId : streamIds) {
5125 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5126 // Streams that use the camera buffer manager are currently not supported in
5127 // offline mode
5128 if (stream->getOfflineProcessingSupport() &&
5129 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5130 offlineStreamIds->push_back(streamId);
5131 }
5132 }
5133}
5134
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005135status_t Camera3Device::setRotateAndCropAutoBehavior(
5136 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5137 ATRACE_CALL();
5138 Mutex::Autolock il(mInterfaceLock);
5139 Mutex::Autolock l(mLock);
5140 if (mRequestThread == nullptr) {
5141 return INVALID_OPERATION;
5142 }
5143 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5144}
5145
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005146bool Camera3Device::supportsCameraMute() {
5147 Mutex::Autolock il(mInterfaceLock);
5148 Mutex::Autolock l(mLock);
5149
5150 return mSupportCameraMute;
5151}
5152
5153status_t Camera3Device::setCameraMute(bool enabled) {
5154 ATRACE_CALL();
5155 Mutex::Autolock il(mInterfaceLock);
5156 Mutex::Autolock l(mLock);
5157
5158 if (mRequestThread == nullptr || !mSupportCameraMute) {
5159 return INVALID_OPERATION;
5160 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005161 int32_t muteMode =
5162 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5163 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5164 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5165 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005166}
5167
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005168status_t Camera3Device::injectCamera(const String8& injectedCamId,
5169 sp<CameraProviderManager> manager) {
5170 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5171 ATRACE_CALL();
5172 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005173 // When the camera device is active, injectCamera() and stopInjection() will call
5174 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5175 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5176 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5177 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5178 // waitUntilStateThenRelock().
5179 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005180
5181 status_t res = NO_ERROR;
5182 if (mInjectionMethods->isInjecting()) {
5183 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5184 return OK;
5185 } else {
5186 res = mInjectionMethods->stopInjection();
5187 if (res != OK) {
5188 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5189 __FUNCTION__, res);
5190 return res;
5191 }
5192 }
5193 }
5194
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005195 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005196 if (res != OK) {
5197 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5198 __FUNCTION__, res);
5199 return res;
5200 }
5201
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005202 // When the second display of android is cast to the remote device, and the opened camera is
5203 // also cast to the second display, in this case, because the camera has configured the streams
5204 // at this time, we can directly call injectCamera() to replace the internal camera with
5205 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005206 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5207 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5208
5209 camera3::camera_stream_configuration injectionConfig;
5210 std::vector<uint32_t> injectionBufferSizes;
5211 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5212 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5213 || injectionBufferSizes.size() <= 0) {
5214 ALOGE("Failed to inject camera due to abandoned configuration! "
5215 "mOperatingMode: %d injectionConfig.num_streams: %d "
5216 "injectionBufferSizes.size(): %zu", mOperatingMode,
5217 injectionConfig.num_streams, injectionBufferSizes.size());
5218 return DEAD_OBJECT;
5219 }
5220
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005221 res = mInjectionMethods->injectCamera(
5222 injectionConfig, injectionBufferSizes);
5223 if (res != OK) {
5224 ALOGE("Can't finish inject camera process!");
5225 return res;
5226 }
5227 }
5228
5229 return OK;
5230}
5231
5232status_t Camera3Device::stopInjection() {
5233 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5234 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005235 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005236 return mInjectionMethods->stopInjection();
5237}
5238
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005239}; // namespace android