blob: 442b122666af73098ace9efc9492918b5cad0c3a [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070055#include "CameraService.h"
Emilian Peeve579d8b2023-02-28 14:16:08 -080056#include "aidl/android/hardware/graphics/common/Dataspace.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080057#include "aidl/AidlUtils.h"
58#include "device3/Camera3Device.h"
59#include "device3/Camera3FakeStream.h"
60#include "device3/Camera3InputStream.h"
61#include "device3/Camera3OutputStream.h"
62#include "device3/Camera3SharedOutputStream.h"
63#include "mediautils/SchedulingPolicyService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070064#include "utils/CameraThreadState.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080065#include "utils/CameraTraces.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080066#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070067#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080068
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080069#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080070#include <tuple>
71
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080072using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080073using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080074
75namespace android {
76
Austin Borger74fca042022-05-23 12:41:21 -070077Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070078 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070079 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080080 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070081 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080082 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070083 mIsConstrainedHighSpeedConfiguration(false),
Emilian Peeve579d8b2023-02-28 14:16:08 -080084 mSupportNativeJpegR(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070085 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070086 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070087 mUsePartialResult(false),
88 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080089 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080090 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070092 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070094 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070095 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070096 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000097 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010098 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070099 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700100 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -0700101 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800102 mOverrideToPortrait(overrideToPortrait),
103 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104{
105 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800107}
108
109Camera3Device::~Camera3Device()
110{
111 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700113 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800117 return mId;
118}
119
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120status_t Camera3Device::initializeCommonLocked() {
121
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700122 /** Start up status tracker thread */
123 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 if (res != OK) {
126 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
127 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700129 mStatusTracker.clear();
130 return res;
131 }
132
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700133 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700134 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700135
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700136 if (mUseHalBufManager) {
137 res = mRequestBufferSM.initialize(mStatusTracker);
138 if (res != OK) {
139 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
140 strerror(-res), res);
141 mInterface->close();
142 mStatusTracker.clear();
143 return res;
144 }
145 }
146
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800147 /** Create buffer manager */
148 mBufferManager = new Camera3BufferManager();
149
150 Vector<int32_t> sessionParamKeys;
151 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
152 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
153 if (sessionKeysEntry.count > 0) {
154 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
155 }
156
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700157 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
158 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
159 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
160 if (availableTestPatternModes.data.i32[i] ==
161 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
162 mSupportCameraMute = true;
163 mSupportTestPatternSolidColor = true;
164 break;
165 } else if (availableTestPatternModes.data.i32[i] ==
166 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
167 mSupportCameraMute = true;
168 mSupportTestPatternSolidColor = false;
169 }
170 }
171
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700172 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800173 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700174 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger18b30a72022-10-27 12:20:29 -0700175 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800177 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700178 SET_ERR_L("Unable to start request queue thread: %s (%d)",
179 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800180 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800181 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800182 return res;
183 }
184
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700185 mPreparerThread = new PreparerThread();
186
Ruben Brunk183f0562015-08-12 12:55:02 -0700187 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800188 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400189 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700190 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700191 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800192 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800193
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800194 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800195 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800196 camera_metadata_entry timestampSource =
197 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
198 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
199 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800200 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800201 }
202
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700203 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100204 camera_metadata_entry partialResultsCount =
205 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
206 if (partialResultsCount.count > 0) {
207 mNumPartialResults = partialResultsCount.data.i32[0];
208 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700209 }
210
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800211 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
212 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700213 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700214 if (res != OK) {
215 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
216 return res;
217 }
218 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800220 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800221 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800222
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800223 if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700224 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
225 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
226 }
227
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800228 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
229 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
230 }
231
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800232 // Hidl/AidlCamera3DeviceInjectionMethods
233 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800234
Ravneetaeb20dc2022-03-30 05:33:03 +0000235 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800236 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700237 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
238 if (res != OK) {
239 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
240 strerror(-res), res);
241 return res;
242 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000243
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800244 return OK;
245}
246
247status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700248 return disconnectImpl();
249}
250
251status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800252 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700253 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800254
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700255 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700256 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700257 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800258 Mutex::Autolock il(mInterfaceLock);
259 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
260 {
261 Mutex::Autolock l(mLock);
262 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000264 if (mRequestThread != NULL) {
265 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
266 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000268 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800269 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000270 } else {
271 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
272 if (res != OK) {
273 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
274 maxExpectedDuration);
275 // Continue to close device even in case of error
276 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000279 // Signal to request thread that we're not expecting any
280 // more requests. This will be true since once we're in
281 // disconnect and we've cleared off the request queue, the
282 // request thread can't receive any new requests through
283 // binder calls - since disconnect holds
284 // mBinderSerialization lock.
285 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700286 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800287
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 if (mStatus == STATUS_ERROR) {
289 CLOGE("Shutting down in an error state");
290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700291
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800292 if (mStatusTracker != NULL) {
293 mStatusTracker->requestExit();
294 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700295
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800296 if (mRequestThread != NULL) {
297 mRequestThread->requestExit();
298 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800300 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
301 for (size_t i = 0; i < mOutputStreams.size(); i++) {
302 streams.push_back(mOutputStreams[i]);
303 }
304 if (mInputStream != nullptr) {
305 streams.push_back(mInputStream);
306 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700307 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800309 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
310 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
312 // HAL may be in a bad state, so waiting for request thread
313 // (which may be stuck in the HAL processCaptureRequest call)
314 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800315 // give up mInterfaceLock here and then lock it again. Could this lead
316 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 mRequestThread->join();
318 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700319 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800320 Mutex::Autolock il(mInterfaceLock);
321 if (mStatusTracker != NULL) {
322 mStatusTracker->join();
323 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800325 if (mInjectionMethods->isInjecting()) {
326 mInjectionMethods->stopInjection();
327 }
328
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800329 HalInterface* interface;
330 {
331 Mutex::Autolock l(mLock);
332 mRequestThread.clear();
333 Mutex::Autolock stLock(mTrackerLock);
334 mStatusTracker.clear();
335 interface = mInterface.get();
336 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700337
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800338 // Call close without internal mutex held, as the HAL close may need to
339 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000340 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700341
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800342 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800344 {
345 Mutex::Autolock l(mLock);
346 mInterface->clear();
347 mOutputStreams.clear();
348 mInputStream.clear();
349 mDeletedStreams.clear();
350 mBufferManager.clear();
351 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
352 }
353
354 for (auto& weakStream : streams) {
355 sp<Camera3StreamInterface> stream = weakStream.promote();
356 if (stream != nullptr) {
357 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
358 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
359 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700360 }
361 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700362 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000363
364 if (mCameraServiceWatchdog != NULL) {
365 mCameraServiceWatchdog->requestExit();
366 mCameraServiceWatchdog.clear();
367 }
368
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700369 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800370}
371
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372// For dumping/debugging only -
373// try to acquire a lock a few times, eventually give up to proceed with
374// debug/dump operations
375bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
376 bool gotLock = false;
377 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
378 if (lock.tryLock() == NO_ERROR) {
379 gotLock = true;
380 break;
381 } else {
382 usleep(kDumpSleepDuration);
383 }
384 }
385 return gotLock;
386}
387
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800388nsecs_t Camera3Device::getMonoToBoottimeOffset() {
389 // try three times to get the clock offset, choose the one
390 // with the minimum gap in measurements.
391 const int tries = 3;
392 nsecs_t bestGap, measured;
393 for (int i = 0; i < tries; ++i) {
394 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
395 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
396 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
397 const nsecs_t gap = tmono2 - tmono;
398 if (i == 0 || gap < bestGap) {
399 bestGap = gap;
400 measured = tbase - ((tmono + tmono2) >> 1);
401 }
402 }
403 return measured;
404}
405
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800406ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
407 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700408 // Get max jpeg size (area-wise) for default sensor pixel mode
409 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800410 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharydbd1efb2023-02-07 16:14:48 -0800411 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700412 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
413 // not ultra high res sensor
414 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800415 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700416 /*isUltraHighResolution*/true);
417 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800418 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
419 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700420 return BAD_VALUE;
421 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700422 bool useMaxSensorPixelModeThreshold = false;
423 if (uhrMaxJpegResolution.width != 0 &&
424 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
425 // Use the ultra high res max jpeg size and max jpeg buffer size
426 useMaxSensorPixelModeThreshold = true;
427 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700428
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 // Get max jpeg buffer size
430 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800431 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800433 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
434 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700435 return BAD_VALUE;
436 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700437 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700438
439 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
440 if (useMaxSensorPixelModeThreshold) {
441 maxJpegBufferSize =
442 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
443 maxDefaultJpegResolution, maxJpegBufferSize);
444 chosenMaxJpegResolution = uhrMaxJpegResolution;
445 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800446 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700447
448 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700449 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700450 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800451 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
452 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700453 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800454 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
455 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700456 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700457 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700458 return jpegBufferSize;
459}
460
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800461ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700462 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800463 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800465 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
466 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700467 return BAD_VALUE;
468 }
469 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
470 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
471 return maxBytesForPointCloud;
472}
473
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800474ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
475 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800476 const int PER_CONFIGURATION_SIZE = 3;
477 const int WIDTH_OFFSET = 0;
478 const int HEIGHT_OFFSET = 1;
479 const int SIZE_OFFSET = 2;
480 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800481 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800482 camera3::SessionConfigurationUtils::getAppropriateModeTag(
483 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
484 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800485 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800486 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
488 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800489 return BAD_VALUE;
490 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700491
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800492 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
493 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
494 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
495 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
496 }
497 }
498
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800499 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
500 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800501 return BAD_VALUE;
502}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700503
Jing Mikec7f9b132023-03-12 11:12:04 +0800504status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800505 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700506
507 // Try to lock, but continue in case of failure (to avoid blocking in
508 // deadlocks)
509 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
510 bool gotLock = tryLockSpinRightRound(mLock);
511
512 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800513 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
514 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700515 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800516 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
517 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700518
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800519 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700520
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800521 String16 templatesOption("-t");
522 int n = args.size();
523 for (int i = 0; i < n; i++) {
524 if (args[i] == templatesOption) {
525 dumpTemplates = true;
526 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000527 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700528 if (i + 1 < n) {
529 String8 monitorTags = String8(args[i + 1]);
530 if (monitorTags == "off") {
531 mTagMonitor.disableMonitoring();
532 } else {
533 mTagMonitor.parseTagsToMonitor(monitorTags);
534 }
535 } else {
536 mTagMonitor.disableMonitoring();
537 }
538 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800539 }
540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800541 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800542
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800543 const char *status =
544 mStatus == STATUS_ERROR ? "ERROR" :
545 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700546 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
547 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800548 mStatus == STATUS_ACTIVE ? "ACTIVE" :
549 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700550
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800551 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700552 if (mStatus == STATUS_ERROR) {
553 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
554 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800555 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800556 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000557 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
558 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
559 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800560 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800561
562 if (mInputStream != NULL) {
563 write(fd, lines.string(), lines.size());
564 mInputStream->dump(fd, args);
565 } else {
566 lines.appendFormat(" No input stream.\n");
567 write(fd, lines.string(), lines.size());
568 }
569 for (size_t i = 0; i < mOutputStreams.size(); i++) {
570 mOutputStreams[i]->dump(fd,args);
571 }
572
Zhijun He431503c2016-03-07 17:30:16 -0800573 if (mBufferManager != NULL) {
574 lines = String8(" Camera3 Buffer Manager:\n");
575 write(fd, lines.string(), lines.size());
576 mBufferManager->dump(fd, args);
577 }
Zhijun He125684a2015-12-26 15:07:30 -0800578
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700579 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700580 if (mInFlightLock.try_lock()) {
581 if (mInFlightMap.size() == 0) {
582 lines.append(" None\n");
583 } else {
584 for (size_t i = 0; i < mInFlightMap.size(); i++) {
585 InFlightRequest r = mInFlightMap.valueAt(i);
586 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
587 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
588 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
589 r.numBuffersLeft);
590 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700591 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700592 mInFlightLock.unlock();
593 } else {
594 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700595 }
596 write(fd, lines.string(), lines.size());
597
Shuzhen Wang686f6442017-06-20 16:16:04 -0700598 if (mRequestThread != NULL) {
599 mRequestThread->dumpCaptureRequestLatency(fd,
600 " ProcessCaptureRequest latency histogram:");
601 }
602
Igor Murashkin1e479c02013-09-06 16:55:14 -0700603 {
604 lines = String8(" Last request sent:\n");
605 write(fd, lines.string(), lines.size());
606
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700607 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700608 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
609 }
610
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800611 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700612 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800613 "TEMPLATE_PREVIEW",
614 "TEMPLATE_STILL_CAPTURE",
615 "TEMPLATE_VIDEO_RECORD",
616 "TEMPLATE_VIDEO_SNAPSHOT",
617 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800618 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800619 };
620
Emilian Peevf4816702020-04-03 15:44:51 -0700621 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800622 camera_metadata_t *templateRequest = nullptr;
623 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700624 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800625 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800626 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800627 lines.append(" Not supported\n");
628 write(fd, lines.string(), lines.size());
629 } else {
630 write(fd, lines.string(), lines.size());
631 dump_indented_camera_metadata(templateRequest,
632 fd, /*verbosity*/2, /*indentation*/8);
633 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800634 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800635 }
636 }
637
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700638 mTagMonitor.dumpMonitoredMetadata(fd);
639
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800641 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800642 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800643 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800645
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700646 if (gotLock) mLock.unlock();
647 if (gotInterfaceLock) mInterfaceLock.unlock();
648
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800649 return OK;
650}
651
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700652status_t Camera3Device::startWatchingTags(const String8 &tags) {
653 mTagMonitor.parseTagsToMonitor(tags);
654 return OK;
655}
656
657status_t Camera3Device::stopWatchingTags() {
658 mTagMonitor.disableMonitoring();
659 return OK;
660}
661
662status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
663 mTagMonitor.getLatestMonitoredTagEvents(out);
664 return OK;
665}
666
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800667const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800668 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800669 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
670 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700671 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800672 mStatus == STATUS_ERROR ?
673 "when in error state" : "before init");
674 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700675 if (physicalId.isEmpty()) {
676 return mDeviceInfo;
677 } else {
678 std::string id(physicalId.c_str());
679 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
680 return mPhysicalDeviceInfoMap.at(id);
681 } else {
682 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
683 return mDeviceInfo;
684 }
685 }
686}
687
688const CameraMetadata& Camera3Device::info() const {
689 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800690 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800691}
692
Jianing Wei90e59c92014-03-12 18:29:36 -0700693status_t Camera3Device::checkStatusOkToCaptureLocked() {
694 switch (mStatus) {
695 case STATUS_ERROR:
696 CLOGE("Device has encountered a serious error");
697 return INVALID_OPERATION;
698 case STATUS_UNINITIALIZED:
699 CLOGE("Device not initialized");
700 return INVALID_OPERATION;
701 case STATUS_UNCONFIGURED:
702 case STATUS_CONFIGURED:
703 case STATUS_ACTIVE:
704 // OK
705 break;
706 default:
707 SET_ERR_L("Unexpected status: %d", mStatus);
708 return INVALID_OPERATION;
709 }
710 return OK;
711}
712
713status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000714 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700715 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700716 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700717 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700718 if (requestList == NULL) {
719 CLOGE("requestList cannot be NULL.");
720 return BAD_VALUE;
721 }
722
Jianing Weicb0652e2014-03-12 18:29:36 -0700723 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000724 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700725 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
726 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
727 ++metadataIt, ++surfaceMapIt) {
728 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700729 if (newRequest == 0) {
730 CLOGE("Can't create capture request");
731 return BAD_VALUE;
732 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700733
Shuzhen Wang9d066012016-09-30 11:30:20 -0700734 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700735 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700736
Jianing Weicb0652e2014-03-12 18:29:36 -0700737 // Setup burst Id and request Id
738 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800739 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
740 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700741 CLOGE("RequestID does not exist in metadata");
742 return BAD_VALUE;
743 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800744 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700745
Jianing Wei90e59c92014-03-12 18:29:36 -0700746 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700747
748 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700749 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700750 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
751 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
752 return BAD_VALUE;
753 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700754
755 // Setup batch size if this is a high speed video recording request.
756 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
757 auto firstRequest = requestList->begin();
758 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
759 if (outputStream->isVideoStream()) {
760 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800761 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700762 break;
763 }
764 }
765 }
766
Jianing Wei90e59c92014-03-12 18:29:36 -0700767 return OK;
768}
769
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800770status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000775 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700776
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800777 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700778}
779
Emilian Peevaebbe412018-01-15 13:53:24 +0000780void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700781 std::list<const SurfaceMap>& surfaceMaps,
782 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000783 PhysicalCameraSettingsList requestList;
784 requestList.push_back({std::string(getId().string()), request});
785 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700786
787 SurfaceMap surfaceMap;
788 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
789 // With no surface list passed in, stream and surface will have 1-to-1
790 // mapping. So the surface index is 0 for each stream in the surfaceMap.
791 for (size_t i = 0; i < streams.count; i++) {
792 surfaceMap[streams.data.i32[i]].push_back(0);
793 }
794 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800795}
796
Jianing Wei90e59c92014-03-12 18:29:36 -0700797status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000798 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700799 const std::list<const SurfaceMap> &surfaceMaps,
800 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700801 /*out*/
802 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700804 nsecs_t requestTimeNs = systemTime();
805
Jianing Wei90e59c92014-03-12 18:29:36 -0700806 Mutex::Autolock il(mInterfaceLock);
807 Mutex::Autolock l(mLock);
808
809 status_t res = checkStatusOkToCaptureLocked();
810 if (res != OK) {
811 // error logged by previous call
812 return res;
813 }
814
815 RequestList requestList;
816
Shuzhen Wang0129d522016-10-30 22:43:41 -0700817 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700818 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700819 if (res != OK) {
820 // error logged by previous call
821 return res;
822 }
823
824 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700825 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700827 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700828 }
829
830 if (res == OK) {
831 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
832 if (res != OK) {
833 SET_ERR_L("Can't transition to active in %f seconds!",
834 kActiveTimeout/1e9);
835 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800836 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700837 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700838 } else {
839 CLOGE("Cannot queue request. Impossible.");
840 return BAD_VALUE;
841 }
842
843 return res;
844}
845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700847 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700848 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700849 ATRACE_CALL();
850
Emilian Peevaebbe412018-01-15 13:53:24 +0000851 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700852}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800853
Jianing Weicb0652e2014-03-12 18:29:36 -0700854status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
855 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800857
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700861
Emilian Peevaebbe412018-01-15 13:53:24 +0000862 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700863 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800864}
865
Emilian Peevaebbe412018-01-15 13:53:24 +0000866status_t Camera3Device::setStreamingRequestList(
867 const List<const PhysicalCameraSettingsList> &requestsList,
868 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700869 ATRACE_CALL();
870
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700872}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800873
874sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000875 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 status_t res;
877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700878 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800879 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
880 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000881 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700882 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700883 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700885 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800886 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700887 } else if (mStatus == STATUS_UNCONFIGURED) {
888 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700889 CLOGE("No streams configured");
890 return NULL;
891 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 }
893
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800895 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800896}
897
Jianing Weicb0652e2014-03-12 18:29:36 -0700898status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800899 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700900 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800901 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800903 switch (mStatus) {
904 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700905 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800906 return INVALID_OPERATION;
907 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700908 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800909 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700910 case STATUS_UNCONFIGURED:
911 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800912 case STATUS_ACTIVE:
913 // OK
914 break;
915 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700916 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800917 return INVALID_OPERATION;
918 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800919 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700920
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700921 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800922}
923
924status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
925 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700926 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800927
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700928 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800929}
930
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700931status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800932 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700933 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700934 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700935 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700936 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800937 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
938 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700939
940 status_t res;
941 bool wasActive = false;
942
943 switch (mStatus) {
944 case STATUS_ERROR:
945 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
946 return INVALID_OPERATION;
947 case STATUS_UNINITIALIZED:
948 ALOGE("%s: Device not initialized", __FUNCTION__);
949 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700950 case STATUS_UNCONFIGURED:
951 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952 // OK
953 break;
954 case STATUS_ACTIVE:
955 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700956 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700957 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700958 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700959 return res;
960 }
961 wasActive = true;
962 break;
963 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700964 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700965 return INVALID_OPERATION;
966 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700967 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700968
969 if (mInputStream != 0) {
970 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
971 return INVALID_OPERATION;
972 }
973
974 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
975 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700976 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700977
978 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800979 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700980
981 *id = mNextStreamId++;
982
983 // Continue captures if active at start
984 if (wasActive) {
985 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100986 // Reuse current operating mode and session parameters for new stream config
987 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700988 if (res != OK) {
989 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
990 __FUNCTION__, mNextStreamId, strerror(-res), res);
991 return res;
992 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700993 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700994 }
995
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800996 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700997 return OK;
998}
999
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001000status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001001 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001002 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001003 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001004 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1005 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001006 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001007 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001008 ATRACE_CALL();
1009
1010 if (consumer == nullptr) {
1011 ALOGE("%s: consumer must not be null", __FUNCTION__);
1012 return BAD_VALUE;
1013 }
1014
1015 std::vector<sp<Surface>> consumers;
1016 consumers.push_back(consumer);
1017
1018 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001019 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001020 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001021 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001022}
1023
1024static bool isRawFormat(int format) {
1025 switch (format) {
1026 case HAL_PIXEL_FORMAT_RAW16:
1027 case HAL_PIXEL_FORMAT_RAW12:
1028 case HAL_PIXEL_FORMAT_RAW10:
1029 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1030 return true;
1031 default:
1032 return false;
1033 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001034}
1035
1036status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1037 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001038 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001039 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001040 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001041 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001042 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001043 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001044
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001045 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001046 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001048 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001049 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001050 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001051 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001052 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001053 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001054 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1055 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001056
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001057 status_t res;
1058 bool wasActive = false;
1059
1060 switch (mStatus) {
1061 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001062 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001063 return INVALID_OPERATION;
1064 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001065 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001067 case STATUS_UNCONFIGURED:
1068 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069 // OK
1070 break;
1071 case STATUS_ACTIVE:
1072 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001073 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001075 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001076 return res;
1077 }
1078 wasActive = true;
1079 break;
1080 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001081 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001082 return INVALID_OPERATION;
1083 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001084 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001085
1086 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001087
Shuzhen Wang0129d522016-10-30 22:43:41 -07001088 if (consumers.size() == 0 && !hasDeferredConsumer) {
1089 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1090 return BAD_VALUE;
1091 }
Zhijun He5d677d12016-05-29 16:52:39 -07001092
Shuzhen Wang0129d522016-10-30 22:43:41 -07001093 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001094 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1095 return BAD_VALUE;
1096 }
1097
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001098 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1099 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1100 // be found in only one sensor pixel mode.
1101 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1102 return BAD_VALUE;
1103 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001104 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001105 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001106 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001107 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001108 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001109 if (blobBufferSize <= 0) {
1110 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1111 return BAD_VALUE;
1112 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001113 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1114 blobBufferSize = width * height;
1115 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001116 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001117 if (blobBufferSize <= 0) {
1118 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1119 return BAD_VALUE;
1120 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001121 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001122 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001123 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001124 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001125 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001126 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001127 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001128 bool maxResolution =
1129 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1130 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001131 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1132 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001133 if (rawOpaqueBufferSize <= 0) {
1134 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1135 return BAD_VALUE;
1136 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001137 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001138 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001139 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001140 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001141 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001142 } else if (isShared) {
1143 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1144 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001145 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001146 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001147 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001148 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001149 newStream = new Camera3OutputStream(mNextStreamId,
1150 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001151 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001152 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001153 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001154 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001155 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001156 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001157 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001158 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001159 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001160 }
Emilian Peev40ead602017-09-26 15:46:36 +01001161
1162 size_t consumerCount = consumers.size();
1163 for (size_t i = 0; i < consumerCount; i++) {
1164 int id = newStream->getSurfaceId(consumers[i]);
1165 if (id < 0) {
1166 SET_ERR_L("Invalid surface id");
1167 return BAD_VALUE;
1168 }
1169 if (surfaceIds != nullptr) {
1170 surfaceIds->push_back(id);
1171 }
1172 }
1173
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175
Emilian Peev08dd2452017-04-06 16:55:14 +01001176 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001177
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001178 newStream->setImageDumpMask(mImageDumpMask);
1179
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001180 res = mOutputStreams.add(mNextStreamId, newStream);
1181 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001182 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183 return res;
1184 }
1185
Shuzhen Wang316781a2020-08-18 18:11:01 -07001186 mSessionStatsBuilder.addStream(mNextStreamId);
1187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001189 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190
1191 // Continue captures if active at start
1192 if (wasActive) {
1193 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001194 // Reuse current operating mode and session parameters for new stream config
1195 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001197 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1198 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 return res;
1200 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001201 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001203 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205}
1206
Emilian Peev710c1422017-08-30 11:19:38 +01001207status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001208 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001209 if (nullptr == streamInfo) {
1210 return BAD_VALUE;
1211 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001212 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001214
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001215 switch (mStatus) {
1216 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001217 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 return INVALID_OPERATION;
1219 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001220 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001222 case STATUS_UNCONFIGURED:
1223 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 case STATUS_ACTIVE:
1225 // OK
1226 break;
1227 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001228 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 return INVALID_OPERATION;
1230 }
1231
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001232 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1233 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001234 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001235 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 }
1237
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001238 streamInfo->width = stream->getWidth();
1239 streamInfo->height = stream->getHeight();
1240 streamInfo->format = stream->getFormat();
1241 streamInfo->dataSpace = stream->getDataSpace();
1242 streamInfo->formatOverridden = stream->isFormatOverridden();
1243 streamInfo->originalFormat = stream->getOriginalFormat();
1244 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1245 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001246 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001247 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249}
1250
1251status_t Camera3Device::setStreamTransform(int id,
1252 int transform) {
1253 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001256
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 switch (mStatus) {
1258 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001259 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 return INVALID_OPERATION;
1261 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001262 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 case STATUS_UNCONFIGURED:
1265 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 case STATUS_ACTIVE:
1267 // OK
1268 break;
1269 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001270 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001271 return INVALID_OPERATION;
1272 }
1273
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001274 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1275 if (stream == nullptr) {
1276 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 return BAD_VALUE;
1278 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001279 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001280}
1281
1282status_t Camera3Device::deleteStream(int id) {
1283 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001285 Mutex::Autolock l(mLock);
1286 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001287
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001288 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001289
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001290 // CameraDevice semantics require device to already be idle before
1291 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001293 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001294 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001295 }
1296
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001297 if (mStatus == STATUS_ERROR) {
1298 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1299 __FUNCTION__, mId.string());
1300 return -EBUSY;
1301 }
1302
Igor Murashkin2fba5842013-04-22 14:03:54 -07001303 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001304 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001305 if (mInputStream != NULL && id == mInputStream->getId()) {
1306 deletedStream = mInputStream;
1307 mInputStream.clear();
1308 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001309 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001310 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001311 return BAD_VALUE;
1312 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001313 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001314 }
1315
1316 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001317 if (stream != nullptr) {
1318 deletedStream = stream;
1319 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001320 }
1321
1322 // Free up the stream endpoint so that it can be used by some other stream
1323 res = deletedStream->disconnect();
1324 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001325 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001326 // fall through since we want to still list the stream as deleted.
1327 }
1328 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001329 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001330
1331 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001332}
1333
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001334status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001335 ATRACE_CALL();
1336 ALOGV("%s: E", __FUNCTION__);
1337
1338 Mutex::Autolock il(mInterfaceLock);
1339 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001340
Emilian Peev811d2952018-05-25 11:08:40 +01001341 // In case the client doesn't include any session parameter, try a
1342 // speculative configuration using the values from the last cached
1343 // default request.
1344 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001345 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001346 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1347 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1348 mLastTemplateId);
1349 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1350 operatingMode);
1351 }
1352
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001353 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1354}
1355
1356status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1357 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001358 //Filter out any incoming session parameters
1359 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001360 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1361 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001362 CameraMetadata filteredParams(availableSessionKeys.count);
1363 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1364 filteredParams.getAndLock());
1365 set_camera_metadata_vendor_id(meta, mVendorTagId);
1366 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001367 if (availableSessionKeys.count > 0) {
1368 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1369 camera_metadata_ro_entry entry = params.find(
1370 availableSessionKeys.data.i32[i]);
1371 if (entry.count > 0) {
1372 filteredParams.update(entry);
1373 }
1374 }
1375 }
1376
1377 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001378}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001379
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001380status_t Camera3Device::getInputBufferProducer(
1381 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001382 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001383 Mutex::Autolock il(mInterfaceLock);
1384 Mutex::Autolock l(mLock);
1385
1386 if (producer == NULL) {
1387 return BAD_VALUE;
1388 } else if (mInputStream == NULL) {
1389 return INVALID_OPERATION;
1390 }
1391
1392 return mInputStream->getInputBufferProducer(producer);
1393}
1394
Emilian Peevf4816702020-04-03 15:44:51 -07001395status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001396 CameraMetadata *request) {
1397 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001398 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001399
Emilian Peevf4816702020-04-03 15:44:51 -07001400 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001401 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001402 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001403 return BAD_VALUE;
1404 }
1405
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001406 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001408 {
1409 Mutex::Autolock l(mLock);
1410 switch (mStatus) {
1411 case STATUS_ERROR:
1412 CLOGE("Device has encountered a serious error");
1413 return INVALID_OPERATION;
1414 case STATUS_UNINITIALIZED:
1415 CLOGE("Device is not initialized!");
1416 return INVALID_OPERATION;
1417 case STATUS_UNCONFIGURED:
1418 case STATUS_CONFIGURED:
1419 case STATUS_ACTIVE:
1420 // OK
1421 break;
1422 default:
1423 SET_ERR_L("Unexpected status: %d", mStatus);
1424 return INVALID_OPERATION;
1425 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001426
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001427 if (!mRequestTemplateCache[templateId].isEmpty()) {
1428 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001429 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001430 return OK;
1431 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001432 }
1433
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001434 camera_metadata_t *rawRequest;
1435 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001436 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001437
1438 {
1439 Mutex::Autolock l(mLock);
1440 if (res == BAD_VALUE) {
1441 ALOGI("%s: template %d is not supported on this camera device",
1442 __FUNCTION__, templateId);
1443 return res;
1444 } else if (res != OK) {
1445 CLOGE("Unable to construct request template %d: %s (%d)",
1446 templateId, strerror(-res), res);
1447 return res;
1448 }
1449
1450 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1451 mRequestTemplateCache[templateId].acquire(rawRequest);
1452
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001453 // Override the template request with zoomRatioMapper
1454 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1455 &mRequestTemplateCache[templateId]);
1456 if (res != OK) {
1457 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1458 templateId, strerror(-res), res);
1459 return res;
1460 }
1461
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001462 // Fill in JPEG_QUALITY if not available
1463 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1464 static const uint8_t kDefaultJpegQuality = 95;
1465 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1466 &kDefaultJpegQuality, 1);
1467 }
1468
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001469 // Fill in AUTOFRAMING if not available
1470 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1471 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1472 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1473 &kDefaultAutoframingMode, 1);
1474 }
1475
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001476 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001477 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001478 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001479 return OK;
1480}
1481
1482status_t Camera3Device::waitUntilDrained() {
1483 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001484 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001485 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001487
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001488 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001489}
1490
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001491status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 switch (mStatus) {
1493 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001494 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 ALOGV("%s: Already idle", __FUNCTION__);
1496 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497 case STATUS_CONFIGURED:
1498 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 case STATUS_ERROR:
1500 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 break;
1503 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 return INVALID_OPERATION;
1506 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001507 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1508 maxExpectedDuration);
1509 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001510 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001511 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001512 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1513 res);
1514 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 return res;
1516}
1517
Ruben Brunk183f0562015-08-12 12:55:02 -07001518void Camera3Device::internalUpdateStatusLocked(Status status) {
1519 mStatus = status;
1520 mRecentStatusUpdates.add(mStatus);
1521 mStatusChanged.broadcast();
1522}
1523
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001525status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001526 if (mRequestThread.get() != nullptr) {
1527 mRequestThread->setPaused(true);
1528 } else {
1529 return NO_INIT;
1530 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001532 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1533 maxExpectedDuration);
1534 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001536 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001538 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 }
1540
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 return res;
1542}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544// Resume after internalPauseAndWaitLocked
1545status_t Camera3Device::internalResumeLocked() {
1546 status_t res;
1547
1548 mRequestThread->setPaused(false);
1549
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001550 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1551 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1553 if (res != OK) {
1554 SET_ERR_L("Can't transition to active in %f seconds!",
1555 kActiveTimeout/1e9);
1556 }
1557 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001559}
1560
Ruben Brunk183f0562015-08-12 12:55:02 -07001561status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001563
1564 size_t startIndex = 0;
1565 if (mStatusWaiters == 0) {
1566 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1567 // this status list
1568 mRecentStatusUpdates.clear();
1569 } else {
1570 // If other threads are waiting on updates to this status list, set the position of the
1571 // first element that this list will check rather than clearing the list.
1572 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 }
1574
Ruben Brunk183f0562015-08-12 12:55:02 -07001575 mStatusWaiters++;
1576
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001577 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001578 if (!active && mUseHalBufManager) {
1579 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001580 if (mStatus == STATUS_ACTIVE) {
1581 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001582 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001583 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001584 mRequestBufferSM.onWaitUntilIdle();
1585 }
1586
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001588 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001590 if (active == (mStatus == STATUS_ACTIVE)) {
1591 // Desired state is current
1592 break;
1593 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001595 nsecs_t timeElapsed = systemTime() - startTime;
1596 nsecs_t timeToWait = timeout - timeElapsed;
1597 if (timeToWait <= 0) {
1598 // Thread woke up spuriously but has timed out since.
1599 // Force out of loop with TIMED_OUT result.
1600 res = TIMED_OUT;
1601 break;
1602 }
1603 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 if (res != OK) break;
1605
Ruben Brunk183f0562015-08-12 12:55:02 -07001606 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1607 // transitions.
1608 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1609 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1610 __FUNCTION__);
1611
1612 // Encountered desired state since we began waiting
1613 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001614 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1615 stateSeen = true;
1616 break;
1617 }
1618 }
1619 } while (!stateSeen);
1620
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001621 if (signalPipelineDrain) {
1622 mRequestThread->resetPipelineDrain();
1623 }
1624
Ruben Brunk183f0562015-08-12 12:55:02 -07001625 mStatusWaiters--;
1626
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 return res;
1628}
1629
1630
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001631status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001633 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001634
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001635 if (listener != NULL && mListener != NULL) {
1636 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1637 }
1638 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001639 mRequestThread->setNotificationListener(listener);
1640 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001641
1642 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643}
1644
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001645bool Camera3Device::willNotify3A() {
1646 return false;
1647}
1648
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001649status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001650 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001651 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001653 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001654 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1655 if (st == std::cv_status::timeout) {
1656 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001657 }
1658 }
1659 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001660}
1661
Jianing Weicb0652e2014-03-12 18:29:36 -07001662status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001664 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001665
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001666 if (mResultQueue.empty()) {
1667 return NOT_ENOUGH_DATA;
1668 }
1669
Jianing Weicb0652e2014-03-12 18:29:36 -07001670 if (frame == NULL) {
1671 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1672 return BAD_VALUE;
1673 }
1674
1675 CaptureResult &result = *(mResultQueue.begin());
1676 frame->mResultExtras = result.mResultExtras;
1677 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001678 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001679 mResultQueue.erase(mResultQueue.begin());
1680
1681 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001682}
1683
1684status_t Camera3Device::triggerAutofocus(uint32_t id) {
1685 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001687
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001688 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1689 // Mix-in this trigger into the next request and only the next request.
1690 RequestTrigger trigger[] = {
1691 {
1692 ANDROID_CONTROL_AF_TRIGGER,
1693 ANDROID_CONTROL_AF_TRIGGER_START
1694 },
1695 {
1696 ANDROID_CONTROL_AF_TRIGGER_ID,
1697 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001698 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001699 };
1700
1701 return mRequestThread->queueTrigger(trigger,
1702 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001703}
1704
1705status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1706 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001707 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001709 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1710 // Mix-in this trigger into the next request and only the next request.
1711 RequestTrigger trigger[] = {
1712 {
1713 ANDROID_CONTROL_AF_TRIGGER,
1714 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1715 },
1716 {
1717 ANDROID_CONTROL_AF_TRIGGER_ID,
1718 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001719 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001720 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001721
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001722 return mRequestThread->queueTrigger(trigger,
1723 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724}
1725
1726status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1727 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001728 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001730 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1731 // Mix-in this trigger into the next request and only the next request.
1732 RequestTrigger trigger[] = {
1733 {
1734 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1735 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1736 },
1737 {
1738 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1739 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001740 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001741 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001742
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001743 return mRequestThread->queueTrigger(trigger,
1744 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001745}
1746
Jianing Weicb0652e2014-03-12 18:29:36 -07001747status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001748 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001749 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001751
Zhijun He7ef20392014-04-21 16:04:17 -07001752 {
1753 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001754
1755 // b/116514106 "disconnect()" can get called twice for the same device. The
1756 // camera device will not be initialized during the second run.
1757 if (mStatus == STATUS_UNINITIALIZED) {
1758 return OK;
1759 }
1760
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001761 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001762
1763 // Stop session and stream counter
1764 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001765 }
1766
Ravneetdbd5b242022-03-02 07:22:46 +00001767 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001768 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001769 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1770 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1771
1772 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001773}
1774
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001775status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001776 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1777}
1778
1779status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001780 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001781 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001782 Mutex::Autolock il(mInterfaceLock);
1783 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001784
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001785 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1786 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001787 CLOGE("Stream %d does not exist", streamId);
1788 return BAD_VALUE;
1789 }
1790
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001791 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001792 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001793 return BAD_VALUE;
1794 }
1795
1796 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001797 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001798 return BAD_VALUE;
1799 }
1800
Ruben Brunkc78ac262015-08-13 17:58:46 -07001801 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001802}
1803
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001804status_t Camera3Device::tearDown(int streamId) {
1805 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001806 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001807 Mutex::Autolock il(mInterfaceLock);
1808 Mutex::Autolock l(mLock);
1809
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001810 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1811 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001812 CLOGE("Stream %d does not exist", streamId);
1813 return BAD_VALUE;
1814 }
1815
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001816 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1817 CLOGE("Stream %d is a target of a in-progress request", streamId);
1818 return BAD_VALUE;
1819 }
1820
1821 return stream->tearDown();
1822}
1823
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001824status_t Camera3Device::addBufferListenerForStream(int streamId,
1825 wp<Camera3StreamBufferListener> listener) {
1826 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001827 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001828 Mutex::Autolock il(mInterfaceLock);
1829 Mutex::Autolock l(mLock);
1830
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001831 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1832 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001833 CLOGE("Stream %d does not exist", streamId);
1834 return BAD_VALUE;
1835 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001836 stream->addBufferListener(listener);
1837
1838 return OK;
1839}
1840
Austin Borger4a870a32022-02-25 01:48:41 +00001841float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1842 camera_metadata_entry minDurations =
1843 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1844 for (size_t i = 0; i < minDurations.count; i += 4) {
1845 if (minDurations.data.i64[i] == stream->getFormat()
1846 && minDurations.data.i64[i+1] == stream->getWidth()
1847 && minDurations.data.i64[i+2] == stream->getHeight()) {
1848 int64_t minFrameDuration = minDurations.data.i64[i+3];
1849 return 1e9f / minFrameDuration;
1850 }
1851 }
1852 return 0.0f;
1853}
1854
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001855/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 * Methods called by subclasses
1857 */
1858
1859void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001860 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001861 std::vector<int> streamIds;
1862 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001863 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001864
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 {
1866 // Need mLock to safely update state and synchronize to current
1867 // state of methods in flight.
1868 Mutex::Autolock l(mLock);
1869 // We can get various system-idle notices from the status tracker
1870 // while starting up. Only care about them if we've actually sent
1871 // in some requests recently.
1872 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1873 return;
1874 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001875 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1876 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001877 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878
1879 // Skip notifying listener if we're doing some user-transparent
1880 // state changes
1881 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001882
Austin Borger4a870a32022-02-25 01:48:41 +00001883 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1884 auto stream = mOutputStreams[i];
1885 if (stream.get() == nullptr) continue;
1886
1887 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1888 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1889
1890 // Populate stream statistics in case of Idle
1891 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001892 streamIds.push_back(stream->getId());
1893 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1894 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001895 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001896 if (camera3Stream != nullptr) {
1897 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001898 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001899 }
1900 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001901 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001902 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001903 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001904 stream->getDynamicRangeProfile(), streamUseCase,
1905 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001906 }
1907 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001908 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001909
1910 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001911 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001912 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001913 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001914 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001915 status_t res = OK;
1916 if (listener != nullptr) {
1917 if (idle) {
1918 // Get session stats from the builder, and notify the listener.
1919 int64_t requestCount, resultErrorCount;
1920 bool deviceError;
1921 std::map<int, StreamStats> streamStatsMap;
1922 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1923 &deviceError, &streamStatsMap);
1924 for (size_t i = 0; i < streamIds.size(); i++) {
1925 int streamId = streamIds[i];
1926 auto stats = streamStatsMap.find(streamId);
1927 if (stats != streamStatsMap.end()) {
1928 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1929 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1930 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1931 streamStats[i].mHistogramType =
1932 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1933 streamStats[i].mHistogramBins.assign(
1934 stats->second.mCaptureLatencyBins.begin(),
1935 stats->second.mCaptureLatencyBins.end());
1936 streamStats[i].mHistogramCounts.assign(
1937 stats->second.mCaptureLatencyHistogram.begin(),
1938 stats->second.mCaptureLatencyHistogram.end());
1939 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001940 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001941 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1942 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001943 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001944 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001945 }
1946 if (res != OK) {
1947 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1948 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949 }
1950}
1951
Shuzhen Wang758c2152017-01-10 18:26:18 -08001952status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001953 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001954 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001955 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1956 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001957
1958 if (surfaceIds == nullptr) {
1959 return BAD_VALUE;
1960 }
1961
Zhijun He5d677d12016-05-29 16:52:39 -07001962 Mutex::Autolock il(mInterfaceLock);
1963 Mutex::Autolock l(mLock);
1964
Shuzhen Wang758c2152017-01-10 18:26:18 -08001965 if (consumers.size() == 0) {
1966 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001967 return BAD_VALUE;
1968 }
1969
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001970 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1971 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001972 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001973 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001974 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001975
1976 // isConsumerConfigurationDeferred will be off after setConsumers
1977 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001978 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001979 if (res != OK) {
1980 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1981 return res;
1982 }
1983
Emilian Peev40ead602017-09-26 15:46:36 +01001984 for (auto &consumer : consumers) {
1985 int id = stream->getSurfaceId(consumer);
1986 if (id < 0) {
1987 CLOGE("Invalid surface id!");
1988 return BAD_VALUE;
1989 }
1990 surfaceIds->push_back(id);
1991 }
1992
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001993 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001994 if (!stream->isConfiguring()) {
1995 CLOGE("Stream %d was already fully configured.", streamId);
1996 return INVALID_OPERATION;
1997 }
Zhijun He5d677d12016-05-29 16:52:39 -07001998
Shuzhen Wang0129d522016-10-30 22:43:41 -07001999 res = stream->finishConfiguration();
2000 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002001 // If finishConfiguration fails due to abandoned surface, do not set
2002 // device to error state.
2003 bool isSurfaceAbandoned =
2004 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2005 if (!isSurfaceAbandoned) {
2006 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2007 stream->getId(), strerror(-res), res);
2008 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002009 return res;
2010 }
Zhijun He5d677d12016-05-29 16:52:39 -07002011 }
2012
2013 return OK;
2014}
2015
Emilian Peev40ead602017-09-26 15:46:36 +01002016status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2017 const std::vector<OutputStreamInfo> &outputInfo,
2018 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2019 Mutex::Autolock il(mInterfaceLock);
2020 Mutex::Autolock l(mLock);
2021
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002022 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2023 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002024 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002025 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002026 }
2027
2028 for (const auto &it : removedSurfaceIds) {
2029 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2030 CLOGE("Shared surface still part of a pending request!");
2031 return -EBUSY;
2032 }
2033 }
2034
Emilian Peev40ead602017-09-26 15:46:36 +01002035 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2036 if (res != OK) {
2037 CLOGE("Stream %d failed to update stream (error %d %s) ",
2038 streamId, res, strerror(-res));
2039 if (res == UNKNOWN_ERROR) {
2040 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2041 __FUNCTION__);
2042 }
2043 return res;
2044 }
2045
2046 return res;
2047}
2048
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002049status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2050 Mutex::Autolock il(mInterfaceLock);
2051 Mutex::Autolock l(mLock);
2052
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002053 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2054 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002055 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2056 return BAD_VALUE;
2057 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002058
2059 if (dropping) {
2060 mSessionStatsBuilder.stopCounter(streamId);
2061 } else {
2062 mSessionStatsBuilder.startCounter(streamId);
2063 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002064 return stream->dropBuffers(dropping);
2065}
2066
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002067/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002068 * Camera3Device private methods
2069 */
2070
2071sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002072 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002075 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002076 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002077
2078 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002079 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 if (inputStreams.count > 0) {
2081 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002082 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002083 CLOGE("Request references unknown input stream %d",
2084 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002085 return NULL;
2086 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002087
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002089 SET_ERR_L("%s: input stream %d is not configured!",
2090 __FUNCTION__, mInputStream->getId());
2091 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002093 // Check if stream prepare is blocking requests.
2094 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002095 CLOGE("Request references an input stream that's being prepared!");
2096 return NULL;
2097 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098
2099 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002100 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002101 }
2102
2103 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002104 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002106 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 return NULL;
2108 }
2109
2110 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002111 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2112 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002113 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002114 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 return NULL;
2116 }
Zhijun He5d677d12016-05-29 16:52:39 -07002117 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002118 auto iter = surfaceMap.find(streams.data.i32[i]);
2119 if (iter != surfaceMap.end()) {
2120 const std::vector<size_t>& surfaces = iter->second;
2121 for (const auto& surface : surfaces) {
2122 if (stream->isConsumerConfigurationDeferred(surface)) {
2123 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2124 "due to deferred consumer", stream->getId(), surface);
2125 return NULL;
2126 }
2127 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002128 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002129 }
2130
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002131 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002132 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2133 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002134 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002135 // Check if stream prepare is blocking requests.
2136 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002137 CLOGE("Request references an output stream that's being prepared!");
2138 return NULL;
2139 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002140
2141 newRequest->mOutputStreams.push(stream);
2142 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002143 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002144 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002146 auto rotateAndCropEntry =
2147 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2148 if (rotateAndCropEntry.count > 0 &&
2149 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2150 newRequest->mRotateAndCropAuto = true;
2151 } else {
2152 newRequest->mRotateAndCropAuto = false;
2153 }
2154
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002155 auto autoframingEntry =
2156 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2157 if (autoframingEntry.count > 0 &&
2158 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2159 newRequest->mAutoframingAuto = true;
2160 } else {
2161 newRequest->mAutoframingAuto = false;
2162 }
2163
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002164 auto zoomRatioEntry =
2165 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2166 if (zoomRatioEntry.count > 0 &&
2167 zoomRatioEntry.data.f[0] == 1.0f) {
2168 newRequest->mZoomRatioIs1x = true;
2169 } else {
2170 newRequest->mZoomRatioIs1x = false;
2171 }
2172
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002173 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002174 for (auto& settings : newRequest->mSettingsList) {
2175 auto testPatternModeEntry =
2176 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2177 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2178 testPatternModeEntry.data.i32[0] :
2179 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002180
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002181 auto testPatternDataEntry =
2182 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2183 if (testPatternDataEntry.count >= 4) {
2184 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2185 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2186 } else {
2187 settings.mOriginalTestPatternData[0] = 0;
2188 settings.mOriginalTestPatternData[1] = 0;
2189 settings.mOriginalTestPatternData[2] = 0;
2190 settings.mOriginalTestPatternData[3] = 0;
2191 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002192 }
2193 }
2194
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002196}
2197
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002198void Camera3Device::cancelStreamsConfigurationLocked() {
2199 int res = OK;
2200 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2201 res = mInputStream->cancelConfiguration();
2202 if (res != OK) {
2203 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2204 mInputStream->getId(), strerror(-res), res);
2205 }
2206 }
2207
2208 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002209 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002210 if (outputStream->isConfiguring()) {
2211 res = outputStream->cancelConfiguration();
2212 if (res != OK) {
2213 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2214 outputStream->getId(), strerror(-res), res);
2215 }
2216 }
2217 }
2218
2219 // Return state to that at start of call, so that future configures
2220 // properly clean things up
2221 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2222 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002223
2224 res = mPreparerThread->resume();
2225 if (res != OK) {
2226 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2227 }
2228}
2229
Emilian Peev0d0191e2020-04-21 17:01:18 -07002230bool Camera3Device::checkAbandonedStreamsLocked() {
2231 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2232 return true;
2233 }
2234
2235 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2236 auto stream = mOutputStreams[i];
2237 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2238 return true;
2239 }
2240 }
2241
2242 return false;
2243}
2244
Emilian Peev3bead5f2020-05-28 17:29:08 -07002245bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002246 ATRACE_CALL();
2247 bool ret = false;
2248
Shuzhen Wang316781a2020-08-18 18:11:01 -07002249 nsecs_t startTime = systemTime();
2250
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002251 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002252 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2253
2254 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002255 if (checkAbandonedStreamsLocked()) {
2256 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2257 __FUNCTION__);
2258 return true;
2259 }
2260
Emilian Peev3bead5f2020-05-28 17:29:08 -07002261 status_t rc = NO_ERROR;
2262 bool markClientActive = false;
2263 if (mStatus == STATUS_ACTIVE) {
2264 markClientActive = true;
2265 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002266
2267 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2268 }
2269
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002270 if (rc == NO_ERROR) {
2271 mNeedConfig = true;
2272 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2273 if (rc == NO_ERROR) {
2274 ret = true;
2275 mPauseStateNotify = false;
2276 //Moving to active state while holding 'mLock' is important.
2277 //There could be pending calls to 'create-/deleteStream' which
2278 //will trigger another stream configuration while the already
2279 //present streams end up with outstanding buffers that will
2280 //not get drained.
2281 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002282 } else if (rc == DEAD_OBJECT) {
2283 // DEAD_OBJECT can be returned if either the consumer surface is
2284 // abandoned, or the HAL has died.
2285 // - If the HAL has died, configureStreamsLocked call will set
2286 // device to error state,
2287 // - If surface is abandoned, we should not set device to error
2288 // state.
2289 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002290 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002291 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002292 }
2293 } else {
2294 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2295 }
2296
Austin Borger74fca042022-05-23 12:41:21 -07002297 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002298 ns2ms(systemTime() - startTime));
2299
Emilian Peev3bead5f2020-05-28 17:29:08 -07002300 if (markClientActive) {
2301 mStatusTracker->markComponentActive(clientStatusId);
2302 }
2303
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002304 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002305}
2306
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002307status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002308 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002309 ATRACE_CALL();
2310 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002311
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002312 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002313 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002314 return INVALID_OPERATION;
2315 }
2316
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002317 if (operatingMode < 0) {
2318 CLOGE("Invalid operating mode: %d", operatingMode);
2319 return BAD_VALUE;
2320 }
2321
2322 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002323 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002324
2325 if (mOperatingMode != operatingMode) {
2326 mNeedConfig = true;
2327 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2328 mOperatingMode = operatingMode;
2329 }
2330
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002331 // Reset min expected duration when session is reconfigured.
2332 mMinExpectedDuration = 0;
2333
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002334 // In case called from configureStreams, abort queued input buffers not belonging to
2335 // any pending requests.
2336 if (mInputStream != NULL && notifyRequestThread) {
2337 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002338 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002339 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002340 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002341 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002342 if (res != OK) {
2343 // Exhausted acquiring all input buffers.
2344 break;
2345 }
2346
Emilian Peevf4816702020-04-03 15:44:51 -07002347 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002348 res = mInputStream->returnInputBuffer(inputBuffer);
2349 if (res != OK) {
2350 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2351 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2352 }
2353 }
2354 }
2355
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002356 if (!mNeedConfig) {
2357 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2358 return OK;
2359 }
2360
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002361 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002362 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002363 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2364 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002365 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002366 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002367 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002368 }
2369
Shuzhen Wang16610a62022-12-15 22:38:07 -08002370 // Override stream use case based on "adb shell command"
2371 overrideStreamUseCaseLocked();
2372
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002374 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002376 mPreparerThread->pause();
2377
Emilian Peevf4816702020-04-03 15:44:51 -07002378 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002379 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002381 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382
Emilian Peevf4816702020-04-03 15:44:51 -07002383 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002384 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002385 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002386
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002387
2388 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002389 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 inputStream = mInputStream->startConfiguration();
2391 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002392 CLOGE("Can't start input stream configuration");
2393 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394 return INVALID_OPERATION;
2395 }
2396 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002397
2398 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002399 }
2400
Shuzhen Wang99080502021-03-07 21:08:20 -08002401 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002402 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002403 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002404
2405 // Don't configure bidi streams twice, nor add them twice to the list
2406 if (mOutputStreams[i].get() ==
2407 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2408
2409 config.num_streams--;
2410 continue;
2411 }
2412
Emilian Peevf4816702020-04-03 15:44:51 -07002413 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002414 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002415 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002416 CLOGE("Can't start output stream configuration");
2417 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002418 return INVALID_OPERATION;
2419 }
2420 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002421
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002422 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002423 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2424 // always occupy the initial entry.
Emilian Peeve579d8b2023-02-28 14:16:08 -08002425 if ((outputStream->data_space == HAL_DATASPACE_V0_JFIF) ||
2426 (outputStream->data_space ==
2427 static_cast<android_dataspace_t>(
2428 aidl::android::hardware::graphics::common::Dataspace::JPEG_R))) {
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002429 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002430 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2431 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002432 } else if (outputStream->data_space ==
2433 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2434 bufferSizes[k] = outputStream->width * outputStream->height;
2435 } else {
2436 ALOGW("%s: Blob dataSpace %d not supported",
2437 __FUNCTION__, outputStream->data_space);
2438 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002439 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002440
2441 if (mOutputStreams[i]->isMultiResolution()) {
2442 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2443 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2444 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2445 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002446
2447 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2448 composerSurfacePresent = true;
2449 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002450 }
2451
2452 config.streams = streams.editArray();
2453
2454 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002455 // max_buffers, usage, and priv fields, as well as data_space and format
2456 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002457
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002458 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002459 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002460 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002461 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002462
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002463 if (res == BAD_VALUE) {
2464 // HAL rejected this set of streams as unsupported, clean up config
2465 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002466 CLOGE("Set of requested inputs/outputs not supported by HAL");
2467 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002468 return BAD_VALUE;
2469 } else if (res != OK) {
2470 // Some other kind of error from configure_streams - this is not
2471 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002472 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2473 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002474 return res;
2475 }
2476
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002477 // Finish all stream configuration immediately.
2478 // TODO: Try to relax this later back to lazy completion, which should be
2479 // faster
2480
Igor Murashkin073f8572013-05-02 14:59:28 -07002481 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002482 bool streamReConfigured = false;
2483 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002484 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002485 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002486 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002487 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002488 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2489 return DEAD_OBJECT;
2490 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002491 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002492 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002493 if (streamReConfigured) {
2494 mInterface->onStreamReConfigured(mInputStream->getId());
2495 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002496 }
2497
2498 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002499 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002500 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002501 bool streamReConfigured = false;
2502 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002503 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002505 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002506 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002507 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2508 return DEAD_OBJECT;
2509 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002510 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002511 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002512 if (streamReConfigured) {
2513 mInterface->onStreamReConfigured(outputStream->getId());
2514 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002515 }
2516 }
2517
Emilian Peeve23f1d92021-09-20 14:56:01 -07002518 mRequestThread->setComposerSurface(composerSurfacePresent);
2519
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520 // Request thread needs to know to avoid using repeat-last-settings protocol
2521 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002522 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002523 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2524 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002525 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526
Zhijun He90f7c372016-08-16 16:19:43 -07002527 char value[PROPERTY_VALUE_MAX];
2528 property_get("camera.fifo.disable", value, "0");
2529 int32_t disableFifo = atoi(value);
2530 if (disableFifo != 1) {
2531 // Boost priority of request thread to SCHED_FIFO.
2532 pid_t requestThreadTid = mRequestThread->getTid();
2533 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002534 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002535 if (res != OK) {
2536 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2537 strerror(-res), res);
2538 } else {
2539 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2540 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002541 }
2542
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002543 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002544 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2545 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2546 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2547 sessionParams.unlock(newSessionParams);
2548 mSessionParams.unlock(currentSessionParams);
2549 if (updateSessionParams) {
2550 mSessionParams = sessionParams;
2551 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002553 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002554
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002556 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002557
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002558 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002559
Zhijun He0a210512014-07-24 13:45:15 -07002560 // tear down the deleted streams after configure streams.
2561 mDeletedStreams.clear();
2562
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002563 auto rc = mPreparerThread->resume();
2564 if (rc != OK) {
2565 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2566 return rc;
2567 }
2568
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002569 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002570 mRequestBufferSM.onStreamsConfigured();
2571 }
2572
Cliff Wu3b268182021-07-06 15:44:43 +08002573 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002574 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002575 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002576 // configure the injection streams.
2577 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002578 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002579 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2580 res = mInjectionMethods->injectCamera(config, bufferSizes);
2581 if (res != OK) {
2582 ALOGE("Can't finish inject camera process!");
2583 return res;
2584 }
Cliff Wu3b268182021-07-06 15:44:43 +08002585 } else {
2586 // First run configureStreamsLocked() and then call injectCamera() case:
2587 // If the stream configuration has been completed and camera deive is active, but the
2588 // injection camera has not been injected yet, we need to store the stream configuration of
2589 // the internal camera (because the stream configuration of the injection camera is based
2590 // on the internal camera). When injecting occurs later, this configuration can be used by
2591 // the injection camera.
2592 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2593 " injection camera has not been injected yet.", __FUNCTION__);
2594 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002595 }
2596
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002598}
2599
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002600status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002601 ATRACE_CALL();
2602 status_t res;
2603
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002604 if (mFakeStreamId != NO_STREAM) {
2605 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002606 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002607 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002608 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002609 return INVALID_OPERATION;
2610 }
2611
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002612 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002613
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002614 sp<Camera3OutputStreamInterface> fakeStream =
2615 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002616
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002619 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002620 return res;
2621 }
2622
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002623 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002624 mNextStreamId++;
2625
2626 return OK;
2627}
2628
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002629status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002630 ATRACE_CALL();
2631 status_t res;
2632
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002633 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002634 if (mOutputStreams.size() == 1) return OK;
2635
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002636 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002637
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002638 // Ok, have a fake stream and there's at least one other output stream,
2639 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002640
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002642 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002643 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002644 return INVALID_OPERATION;
2645 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647
2648 // Free up the stream endpoint so that it can be used by some other stream
2649 res = deletedStream->disconnect();
2650 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002651 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002652 // fall through since we want to still list the stream as deleted.
2653 }
2654 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002655 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002656
2657 return res;
2658}
2659
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002660void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002661 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002662 Mutex::Autolock l(mLock);
2663 va_list args;
2664 va_start(args, fmt);
2665
2666 setErrorStateLockedV(fmt, args);
2667
2668 va_end(args);
2669}
2670
2671void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002672 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002673 Mutex::Autolock l(mLock);
2674 setErrorStateLockedV(fmt, args);
2675}
2676
2677void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2678 va_list args;
2679 va_start(args, fmt);
2680
2681 setErrorStateLockedV(fmt, args);
2682
2683 va_end(args);
2684}
2685
2686void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002687 // Print out all error messages to log
2688 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002689 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002690
2691 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002692 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002693
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002694 mErrorCause = errorCause;
2695
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002696 if (mRequestThread != nullptr) {
2697 mRequestThread->setPaused(true);
2698 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002699 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002700
2701 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002702 sp<NotificationListener> listener = mListener.promote();
2703 if (listener != NULL) {
2704 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002705 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002706 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002707 }
2708
2709 // Save stack trace. View by dumping it later.
2710 CameraTraces::saveTrace();
2711 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002712}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002713
2714/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002715 * In-flight request management
2716 */
2717
Jianing Weicb0652e2014-03-12 18:29:36 -07002718status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002719 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002720 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002721 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002722 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002723 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002724 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002725 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002726 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002727
2728 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002729 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002730 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002731 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2732 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002733 if (res < 0) return res;
2734
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002735 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002736 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2737 // avoid a deadlock during reprocess requests.
2738 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002739 if (mStatusTracker != nullptr) {
2740 mStatusTracker->markComponentActive(mInFlightStatusId);
2741 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002742 }
2743
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002744 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002745 return OK;
2746}
2747
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002748void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002749 // Indicate idle inFlightMap to the status tracker
2750 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002751 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002752 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2753 // avoid a deadlock during reprocess requests.
2754 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002755 if (mStatusTracker != nullptr) {
2756 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2757 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002758 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002759 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002760}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002761
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002762void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002763 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002764 // something has likely gone wrong. This might still be legit only if application send in
2765 // a long burst of long exposure requests.
2766 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2767 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2768 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2769 mInFlightMap.size(), mExpectedInflightDuration);
2770 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2771 kInFlightWarnLimitHighSpeed) {
2772 CLOGW("In-flight list too large for high speed configuration: %zu,"
2773 "total inflight duration %" PRIu64,
2774 mInFlightMap.size(), mExpectedInflightDuration);
2775 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002776 }
2777}
2778
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002779void Camera3Device::onInflightMapFlushedLocked() {
2780 mExpectedInflightDuration = 0;
2781}
2782
2783void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002784 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002785 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2786 mInFlightMap.removeItemsAt(idx, 1);
2787
2788 onInflightEntryRemovedLocked(duration);
2789}
2790
2791
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002792void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002793 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002794 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002795 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002796 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002797 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002798 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002799
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 FlushInflightReqStates states {
2801 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002802 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002803
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002804 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002805}
2806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002807CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002808 ALOGV("%s", __FUNCTION__);
2809
Igor Murashkin1e479c02013-09-06 16:55:14 -07002810 CameraMetadata retVal;
2811
2812 if (mRequestThread != NULL) {
2813 retVal = mRequestThread->getLatestRequest();
2814 }
2815
Igor Murashkin1e479c02013-09-06 16:55:14 -07002816 return retVal;
2817}
2818
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002819void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002820 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002821 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002822 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2823 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002824
2825 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002826 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002827}
2828
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002829void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002830 std::vector<native_handle_t*> *handles, bool closeFd) {
2831 if (handles == nullptr) {
2832 return;
2833 }
2834 if (closeFd) {
2835 for (auto& handle : *handles) {
2836 native_handle_close(handle);
2837 }
2838 }
2839 for (auto& handle : *handles) {
2840 native_handle_delete(handle);
2841 }
2842 handles->clear();
2843 return;
2844}
2845
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002846/**
2847 * HalInterface inner class methods
2848 */
2849
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002850void Camera3Device::HalInterface::getInflightBufferKeys(
2851 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002852 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002853 return;
2854}
2855
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002856void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2857 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002858 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002859 return;
2860}
2861
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002862bool Camera3Device::HalInterface::verifyBufferIds(
2863 int32_t streamId, std::vector<uint64_t>& bufIds) {
2864 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002865}
2866
2867status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002868 int32_t frameNumber, int32_t streamId,
2869 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002870 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002871}
2872
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002873status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002874 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002875 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002876}
2877
2878// Find and pop a buffer_handle_t based on bufferId
2879status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002880 uint64_t bufferId,
2881 /*out*/ buffer_handle_t** buffer,
2882 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002883 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002884}
2885
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002886std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2887 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002888 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002889}
2890
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002891uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2892 const native_handle_t* handle) {
2893 return mBufferRecords.removeOneBufferCache(streamId, handle);
2894}
2895
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002896void Camera3Device::HalInterface::onBufferFreed(
2897 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002898 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2899 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2900 if (bufferId != BUFFER_ID_NO_BUFFER) {
2901 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002902 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002903}
2904
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002905void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002906 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2907 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2908 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002909 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2910 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002911}
2912
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002913/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002914 * RequestThread inner class methods
2915 */
2916
2917Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002918 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002919 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002920 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002921 bool supportCameraMute,
2922 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002923 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002924 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002925 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002926 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002927 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002928 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002929 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002930 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002931 mReconfigured(false),
2932 mDoPause(false),
2933 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002934 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002935 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002936 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002937 mCurrentAfTriggerId(0),
2938 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002939 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00002940 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002941 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002942 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002943 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002944 mRepeatingLastFrameNumber(
2945 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002946 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002947 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002948 mRequestLatency(kRequestLatencyBinSize),
2949 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002950 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002951 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07002952 mSupportCameraMute(supportCameraMute),
2953 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002954 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08002955 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002956}
2957
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002958Camera3Device::RequestThread::~RequestThread() {}
2959
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002960void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002961 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002962 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002963 Mutex::Autolock l(mRequestLock);
2964 mListener = listener;
2965}
2966
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002967void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002968 const CameraMetadata& sessionParams,
2969 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002970 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971 Mutex::Autolock l(mRequestLock);
2972 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002973 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002974 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002975 // Prepare video stream for high speed recording.
2976 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002977 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978}
2979
Jianing Wei90e59c92014-03-12 18:29:36 -07002980status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002981 List<sp<CaptureRequest> > &requests,
2982 /*out*/
2983 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002984 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002985 Mutex::Autolock l(mRequestLock);
2986 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2987 ++it) {
2988 mRequestQueue.push_back(*it);
2989 }
2990
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002991 if (lastFrameNumber != NULL) {
2992 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2993 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2994 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2995 *lastFrameNumber);
2996 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002997
Jianing Wei90e59c92014-03-12 18:29:36 -07002998 unpauseForNewRequests();
2999
3000 return OK;
3001}
3002
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003003
3004status_t Camera3Device::RequestThread::queueTrigger(
3005 RequestTrigger trigger[],
3006 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003007 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003008 Mutex::Autolock l(mTriggerMutex);
3009 status_t ret;
3010
3011 for (size_t i = 0; i < count; ++i) {
3012 ret = queueTriggerLocked(trigger[i]);
3013
3014 if (ret != OK) {
3015 return ret;
3016 }
3017 }
3018
3019 return OK;
3020}
3021
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003022const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3023 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003024 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003025 if (d != nullptr) return d->mId;
3026 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003027}
3028
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003029status_t Camera3Device::RequestThread::queueTriggerLocked(
3030 RequestTrigger trigger) {
3031
3032 uint32_t tag = trigger.metadataTag;
3033 ssize_t index = mTriggerMap.indexOfKey(tag);
3034
3035 switch (trigger.getTagType()) {
3036 case TYPE_BYTE:
3037 // fall-through
3038 case TYPE_INT32:
3039 break;
3040 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003041 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3042 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003043 return INVALID_OPERATION;
3044 }
3045
3046 /**
3047 * Collect only the latest trigger, since we only have 1 field
3048 * in the request settings per trigger tag, and can't send more than 1
3049 * trigger per request.
3050 */
3051 if (index != NAME_NOT_FOUND) {
3052 mTriggerMap.editValueAt(index) = trigger;
3053 } else {
3054 mTriggerMap.add(tag, trigger);
3055 }
3056
3057 return OK;
3058}
3059
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003060status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003061 const RequestList &requests,
3062 /*out*/
3063 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003064 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003065 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003066 if (lastFrameNumber != NULL) {
3067 *lastFrameNumber = mRepeatingLastFrameNumber;
3068 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003069 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003070 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003071 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3072 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003073
3074 unpauseForNewRequests();
3075
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003076 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003077 return OK;
3078}
3079
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003080bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003081 if (mRepeatingRequests.empty()) {
3082 return false;
3083 }
3084 int32_t requestId = requestIn->mResultExtras.requestId;
3085 const RequestList &repeatRequests = mRepeatingRequests;
3086 // All repeating requests are guaranteed to have same id so only check first quest
3087 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3088 return (firstRequest->mResultExtras.requestId == requestId);
3089}
3090
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003091status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003092 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003093 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003094 return clearRepeatingRequestsLocked(lastFrameNumber);
3095
3096}
3097
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003098status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3099 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003100 std::vector<int32_t> streamIds;
3101 for (const auto& request : mRepeatingRequests) {
3102 for (const auto& stream : request->mOutputStreams) {
3103 streamIds.push_back(stream->getId());
3104 }
3105 }
3106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003107 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003108 if (lastFrameNumber != NULL) {
3109 *lastFrameNumber = mRepeatingLastFrameNumber;
3110 }
Emilian Peev2295df72021-11-12 18:14:10 -08003111
3112 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3113
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003114 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003115 return OK;
3116}
3117
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003118status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003120 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003121 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003122 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003123
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003124 // Send errors for all requests pending in the request queue, including
3125 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003126 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003127 if (listener != NULL) {
3128 for (RequestList::iterator it = mRequestQueue.begin();
3129 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003130 // Abort the input buffers for reprocess requests.
3131 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003132 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003133 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003134 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003135 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003136 if (res != OK) {
3137 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3138 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3139 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003140 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003141 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3142 if (res != OK) {
3143 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3144 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3145 }
3146 }
3147 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003148 // Set the frame number this request would have had, if it
3149 // had been submitted; this frame number will not be reused.
3150 // The requestId and burstId fields were set when the request was
3151 // submitted originally (in convertMetadataListToRequestListLocked)
3152 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003153 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003154 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003155 }
3156 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003157 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003158
3159 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003160 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003161 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003162 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003163 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003164 return OK;
3165}
3166
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003167status_t Camera3Device::RequestThread::flush() {
3168 ATRACE_CALL();
3169 Mutex::Autolock l(mFlushLock);
3170
Emilian Peev08dd2452017-04-06 16:55:14 +01003171 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003172}
3173
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003174void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003175 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003176 Mutex::Autolock l(mPauseLock);
3177 mDoPause = paused;
3178 mDoPauseSignal.signal();
3179}
3180
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003181status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3182 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003183 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003184 Mutex::Autolock l(mLatestRequestMutex);
3185 status_t res;
3186 while (mLatestRequestId != requestId) {
3187 nsecs_t startTime = systemTime();
3188
3189 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3190 if (res != OK) return res;
3191
3192 timeout -= (systemTime() - startTime);
3193 }
3194
3195 return OK;
3196}
3197
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003198void Camera3Device::RequestThread::requestExit() {
3199 // Call parent to set up shutdown
3200 Thread::requestExit();
3201 // The exit from any possible waits
3202 mDoPauseSignal.signal();
3203 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003204
3205 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3206 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003207}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003208
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003209void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003210 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003211 bool surfaceAbandoned = false;
3212 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003213 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003214 {
3215 Mutex::Autolock l(mRequestLock);
3216 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3217 // repeating requests.
3218 for (const auto& request : mRepeatingRequests) {
3219 for (const auto& s : request->mOutputStreams) {
3220 if (s->isAbandoned()) {
3221 surfaceAbandoned = true;
3222 clearRepeatingRequestsLocked(&lastFrameNumber);
3223 break;
3224 }
3225 }
3226 if (surfaceAbandoned) {
3227 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003228 }
3229 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003230 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003231 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003232
3233 if (listener != NULL && surfaceAbandoned) {
3234 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003235 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003236}
3237
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003238bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003239 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003240 status_t res;
3241 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003242 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003243 uint32_t numRequestProcessed = 0;
3244 for (size_t i = 0; i < batchSize; i++) {
3245 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003246 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003247 }
3248
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003249 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3250
3251 bool triggerRemoveFailed = false;
3252 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3253 for (size_t i = 0; i < numRequestProcessed; i++) {
3254 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3255 nextRequest.submitted = true;
3256
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003257 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003258
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003259 if (!triggerRemoveFailed) {
3260 // Remove any previously queued triggers (after unlock)
3261 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3262 if (removeTriggerRes != OK) {
3263 triggerRemoveFailed = true;
3264 triggerFailedRequest = nextRequest;
3265 }
3266 }
3267 }
3268
3269 if (triggerRemoveFailed) {
3270 SET_ERR("RequestThread: Unable to remove triggers "
3271 "(capture request %d, HAL device: %s (%d)",
3272 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3273 cleanUpFailedRequests(/*sendRequestError*/ false);
3274 return false;
3275 }
3276
3277 if (res != OK) {
3278 // Should only get a failure here for malformed requests or device-level
3279 // errors, so consider all errors fatal. Bad metadata failures should
3280 // come through notify.
3281 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3282 mNextRequests[numRequestProcessed].halRequest.frame_number,
3283 strerror(-res), res);
3284 cleanUpFailedRequests(/*sendRequestError*/ false);
3285 return false;
3286 }
3287 return true;
3288}
3289
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003290Camera3Device::RequestThread::ExpectedDurationInfo
3291 Camera3Device::RequestThread::calculateExpectedDurationRange(
3292 const camera_metadata_t *request) {
3293 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003294 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003295 InFlightRequest::kDefaultMaxExpectedDuration,
3296 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003297 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3298 find_camera_metadata_ro_entry(request,
3299 ANDROID_CONTROL_AE_MODE,
3300 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003301 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003302
3303 switch (e.data.u8[0]) {
3304 case ANDROID_CONTROL_AE_MODE_OFF:
3305 find_camera_metadata_ro_entry(request,
3306 ANDROID_SENSOR_EXPOSURE_TIME,
3307 &e);
3308 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003309 expectedDurationInfo.minDuration = e.data.i64[0];
3310 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003311 }
3312 find_camera_metadata_ro_entry(request,
3313 ANDROID_SENSOR_FRAME_DURATION,
3314 &e);
3315 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003316 expectedDurationInfo.minDuration =
3317 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3318 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003319 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003320 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003321 break;
3322 default:
3323 find_camera_metadata_ro_entry(request,
3324 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3325 &e);
3326 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003327 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3328 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003329 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003330 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003331 break;
3332 }
3333
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003334 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003335}
3336
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003337bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3338 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3339 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3340 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3341 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3342 return true;
3343 }
3344
3345 return false;
3346}
3347
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003348void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3349 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003350 camera_capture_request_t& halRequest = nextRequest.halRequest;
3351 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003352 Mutex::Autolock al(mLatestRequestMutex);
3353
Shuzhen Wang83bff122020-11-20 15:51:39 -08003354 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003355 mLatestRequest.acquire(cloned);
3356
3357 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003358 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3359 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3360 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003361 CameraMetadata(cloned));
3362 }
3363
3364 sp<Camera3Device> parent = mParent.promote();
3365 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003366 int32_t inputStreamId = -1;
3367 if (halRequest.input_buffer != nullptr) {
3368 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3369 }
3370
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003371 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003372 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003373 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3374 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003375 }
3376 }
3377
Shuzhen Wang83bff122020-11-20 15:51:39 -08003378 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003379 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003380 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003381 }
3382
Shuzhen Wang83bff122020-11-20 15:51:39 -08003383 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003384}
3385
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003386bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3387 ATRACE_CALL();
3388 bool updatesDetected = false;
3389
Emilian Peev4ec17882019-01-24 17:16:58 -08003390 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003391 for (auto tag : mSessionParamKeys) {
3392 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003393 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003394
3395 if (entry.count > 0) {
3396 bool isDifferent = false;
3397 if (lastEntry.count > 0) {
3398 // Have a last value, compare to see if changed
3399 if (lastEntry.type == entry.type &&
3400 lastEntry.count == entry.count) {
3401 // Same type and count, compare values
3402 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3403 size_t entryBytes = bytesPerValue * lastEntry.count;
3404 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3405 if (cmp != 0) {
3406 isDifferent = true;
3407 }
3408 } else {
3409 // Count or type has changed
3410 isDifferent = true;
3411 }
3412 } else {
3413 // No last entry, so always consider to be different
3414 isDifferent = true;
3415 }
3416
3417 if (isDifferent) {
3418 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003419 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3420 updatesDetected = true;
3421 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003422 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003423 }
3424 } else if (lastEntry.count > 0) {
3425 // Value has been removed
3426 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003427 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003428 updatesDetected = true;
3429 }
3430 }
3431
Emilian Peev4ec17882019-01-24 17:16:58 -08003432 bool reconfigureRequired;
3433 if (updatesDetected) {
3434 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3435 updatedParams);
3436 mLatestSessionParams = updatedParams;
3437 } else {
3438 reconfigureRequired = false;
3439 }
3440
3441 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003442}
3443
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003444bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003445 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003447 // Any function called from threadLoop() must not hold mInterfaceLock since
3448 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3449 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003450
3451 // Handle paused state.
3452 if (waitIfPaused()) {
3453 return true;
3454 }
3455
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003456 // Wait for the next batch of requests.
3457 waitForNextRequestBatch();
3458 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003459 return true;
3460 }
3461
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003462 // Get the latest request ID, if any
3463 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003464 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003465 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003466 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003467 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003468 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003469 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3470 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003471 }
3472
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003473 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3474 // or a single request from streaming or burst. In either case the first element
3475 // should contain the latest camera settings that we need to check for any session
3476 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003477 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003478 res = OK;
3479
3480 //Input stream buffers are already acquired at this point so an input stream
3481 //will not be able to move to idle state unless we force it.
3482 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3483 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3484 if (res != OK) {
3485 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3486 cleanUpFailedRequests(/*sendRequestError*/ false);
3487 return false;
3488 }
3489 }
3490
3491 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003492 sp<Camera3Device> parent = mParent.promote();
3493 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003494 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3495 if (statusTracker != nullptr) {
3496 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3497 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003498 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003499 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003500 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003501
3502 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3503 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3504 if (res != OK) {
3505 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3506 cleanUpFailedRequests(/*sendRequestError*/ false);
3507 return false;
3508 }
3509 }
3510 }
3511 }
3512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003513 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003514 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003515 if (res == TIMED_OUT) {
3516 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003517 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003518 // Check if any stream is abandoned.
3519 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003520 return true;
3521 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003522 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003523 return false;
3524 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003525
Zhijun Hecc27e112013-10-03 16:12:43 -07003526 // Inform waitUntilRequestProcessed thread of a new request ID
3527 {
3528 Mutex::Autolock al(mLatestRequestMutex);
3529
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003530 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003531 mLatestRequestSignal.signal();
3532 }
3533
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003534 // Submit a batch of requests to HAL.
3535 // Use flush lock only when submitting multilple requests in a batch.
3536 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3537 // which may take a long time to finish so synchronizing flush() and
3538 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3539 // For now, only synchronize for high speed recording and we should figure something out for
3540 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003541 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003542
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003543 if (useFlushLock) {
3544 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003545 }
3546
Zhijun Hef0645c12016-08-02 00:58:11 -07003547 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003548 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003549
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003550 sp<Camera3Device> parent = mParent.promote();
3551 if (parent != nullptr) {
3552 parent->mRequestBufferSM.onSubmittingRequest();
3553 }
3554
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003555 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003556 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003557 submitRequestSuccess = sendRequestsBatch();
3558
Shuzhen Wang686f6442017-06-20 16:16:04 -07003559 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3560 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003561
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003562 if (useFlushLock) {
3563 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003564 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003565
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003566 // Unset as current request
3567 {
3568 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003569 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003570 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003571 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003572
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003573 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003574}
3575
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003576status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3577 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3578 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3579 ANDROID_SCALER_CROP_REGION_SET};
3580 if (request == nullptr) {
3581 ALOGE("%s request metadata nullptr", __FUNCTION__);
3582 return BAD_VALUE;
3583 }
3584 status_t res = OK;
3585 for (const auto &key : kFwkOnlyRegionKeys) {
3586 if (request->exists(key)) {
3587 res = request->erase(key);
3588 if (res != OK) {
3589 return res;
3590 }
3591 }
3592 }
3593 return OK;
3594}
3595
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003596status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003597 ATRACE_CALL();
3598
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003599 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003600 for (size_t i = 0; i < mNextRequests.size(); i++) {
3601 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003602 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003603 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3604 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003605
3606 // Prepare a request to HAL
3607 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3608
3609 // Insert any queued triggers (before metadata is locked)
3610 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003611 if (res < 0) {
3612 SET_ERR("RequestThread: Unable to insert triggers "
3613 "(capture request %d, HAL device: %s (%d)",
3614 halRequest->frame_number, strerror(-res), res);
3615 return INVALID_OPERATION;
3616 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003617
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003618 int triggerCount = res;
3619 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3620 mPrevTriggers = triggerCount;
3621
Emilian Peeve23f1d92021-09-20 14:56:01 -07003622 // Do not override rotate&crop for stream configurations that include
Austin Borger18b30a72022-10-27 12:20:29 -07003623 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3624 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3625 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003626 overrideAutoRotateAndCrop(captureRequest);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003627 bool autoframingChanged = overrideAutoframing(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003628 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003629
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003630 // If the request is the same as last, or we had triggers now or last time or
3631 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003632 bool newRequest =
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003633 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged ||
3634 autoframingChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003635 // Request settings are all the same within one batch, so only treat the first
3636 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003637 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003638 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003639 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 /**
3641 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003642 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003644 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003645 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003646 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003647 "(capture request %d, HAL device: %s (%d)",
3648 halRequest->frame_number, strerror(-res), res);
3649 return INVALID_OPERATION;
3650 }
3651
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003652 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003653 sp<Camera3Device> parent = mParent.promote();
3654 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003655 List<PhysicalCameraSettings>::iterator it;
3656 for (it = captureRequest->mSettingsList.begin();
3657 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003658 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3659 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003660 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3661 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3662 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3663 res);
3664 return INVALID_OPERATION;
3665 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003666 continue;
3667 }
3668
3669 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3670 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3671 updateCaptureRequest(&(it->metadata));
3672 if (res != OK) {
3673 SET_ERR("RequestThread: Unable to correct capture requests "
3674 "for scaler crop region and metering regions for request "
3675 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3676 res);
3677 return INVALID_OPERATION;
3678 }
3679 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003680 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3681 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3682 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3683 res);
3684 return INVALID_OPERATION;
3685 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003686 }
3687 }
3688
3689 // Correct metadata regions for distortion correction if enabled
3690 for (it = captureRequest->mSettingsList.begin();
3691 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003692 if (parent->mDistortionMappers.find(it->cameraId) ==
3693 parent->mDistortionMappers.end()) {
3694 continue;
3695 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003696
3697 if (!captureRequest->mDistortionCorrectionUpdated) {
3698 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3699 &(it->metadata));
3700 if (res != OK) {
3701 SET_ERR("RequestThread: Unable to correct capture requests "
3702 "for lens distortion for request %d: %s (%d)",
3703 halRequest->frame_number, strerror(-res), res);
3704 return INVALID_OPERATION;
3705 }
3706 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003707 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003708 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003709
3710 for (it = captureRequest->mSettingsList.begin();
3711 it != captureRequest->mSettingsList.end(); it++) {
3712 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3713 parent->mZoomRatioMappers.end()) {
3714 continue;
3715 }
3716
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003717 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003718 cameraIdsWithZoom.insert(it->cameraId);
3719 }
3720
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003721 if (!captureRequest->mZoomRatioUpdated) {
3722 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3723 &(it->metadata));
3724 if (res != OK) {
3725 SET_ERR("RequestThread: Unable to correct capture requests "
3726 "for zoom ratio for request %d: %s (%d)",
3727 halRequest->frame_number, strerror(-res), res);
3728 return INVALID_OPERATION;
3729 }
3730 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003731 }
3732 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003733 if (captureRequest->mRotateAndCropAuto &&
3734 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003735 for (it = captureRequest->mSettingsList.begin();
3736 it != captureRequest->mSettingsList.end(); it++) {
3737 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3738 if (mapper != parent->mRotateAndCropMappers.end()) {
3739 res = mapper->second.updateCaptureRequest(&(it->metadata));
3740 if (res != OK) {
3741 SET_ERR("RequestThread: Unable to correct capture requests "
3742 "for rotate-and-crop for request %d: %s (%d)",
3743 halRequest->frame_number, strerror(-res), res);
3744 return INVALID_OPERATION;
3745 }
3746 }
3747 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003748 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003749 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003750
3751 for (it = captureRequest->mSettingsList.begin();
3752 it != captureRequest->mSettingsList.end(); it++) {
3753 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3754 mVndkVersion, it->metadata, false /*isStatic*/);
3755 if (res != OK) {
3756 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3757 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3758 return INVALID_OPERATION;
3759 }
3760 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003761 }
3762 }
3763
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003764 /**
3765 * The request should be presorted so accesses in HAL
3766 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3767 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003768 captureRequest->mSettingsList.begin()->metadata.sort();
3769 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003770 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003771 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003772 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3773
3774 IF_ALOGV() {
3775 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3776 find_camera_metadata_ro_entry(
3777 halRequest->settings,
3778 ANDROID_CONTROL_AF_TRIGGER,
3779 &e
3780 );
3781 if (e.count > 0) {
3782 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3783 __FUNCTION__,
3784 halRequest->frame_number,
3785 e.data.u8[0]);
3786 }
3787 }
3788 } else {
3789 // leave request.settings NULL to indicate 'reuse latest given'
3790 ALOGVV("%s: Request settings are REUSED",
3791 __FUNCTION__);
3792 }
3793
Emilian Peevaebbe412018-01-15 13:53:24 +00003794 if (captureRequest->mSettingsList.size() > 1) {
3795 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3796 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003797 if (newRequest) {
3798 halRequest->physcam_settings =
3799 new const camera_metadata* [halRequest->num_physcam_settings];
3800 } else {
3801 halRequest->physcam_settings = nullptr;
3802 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003803 auto it = ++captureRequest->mSettingsList.begin();
3804 size_t i = 0;
3805 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3806 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003807 if (newRequest) {
3808 it->metadata.sort();
3809 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3810 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003811 }
3812 }
3813
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003814 uint32_t totalNumBuffers = 0;
3815
3816 // Fill in buffers
3817 if (captureRequest->mInputStream != NULL) {
3818 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003819
3820 halRequest->input_width = captureRequest->mInputBufferSize.width;
3821 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003822 totalNumBuffers += 1;
3823 } else {
3824 halRequest->input_buffer = NULL;
3825 }
3826
Emilian Peevf4816702020-04-03 15:44:51 -07003827 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003828 captureRequest->mOutputStreams.size());
3829 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003830 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003831
3832 sp<Camera3Device> parent = mParent.promote();
3833 if (parent == NULL) {
3834 // Should not happen, and nowhere to send errors to, so just log it
3835 CLOGE("RequestThread: Parent is gone");
3836 return INVALID_OPERATION;
3837 }
3838 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3839
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003840 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003841 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003842 sp<Camera3OutputStreamInterface> outputStream =
3843 captureRequest->mOutputStreams.editItemAt(j);
3844 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003845
3846 // Prepare video buffers for high speed recording on the first video request.
3847 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3848 // Only try to prepare video stream on the first video request.
3849 mPrepareVideoStream = false;
3850
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003851 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3852 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003853 while (res == NOT_ENOUGH_DATA) {
3854 res = outputStream->prepareNextBuffer();
3855 }
3856 if (res != OK) {
3857 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3858 __FUNCTION__, strerror(-res), res);
3859 outputStream->cancelPrepare();
3860 }
3861 }
3862
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003863 std::vector<size_t> uniqueSurfaceIds;
3864 res = outputStream->getUniqueSurfaceIds(
3865 captureRequest->mOutputSurfaces[streamId],
3866 &uniqueSurfaceIds);
3867 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3868 if (res != OK && res != INVALID_OPERATION) {
3869 ALOGE("%s: failed to query stream %d unique surface IDs",
3870 __FUNCTION__, streamId);
3871 return res;
3872 }
3873 if (res == OK) {
3874 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3875 }
3876
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003877 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003878 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003879 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003880 return TIMED_OUT;
3881 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003882 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003883 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003884 buffer.stream = outputStream->asHalStream();
3885 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003886 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003887 buffer.acquire_fence = -1;
3888 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003889 // Mark the output stream as unpreparable to block clients from calling
3890 // 'prepare' after this request reaches CameraHal and before the respective
3891 // buffers are requested.
3892 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003893 } else {
3894 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3895 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003896 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003897 if (res != OK) {
3898 // Can't get output buffer from gralloc queue - this could be due to
3899 // abandoned queue or other consumer misbehavior, so not a fatal
3900 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003901 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003902 " %s (%d)", strerror(-res), res);
3903
3904 return TIMED_OUT;
3905 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003906 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003907
3908 {
3909 sp<Camera3Device> parent = mParent.promote();
3910 if (parent != nullptr) {
3911 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3912 for (const auto& settings : captureRequest->mSettingsList) {
3913 if ((streamCameraId.isEmpty() &&
3914 parent->getId() == settings.cameraId.c_str()) ||
3915 streamCameraId == settings.cameraId.c_str()) {
3916 outputStream->fireBufferRequestForFrameNumber(
3917 captureRequest->mResultExtras.frameNumber,
3918 settings.metadata);
3919 }
3920 }
3921 }
3922 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003923
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003924 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003925 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3926 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3927 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3928 } else if (!physicalCameraId.isEmpty()) {
3929 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003930 }
3931 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003932 }
3933 totalNumBuffers += halRequest->num_output_buffers;
3934
3935 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003936 // If this request list is for constrained high speed recording (not
3937 // preview), and the current request is not the last one in the batch,
3938 // do not send callback to the app.
3939 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003940 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003941 hasCallback = false;
3942 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003943 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003944 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003945 const camera_metadata_t* settings = halRequest->settings;
3946 bool shouldUnlockSettings = false;
3947 if (settings == nullptr) {
3948 shouldUnlockSettings = true;
3949 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3950 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003951 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3952 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003953 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003954 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3955 isStillCapture = true;
3956 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3957 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003958
Emilian Peevaf8416e2021-02-04 17:52:43 -08003959 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003960 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003961 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3962 isZslCapture = true;
3963 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003964 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003965 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003966 res = parent->registerInFlight(halRequest->frame_number,
3967 totalNumBuffers, captureRequest->mResultExtras,
3968 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003969 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003970 expectedDurationInfo.minDuration,
3971 expectedDurationInfo.maxDuration,
3972 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003973 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003974 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
3975 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003976 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003977 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003978 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3979 ", burstId = %" PRId32 ".",
3980 __FUNCTION__,
3981 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3982 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003983
3984 if (shouldUnlockSettings) {
3985 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3986 }
3987
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003988 if (res != OK) {
3989 SET_ERR("RequestThread: Unable to register new in-flight request:"
3990 " %s (%d)", strerror(-res), res);
3991 return INVALID_OPERATION;
3992 }
3993 }
3994
3995 return OK;
3996}
3997
Igor Murashkin1e479c02013-09-06 16:55:14 -07003998CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003999 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004000 Mutex::Autolock al(mLatestRequestMutex);
4001
4002 ALOGV("RequestThread::%s", __FUNCTION__);
4003
4004 return mLatestRequest;
4005}
4006
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004007bool Camera3Device::RequestThread::isStreamPending(
4008 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004009 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004010 Mutex::Autolock l(mRequestLock);
4011
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004012 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004013 if (!nextRequest.submitted) {
4014 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4015 if (stream == s) return true;
4016 }
4017 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004018 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004019 }
4020
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004021 for (const auto& request : mRequestQueue) {
4022 for (const auto& s : request->mOutputStreams) {
4023 if (stream == s) return true;
4024 }
4025 if (stream == request->mInputStream) return true;
4026 }
4027
4028 for (const auto& request : mRepeatingRequests) {
4029 for (const auto& s : request->mOutputStreams) {
4030 if (stream == s) return true;
4031 }
4032 if (stream == request->mInputStream) return true;
4033 }
4034
4035 return false;
4036}
Jianing Weicb0652e2014-03-12 18:29:36 -07004037
Emilian Peev40ead602017-09-26 15:46:36 +01004038bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4039 ATRACE_CALL();
4040 Mutex::Autolock l(mRequestLock);
4041
4042 for (const auto& nextRequest : mNextRequests) {
4043 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4044 if (s.first == streamId) {
4045 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4046 if (it != s.second.end()) {
4047 return true;
4048 }
4049 }
4050 }
4051 }
4052
4053 for (const auto& request : mRequestQueue) {
4054 for (const auto& s : request->mOutputSurfaces) {
4055 if (s.first == streamId) {
4056 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4057 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004058 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004059 }
4060 }
4061 }
4062 }
4063
4064 for (const auto& request : mRepeatingRequests) {
4065 for (const auto& s : request->mOutputSurfaces) {
4066 if (s.first == streamId) {
4067 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4068 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004069 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004070 }
4071 }
4072 }
4073 }
4074
4075 return false;
4076}
4077
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004078void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4079 if (!mUseHalBufManager) {
4080 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4081 return;
4082 }
4083
4084 Mutex::Autolock pl(mPauseLock);
4085 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004086 mInterface->signalPipelineDrain(streamIds);
4087 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004088 }
4089 // If request thread is still busy, wait until paused then notify HAL
4090 mNotifyPipelineDrain = true;
4091 mStreamIdsToBeDrained = streamIds;
4092}
4093
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004094void Camera3Device::RequestThread::resetPipelineDrain() {
4095 Mutex::Autolock pl(mPauseLock);
4096 mNotifyPipelineDrain = false;
4097 mStreamIdsToBeDrained.clear();
4098}
4099
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004100void Camera3Device::RequestThread::clearPreviousRequest() {
4101 Mutex::Autolock l(mRequestLock);
4102 mPrevRequest.clear();
4103}
4104
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004105status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4106 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4107 ATRACE_CALL();
4108 Mutex::Autolock l(mTriggerMutex);
4109 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4110 return BAD_VALUE;
4111 }
4112 mRotateAndCropOverride = rotateAndCropValue;
4113 return OK;
4114}
4115
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004116status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4117 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4118 ATRACE_CALL();
4119 Mutex::Autolock l(mTriggerMutex);
4120 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
4121 return BAD_VALUE;
4122 }
4123 mAutoframingOverride = autoframingValue;
4124 return OK;
4125}
4126
Emilian Peeve23f1d92021-09-20 14:56:01 -07004127status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4128 ATRACE_CALL();
4129 Mutex::Autolock l(mTriggerMutex);
4130 mComposerOutput = composerSurfacePresent;
4131 return OK;
4132}
4133
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004134status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004135 ATRACE_CALL();
4136 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004137 if (muteMode != mCameraMute) {
4138 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004139 mCameraMuteChanged = true;
4140 }
4141 return OK;
4142}
4143
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004144nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004145 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004146 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004147 return mExpectedInflightDuration > kMinInflightDuration ?
4148 mExpectedInflightDuration : kMinInflightDuration;
4149}
4150
Emilian Peevaebbe412018-01-15 13:53:24 +00004151void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004152 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004153 if ((request == nullptr) || (halRequest == nullptr)) {
4154 ALOGE("%s: Invalid request!", __FUNCTION__);
4155 return;
4156 }
4157
4158 if (halRequest->num_physcam_settings > 0) {
4159 if (halRequest->physcam_id != nullptr) {
4160 delete [] halRequest->physcam_id;
4161 halRequest->physcam_id = nullptr;
4162 }
4163 if (halRequest->physcam_settings != nullptr) {
4164 auto it = ++(request->mSettingsList.begin());
4165 size_t i = 0;
4166 for (; it != request->mSettingsList.end(); it++, i++) {
4167 it->metadata.unlock(halRequest->physcam_settings[i]);
4168 }
4169 delete [] halRequest->physcam_settings;
4170 halRequest->physcam_settings = nullptr;
4171 }
4172 }
4173}
4174
Ravneetaeb20dc2022-03-30 05:33:03 +00004175status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4176 Mutex::Autolock il(mInterfaceLock);
4177 Mutex::Autolock l(mLock);
4178
4179 if (mCameraServiceWatchdog != NULL) {
4180 mCameraServiceWatchdog->setEnabled(enabled);
4181 }
4182
4183 return OK;
4184}
4185
Shuzhen Wang16610a62022-12-15 22:38:07 -08004186void Camera3Device::setStreamUseCaseOverrides(
4187 const std::vector<int64_t>& useCaseOverrides) {
4188 Mutex::Autolock il(mInterfaceLock);
4189 Mutex::Autolock l(mLock);
4190 mStreamUseCaseOverrides = useCaseOverrides;
4191}
4192
4193void Camera3Device::clearStreamUseCaseOverrides() {
4194 Mutex::Autolock il(mInterfaceLock);
4195 Mutex::Autolock l(mLock);
4196 mStreamUseCaseOverrides.clear();
4197}
4198
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004199bool Camera3Device::hasDeviceError() {
4200 Mutex::Autolock il(mInterfaceLock);
4201 Mutex::Autolock l(mLock);
4202 return mStatus == STATUS_ERROR;
4203}
4204
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004205void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4206 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004207 return;
4208 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004209
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004210 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004211 // Skip the ones that have been submitted successfully.
4212 if (nextRequest.submitted) {
4213 continue;
4214 }
4215
4216 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004217 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4218 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004219
4220 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004221 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 }
4223
Emilian Peevaebbe412018-01-15 13:53:24 +00004224 cleanupPhysicalSettings(captureRequest, halRequest);
4225
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004226 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004227 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004228 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4229 }
4230
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004231 // No output buffer can be returned when using HAL buffer manager
4232 if (!mUseHalBufManager) {
4233 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4234 //Buffers that failed processing could still have
4235 //valid acquire fence.
4236 int acquireFence = (*outputBuffers)[i].acquire_fence;
4237 if (0 <= acquireFence) {
4238 close(acquireFence);
4239 outputBuffers->editItemAt(i).acquire_fence = -1;
4240 }
Emilian Peevf4816702020-04-03 15:44:51 -07004241 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004242 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4243 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004244 /*timestampIncreasing*/true, std::vector<size_t> (),
4245 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004246 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004247 }
4248
4249 if (sendRequestError) {
4250 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004251 sp<NotificationListener> listener = mListener.promote();
4252 if (listener != NULL) {
4253 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004254 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004255 captureRequest->mResultExtras);
4256 }
4257 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004258
4259 // Remove yet-to-be submitted inflight request from inflightMap
4260 {
4261 sp<Camera3Device> parent = mParent.promote();
4262 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004263 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004264 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4265 if (idx >= 0) {
4266 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4267 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4268 parent->removeInFlightMapEntryLocked(idx);
4269 }
4270 }
4271 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004273
4274 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004275 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276}
4277
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004278void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004279 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004280 // Optimized a bit for the simple steady-state case (single repeating
4281 // request), to avoid putting that request in the queue temporarily.
4282 Mutex::Autolock l(mRequestLock);
4283
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004284 assert(mNextRequests.empty());
4285
4286 NextRequest nextRequest;
4287 nextRequest.captureRequest = waitForNextRequestLocked();
4288 if (nextRequest.captureRequest == nullptr) {
4289 return;
4290 }
4291
Emilian Peevf4816702020-04-03 15:44:51 -07004292 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004293 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004294 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004295
4296 // Wait for additional requests
4297 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4298
4299 for (size_t i = 1; i < batchSize; i++) {
4300 NextRequest additionalRequest;
4301 additionalRequest.captureRequest = waitForNextRequestLocked();
4302 if (additionalRequest.captureRequest == nullptr) {
4303 break;
4304 }
4305
Emilian Peevf4816702020-04-03 15:44:51 -07004306 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004307 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004308 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004309 }
4310
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004311 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004312 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004313 mNextRequests.size(), batchSize);
4314 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004315 }
4316
4317 return;
4318}
4319
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004320void Camera3Device::RequestThread::setRequestClearing() {
4321 Mutex::Autolock l(mRequestLock);
4322 mRequestClearing = true;
4323}
4324
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004325sp<Camera3Device::CaptureRequest>
4326 Camera3Device::RequestThread::waitForNextRequestLocked() {
4327 status_t res;
4328 sp<CaptureRequest> nextRequest;
4329
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004330 while (mRequestQueue.empty()) {
4331 if (!mRepeatingRequests.empty()) {
4332 // Always atomically enqueue all requests in a repeating request
4333 // list. Guarantees a complete in-sequence set of captures to
4334 // application.
4335 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004336 if (mFirstRepeating) {
4337 mFirstRepeating = false;
4338 } else {
4339 for (auto& request : requests) {
4340 // For repeating requests, override timestamp request using
4341 // the time a request is inserted into the request queue,
4342 // because the original repeating request will have an old
4343 // fixed timestamp.
4344 request->mRequestTimeNs = systemTime();
4345 }
4346 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 RequestList::const_iterator firstRequest =
4348 requests.begin();
4349 nextRequest = *firstRequest;
4350 mRequestQueue.insert(mRequestQueue.end(),
4351 ++firstRequest,
4352 requests.end());
4353 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004354
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004355 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 break;
4358 }
4359
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004360 if (!mRequestClearing) {
4361 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004364 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4365 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004366 Mutex::Autolock pl(mPauseLock);
4367 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004368 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004369 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004370 if (mNotifyPipelineDrain) {
4371 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4372 mNotifyPipelineDrain = false;
4373 mStreamIdsToBeDrained.clear();
4374 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004375 // Let the tracker know
4376 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4377 if (statusTracker != 0) {
4378 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4379 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004380 sp<Camera3Device> parent = mParent.promote();
4381 if (parent != nullptr) {
4382 parent->mRequestBufferSM.onRequestThreadPaused();
4383 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004384 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004385 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004386 // Stop waiting for now and let thread management happen
4387 return NULL;
4388 }
4389 }
4390
4391 if (nextRequest == NULL) {
4392 // Don't have a repeating request already in hand, so queue
4393 // must have an entry now.
4394 RequestList::iterator firstRequest =
4395 mRequestQueue.begin();
4396 nextRequest = *firstRequest;
4397 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004398 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4399 sp<NotificationListener> listener = mListener.promote();
4400 if (listener != NULL) {
4401 listener->notifyRequestQueueEmpty();
4402 }
4403 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004404 }
4405
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004406 // In case we've been unpaused by setPaused clearing mDoPause, need to
4407 // update internal pause state (capture/setRepeatingRequest unpause
4408 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004409 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004410 if (mPaused) {
4411 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4412 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4413 if (statusTracker != 0) {
4414 statusTracker->markComponentActive(mStatusId);
4415 }
4416 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004417 mPaused = false;
4418
4419 // Check if we've reconfigured since last time, and reset the preview
4420 // request if so. Can't use 'NULL request == repeat' across configure calls.
4421 if (mReconfigured) {
4422 mPrevRequest.clear();
4423 mReconfigured = false;
4424 }
4425
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004426 if (nextRequest != NULL) {
4427 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004428 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4429 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004430
4431 // Since RequestThread::clear() removes buffers from the input stream,
4432 // get the right buffer here before unlocking mRequestLock
4433 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004434 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4435 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004436 if (res != OK) {
4437 // Can't get input buffer from gralloc queue - this could be due to
4438 // disconnected queue or other producer misbehavior, so not a fatal
4439 // error
4440 ALOGE("%s: Can't get input buffer, skipping request:"
4441 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004442
4443 sp<NotificationListener> listener = mListener.promote();
4444 if (listener != NULL) {
4445 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004446 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004447 nextRequest->mResultExtras);
4448 }
4449 return NULL;
4450 }
4451 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004452 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004453
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004454 return nextRequest;
4455}
4456
4457bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004458 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004459 status_t res;
4460 Mutex::Autolock l(mPauseLock);
4461 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004462 if (mPaused == false) {
4463 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004464 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004465 if (mNotifyPipelineDrain) {
4466 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4467 mNotifyPipelineDrain = false;
4468 mStreamIdsToBeDrained.clear();
4469 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004470 // Let the tracker know
4471 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4472 if (statusTracker != 0) {
4473 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4474 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004475 sp<Camera3Device> parent = mParent.promote();
4476 if (parent != nullptr) {
4477 parent->mRequestBufferSM.onRequestThreadPaused();
4478 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004479 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004481 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004482 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004483 return true;
4484 }
4485 }
4486 // We don't set mPaused to false here, because waitForNextRequest needs
4487 // to further manage the paused state in case of starvation.
4488 return false;
4489}
4490
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004491void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004492 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004493 // With work to do, mark thread as unpaused.
4494 // If paused by request (setPaused), don't resume, to avoid
4495 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004496 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004497 Mutex::Autolock p(mPauseLock);
4498 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004499 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4500 if (mPaused) {
4501 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4502 if (statusTracker != 0) {
4503 statusTracker->markComponentActive(mStatusId);
4504 }
4505 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004506 mPaused = false;
4507 }
4508}
4509
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004510void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4511 sp<Camera3Device> parent = mParent.promote();
4512 if (parent != NULL) {
4513 va_list args;
4514 va_start(args, fmt);
4515
4516 parent->setErrorStateV(fmt, args);
4517
4518 va_end(args);
4519 }
4520}
4521
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004522status_t Camera3Device::RequestThread::insertTriggers(
4523 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004524 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004525 Mutex::Autolock al(mTriggerMutex);
4526
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004527 sp<Camera3Device> parent = mParent.promote();
4528 if (parent == NULL) {
4529 CLOGE("RequestThread: Parent is gone");
4530 return DEAD_OBJECT;
4531 }
4532
Emilian Peevaebbe412018-01-15 13:53:24 +00004533 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004534 size_t count = mTriggerMap.size();
4535
4536 for (size_t i = 0; i < count; ++i) {
4537 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004538 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004539
4540 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4541 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4542 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004543 if (isAeTrigger) {
4544 request->mResultExtras.precaptureTriggerId = triggerId;
4545 mCurrentPreCaptureTriggerId = triggerId;
4546 } else {
4547 request->mResultExtras.afTriggerId = triggerId;
4548 mCurrentAfTriggerId = triggerId;
4549 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004550 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004551 }
4552
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004553 camera_metadata_entry entry = metadata.find(tag);
4554
4555 if (entry.count > 0) {
4556 /**
4557 * Already has an entry for this trigger in the request.
4558 * Rewrite it with our requested trigger value.
4559 */
4560 RequestTrigger oldTrigger = trigger;
4561
4562 oldTrigger.entryValue = entry.data.u8[0];
4563
4564 mTriggerReplacedMap.add(tag, oldTrigger);
4565 } else {
4566 /**
4567 * More typical, no trigger entry, so we just add it
4568 */
4569 mTriggerRemovedMap.add(tag, trigger);
4570 }
4571
4572 status_t res;
4573
4574 switch (trigger.getTagType()) {
4575 case TYPE_BYTE: {
4576 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4577 res = metadata.update(tag,
4578 &entryValue,
4579 /*count*/1);
4580 break;
4581 }
4582 case TYPE_INT32:
4583 res = metadata.update(tag,
4584 &trigger.entryValue,
4585 /*count*/1);
4586 break;
4587 default:
4588 ALOGE("%s: Type not supported: 0x%x",
4589 __FUNCTION__,
4590 trigger.getTagType());
4591 return INVALID_OPERATION;
4592 }
4593
4594 if (res != OK) {
4595 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4596 ", value %d", __FUNCTION__, trigger.getTagName(),
4597 trigger.entryValue);
4598 return res;
4599 }
4600
4601 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4602 trigger.getTagName(),
4603 trigger.entryValue);
4604 }
4605
4606 mTriggerMap.clear();
4607
4608 return count;
4609}
4610
4611status_t Camera3Device::RequestThread::removeTriggers(
4612 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004613 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004614 Mutex::Autolock al(mTriggerMutex);
4615
Emilian Peevaebbe412018-01-15 13:53:24 +00004616 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004617
4618 /**
4619 * Replace all old entries with their old values.
4620 */
4621 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4622 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4623
4624 status_t res;
4625
4626 uint32_t tag = trigger.metadataTag;
4627 switch (trigger.getTagType()) {
4628 case TYPE_BYTE: {
4629 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4630 res = metadata.update(tag,
4631 &entryValue,
4632 /*count*/1);
4633 break;
4634 }
4635 case TYPE_INT32:
4636 res = metadata.update(tag,
4637 &trigger.entryValue,
4638 /*count*/1);
4639 break;
4640 default:
4641 ALOGE("%s: Type not supported: 0x%x",
4642 __FUNCTION__,
4643 trigger.getTagType());
4644 return INVALID_OPERATION;
4645 }
4646
4647 if (res != OK) {
4648 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4649 ", trigger value %d", __FUNCTION__,
4650 trigger.getTagName(), trigger.entryValue);
4651 return res;
4652 }
4653 }
4654 mTriggerReplacedMap.clear();
4655
4656 /**
4657 * Remove all new entries.
4658 */
4659 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4660 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4661 status_t res = metadata.erase(trigger.metadataTag);
4662
4663 if (res != OK) {
4664 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4665 ", trigger value %d", __FUNCTION__,
4666 trigger.getTagName(), trigger.entryValue);
4667 return res;
4668 }
4669 }
4670 mTriggerRemovedMap.clear();
4671
4672 return OK;
4673}
4674
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004675status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004676 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004677 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004678 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004679 status_t res;
4680
Emilian Peevaebbe412018-01-15 13:53:24 +00004681 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004682
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004683 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004684 // exists
4685 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4686 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4687 if (afTrigger.count > 0 &&
4688 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4689 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004690 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004691 if (res != OK) return res;
4692 }
4693
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004694 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004695 // if none already exists
4696 camera_metadata_entry pcTrigger =
4697 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4698 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4699 if (pcTrigger.count > 0 &&
4700 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4701 pcId.count == 0) {
4702 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004703 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004704 if (res != OK) return res;
4705 }
4706
4707 return OK;
4708}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004709
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004710bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4711 const sp<CaptureRequest> &request) {
4712 ATRACE_CALL();
4713
Austin Borger18b30a72022-10-27 12:20:29 -07004714 if (mOverrideToPortrait) {
4715 Mutex::Autolock l(mTriggerMutex);
4716 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4717 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4718 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4719 &rotateAndCrop_u8, 1);
4720 return true;
4721 }
4722
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004723 if (request->mRotateAndCropAuto) {
4724 Mutex::Autolock l(mTriggerMutex);
4725 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4726
4727 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4728 if (rotateAndCropEntry.count > 0) {
4729 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4730 return false;
4731 } else {
4732 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4733 return true;
4734 }
4735 } else {
4736 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4737 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4738 &rotateAndCrop_u8, 1);
4739 return true;
4740 }
4741 }
4742 return false;
4743}
4744
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004745bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4746 ATRACE_CALL();
4747
4748 if (request->mAutoframingAuto) {
4749 Mutex::Autolock l(mTriggerMutex);
4750 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4751
4752 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4753 if (autoframingEntry.count > 0) {
4754 if (autoframingEntry.data.u8[0] == mAutoframingOverride) {
4755 return false;
4756 } else {
4757 autoframingEntry.data.u8[0] = mAutoframingOverride;
4758 return true;
4759 }
4760 } else {
4761 uint8_t autoframing_u8 = mAutoframingOverride;
4762 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4763 &autoframing_u8, 1);
4764 return true;
4765 }
4766 }
4767 return false;
4768}
4769
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004770bool Camera3Device::RequestThread::overrideTestPattern(
4771 const sp<CaptureRequest> &request) {
4772 ATRACE_CALL();
4773
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004774 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004775
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004776 Mutex::Autolock l(mTriggerMutex);
4777
4778 bool changed = false;
4779
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004780 // For a multi-camera, the physical cameras support the same set of
4781 // test pattern modes as the logical camera.
4782 for (auto& settings : request->mSettingsList) {
4783 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004784
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004785 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4786 int32_t testPatternData[4] = {
4787 settings.mOriginalTestPatternData[0],
4788 settings.mOriginalTestPatternData[1],
4789 settings.mOriginalTestPatternData[2],
4790 settings.mOriginalTestPatternData[3]
4791 };
4792 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4793 testPatternMode = mCameraMute;
4794 testPatternData[0] = 0;
4795 testPatternData[1] = 0;
4796 testPatternData[2] = 0;
4797 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004798 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004799
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004800 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4801 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4802 if (testPatternEntry.count > 0) {
4803 if (testPatternEntry.data.i32[0] != testPatternMode) {
4804 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004805 changed = true;
4806 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004807 } else if (supportTestPatternModeKey) {
4808 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4809 &testPatternMode, 1);
4810 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004811 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004812
4813 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4814 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4815 if (testPatternColor.count >= 4) {
4816 for (size_t i = 0; i < 4; i++) {
4817 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4818 testPatternColor.data.i32[i] = testPatternData[i];
4819 changed = true;
4820 }
4821 }
4822 } else if (supportTestPatternDataKey) {
4823 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4824 testPatternData, 4);
4825 changed = true;
4826 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004827 }
4828
4829 return changed;
4830}
4831
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004832status_t Camera3Device::RequestThread::setHalInterface(
4833 sp<HalInterface> newHalInterface) {
4834 if (newHalInterface.get() == nullptr) {
4835 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4836 return DEAD_OBJECT;
4837 }
4838
4839 mInterface = newHalInterface;
4840
4841 return OK;
4842}
4843
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004844/**
4845 * PreparerThread inner class methods
4846 */
4847
4848Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004849 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004850 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004851}
4852
4853Camera3Device::PreparerThread::~PreparerThread() {
4854 Thread::requestExitAndWait();
4855 if (mCurrentStream != nullptr) {
4856 mCurrentStream->cancelPrepare();
4857 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4858 mCurrentStream.clear();
4859 }
4860 clear();
4861}
4862
Ruben Brunkc78ac262015-08-13 17:58:46 -07004863status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004864 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004865 status_t res;
4866
4867 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004868 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004869
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004870 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 if (res == OK) {
4872 // No preparation needed, fire listener right off
4873 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004874 if (listener != NULL) {
4875 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004876 }
4877 return OK;
4878 } else if (res != NOT_ENOUGH_DATA) {
4879 return res;
4880 }
4881
4882 // Need to prepare, start up thread if necessary
4883 if (!mActive) {
4884 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4885 // isn't running
4886 Thread::requestExitAndWait();
4887 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4888 if (res != OK) {
4889 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004890 if (listener != NULL) {
4891 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004892 }
4893 return res;
4894 }
4895 mCancelNow = false;
4896 mActive = true;
4897 ALOGV("%s: Preparer stream started", __FUNCTION__);
4898 }
4899
4900 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004901 mPendingStreams.push_back(
4902 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004903 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4904
4905 return OK;
4906}
4907
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004908void Camera3Device::PreparerThread::pause() {
4909 ATRACE_CALL();
4910
4911 Mutex::Autolock l(mLock);
4912
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004913 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
4914 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004915 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4916 int currentMaxCount = mCurrentMaxCount;
4917 mPendingStreams.clear();
4918 mCancelNow = true;
4919 while (mActive) {
4920 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4921 if (res == TIMED_OUT) {
4922 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4923 return;
4924 } else if (res != OK) {
4925 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4926 return;
4927 }
4928 }
4929
4930 //Check whether the prepare thread was able to complete the current
4931 //stream. In case work is still pending emplace it along with the rest
4932 //of the streams in the pending list.
4933 if (currentStream != nullptr) {
4934 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004935 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004936 }
4937 }
4938
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004939 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004940 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004941 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004942 }
4943}
4944
4945status_t Camera3Device::PreparerThread::resume() {
4946 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004947 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004948 status_t res;
4949
4950 Mutex::Autolock l(mLock);
4951 sp<NotificationListener> listener = mListener.promote();
4952
4953 if (mActive) {
4954 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4955 return NO_INIT;
4956 }
4957
4958 auto it = mPendingStreams.begin();
4959 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004960 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004961 if (res == OK) {
4962 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004963 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004964 }
4965 it = mPendingStreams.erase(it);
4966 } else if (res != NOT_ENOUGH_DATA) {
4967 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4968 res, strerror(-res));
4969 it = mPendingStreams.erase(it);
4970 } else {
4971 it++;
4972 }
4973 }
4974
4975 if (mPendingStreams.empty()) {
4976 return OK;
4977 }
4978
4979 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4980 if (res != OK) {
4981 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4982 __FUNCTION__, res, strerror(-res));
4983 return res;
4984 }
4985 mCancelNow = false;
4986 mActive = true;
4987 ALOGV("%s: Preparer stream started", __FUNCTION__);
4988
4989 return OK;
4990}
4991
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004992status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004993 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004994 Mutex::Autolock l(mLock);
4995
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004996 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004997 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004998 }
4999 mPendingStreams.clear();
5000 mCancelNow = true;
5001
5002 return OK;
5003}
5004
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005005void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005006 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005007 Mutex::Autolock l(mLock);
5008 mListener = listener;
5009}
5010
5011bool Camera3Device::PreparerThread::threadLoop() {
5012 status_t res;
5013 {
5014 Mutex::Autolock l(mLock);
5015 if (mCurrentStream == nullptr) {
5016 // End thread if done with work
5017 if (mPendingStreams.empty()) {
5018 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5019 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5020 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5021 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005022 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005023 return false;
5024 }
5025
5026 // Get next stream to prepare
5027 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005028 mCurrentMaxCount = std::get<0>(*it);
5029 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005030 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005031 mPendingStreams.erase(it);
5032 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5033 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5034 } else if (mCancelNow) {
5035 mCurrentStream->cancelPrepare();
5036 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5037 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5038 mCurrentStream.clear();
5039 mCancelNow = false;
5040 return true;
5041 }
5042 }
5043
5044 res = mCurrentStream->prepareNextBuffer();
5045 if (res == NOT_ENOUGH_DATA) return true;
5046 if (res != OK) {
5047 // Something bad happened; try to recover by cancelling prepare and
5048 // signalling listener anyway
5049 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5050 mCurrentStream->getId(), res, strerror(-res));
5051 mCurrentStream->cancelPrepare();
5052 }
5053
5054 // This stream has finished, notify listener
5055 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005056 sp<NotificationListener> listener = mListener.promote();
5057 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005058 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5059 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005060 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005061 }
5062
5063 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5064 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005065 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005066
5067 return true;
5068}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005069
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005070status_t Camera3Device::RequestBufferStateMachine::initialize(
5071 sp<camera3::StatusTracker> statusTracker) {
5072 if (statusTracker == nullptr) {
5073 ALOGE("%s: statusTracker is null", __FUNCTION__);
5074 return BAD_VALUE;
5075 }
5076
5077 std::lock_guard<std::mutex> lock(mLock);
5078 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005079 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005080 return OK;
5081}
5082
5083bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5084 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005085 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005086 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005087 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005088 return true;
5089 }
5090 return false;
5091}
5092
5093void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5094 std::lock_guard<std::mutex> lock(mLock);
5095 if (!mRequestBufferOngoing) {
5096 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5097 return;
5098 }
5099 mRequestBufferOngoing = false;
5100 if (mStatus == RB_STATUS_PENDING_STOP) {
5101 checkSwitchToStopLocked();
5102 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005103 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005104}
5105
5106void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5107 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005108 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005109 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005110 return;
5111}
5112
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005113void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005114 std::lock_guard<std::mutex> lock(mLock);
5115 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005116 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5117 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005118 mInflightMapEmpty = false;
5119 if (mStatus == RB_STATUS_STOPPED) {
5120 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005121 }
5122 return;
5123}
5124
5125void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5126 std::lock_guard<std::mutex> lock(mLock);
5127 mRequestThreadPaused = true;
5128 if (mStatus == RB_STATUS_PENDING_STOP) {
5129 checkSwitchToStopLocked();
5130 }
5131 return;
5132}
5133
5134void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5135 std::lock_guard<std::mutex> lock(mLock);
5136 mInflightMapEmpty = true;
5137 if (mStatus == RB_STATUS_PENDING_STOP) {
5138 checkSwitchToStopLocked();
5139 }
5140 return;
5141}
5142
5143void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5144 std::lock_guard<std::mutex> lock(mLock);
5145 if (!checkSwitchToStopLocked()) {
5146 mStatus = RB_STATUS_PENDING_STOP;
5147 }
5148 return;
5149}
5150
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005151bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5152 std::lock_guard<std::mutex> lock(mLock);
5153 if (mRequestBufferOngoing) {
5154 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5155 __FUNCTION__);
5156 return false;
5157 }
5158 mSwitchedToOffline = true;
5159 mInflightMapEmpty = true;
5160 mRequestThreadPaused = true;
5161 mStatus = RB_STATUS_STOPPED;
5162 return true;
5163}
5164
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005165void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5166 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5167 if (statusTracker != nullptr) {
5168 if (active) {
5169 statusTracker->markComponentActive(mRequestBufferStatusId);
5170 } else {
5171 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5172 }
5173 }
5174}
5175
5176bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5177 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5178 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005179 return true;
5180 }
5181 return false;
5182}
5183
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005184bool Camera3Device::startRequestBuffer() {
5185 return mRequestBufferSM.startRequestBuffer();
5186}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005187
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005188void Camera3Device::endRequestBuffer() {
5189 mRequestBufferSM.endRequestBuffer();
5190}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005191
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005192nsecs_t Camera3Device::getWaitDuration() {
5193 return kBaseGetBufferWait + getExpectedInFlightDuration();
5194}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005195
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005196void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5197 mInterface->getInflightBufferKeys(out);
5198}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005199
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005200void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5201 mInterface->getInflightRequestBufferKeys(out);
5202}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005203
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005204std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5205 std::vector<sp<Camera3StreamInterface>> ret;
5206 bool hasInputStream = mInputStream != nullptr;
5207 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5208 if (hasInputStream) {
5209 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005210 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005211 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5212 ret.push_back(mOutputStreams[i]);
5213 }
5214 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5215 ret.push_back(mDeletedStreams[i]);
5216 }
5217 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005218}
5219
Emilian Peevcc0b7952020-01-07 13:54:47 -08005220void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5221 ATRACE_CALL();
5222
5223 if (offlineStreamIds == nullptr) {
5224 return;
5225 }
5226
5227 Mutex::Autolock il(mInterfaceLock);
5228
5229 auto streamIds = mOutputStreams.getStreamIds();
5230 bool hasInputStream = mInputStream != nullptr;
5231 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5232 offlineStreamIds->push_back(mInputStream->getId());
5233 }
5234
5235 for (const auto & streamId : streamIds) {
5236 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5237 // Streams that use the camera buffer manager are currently not supported in
5238 // offline mode
5239 if (stream->getOfflineProcessingSupport() &&
5240 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5241 offlineStreamIds->push_back(streamId);
5242 }
5243 }
5244}
5245
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005246status_t Camera3Device::setRotateAndCropAutoBehavior(
5247 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5248 ATRACE_CALL();
5249 Mutex::Autolock il(mInterfaceLock);
5250 Mutex::Autolock l(mLock);
5251 if (mRequestThread == nullptr) {
5252 return INVALID_OPERATION;
5253 }
5254 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5255}
5256
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005257status_t Camera3Device::setAutoframingAutoBehavior(
5258 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5259 ATRACE_CALL();
5260 Mutex::Autolock il(mInterfaceLock);
5261 Mutex::Autolock l(mLock);
5262 if (mRequestThread == nullptr) {
5263 return INVALID_OPERATION;
5264 }
5265 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5266}
5267
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005268bool Camera3Device::supportsCameraMute() {
5269 Mutex::Autolock il(mInterfaceLock);
5270 Mutex::Autolock l(mLock);
5271
5272 return mSupportCameraMute;
5273}
5274
5275status_t Camera3Device::setCameraMute(bool enabled) {
5276 ATRACE_CALL();
5277 Mutex::Autolock il(mInterfaceLock);
5278 Mutex::Autolock l(mLock);
5279
5280 if (mRequestThread == nullptr || !mSupportCameraMute) {
5281 return INVALID_OPERATION;
5282 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005283 int32_t muteMode =
5284 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5285 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5286 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5287 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005288}
5289
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005290status_t Camera3Device::injectCamera(const String8& injectedCamId,
5291 sp<CameraProviderManager> manager) {
5292 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5293 ATRACE_CALL();
5294 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005295 // When the camera device is active, injectCamera() and stopInjection() will call
5296 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5297 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5298 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5299 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5300 // waitUntilStateThenRelock().
5301 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005302
5303 status_t res = NO_ERROR;
5304 if (mInjectionMethods->isInjecting()) {
5305 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5306 return OK;
5307 } else {
5308 res = mInjectionMethods->stopInjection();
5309 if (res != OK) {
5310 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5311 __FUNCTION__, res);
5312 return res;
5313 }
5314 }
5315 }
5316
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005317 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005318 if (res != OK) {
5319 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5320 __FUNCTION__, res);
5321 return res;
5322 }
5323
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005324 // When the second display of android is cast to the remote device, and the opened camera is
5325 // also cast to the second display, in this case, because the camera has configured the streams
5326 // at this time, we can directly call injectCamera() to replace the internal camera with
5327 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005328 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5329 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5330
5331 camera3::camera_stream_configuration injectionConfig;
5332 std::vector<uint32_t> injectionBufferSizes;
5333 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5334 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5335 || injectionBufferSizes.size() <= 0) {
5336 ALOGE("Failed to inject camera due to abandoned configuration! "
5337 "mOperatingMode: %d injectionConfig.num_streams: %d "
5338 "injectionBufferSizes.size(): %zu", mOperatingMode,
5339 injectionConfig.num_streams, injectionBufferSizes.size());
5340 return DEAD_OBJECT;
5341 }
5342
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005343 res = mInjectionMethods->injectCamera(
5344 injectionConfig, injectionBufferSizes);
5345 if (res != OK) {
5346 ALOGE("Can't finish inject camera process!");
5347 return res;
5348 }
5349 }
5350
5351 return OK;
5352}
5353
5354status_t Camera3Device::stopInjection() {
5355 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5356 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005357 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005358 return mInjectionMethods->stopInjection();
5359}
5360
Shuzhen Wang16610a62022-12-15 22:38:07 -08005361void Camera3Device::overrideStreamUseCaseLocked() {
5362 if (mStreamUseCaseOverrides.size() == 0) {
5363 return;
5364 }
5365
5366 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5367 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5368 // Refer to CameraService::printHelp for details.
5369 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5370 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5371 outputStreamsIndices[i] = i;
5372 }
5373
5374 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5375 [&](int a, int b) -> bool {
5376
5377 auto formatScore = [](int format) {
5378 switch (format) {
5379 case HAL_PIXEL_FORMAT_BLOB:
5380 return 4;
5381 case HAL_PIXEL_FORMAT_RAW16:
5382 case HAL_PIXEL_FORMAT_RAW10:
5383 case HAL_PIXEL_FORMAT_RAW12:
5384 return 3;
5385 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5386 return 2;
5387 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5388 return 1;
5389 default:
5390 return 0;
5391 }
5392 };
5393
5394 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5395 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5396 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5397 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5398 if (sizeA > sizeB ||
5399 (sizeA == sizeB && formatAScore >= formatBScore)) {
5400 return true;
5401 } else {
5402 return false;
5403 }
5404 });
5405
5406 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5408 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5409 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5410 }
5411}
5412
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005413}; // namespace android