blob: 9faea202915ddeac95b14a26d2c05420ca72662d [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070055#include "CameraService.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080056#include "aidl/AidlUtils.h"
57#include "device3/Camera3Device.h"
58#include "device3/Camera3FakeStream.h"
59#include "device3/Camera3InputStream.h"
60#include "device3/Camera3OutputStream.h"
61#include "device3/Camera3SharedOutputStream.h"
62#include "mediautils/SchedulingPolicyService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Emilian Peeva1b26262023-02-06 17:27:41 -080064#include "utils/CameraTraces.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080065#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070066#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080073
74namespace android {
75
Austin Borger74fca042022-05-23 12:41:21 -070076Camera3Device::Camera3Device(std::shared_ptr<CameraServiceProxyWrapper>& cameraServiceProxyWrapper,
Austin Borger18b30a72022-10-27 12:20:29 -070077 const String8 &id, bool overrideForPerfClass, bool overrideToPortrait, bool legacyClient):
Austin Borger74fca042022-05-23 12:41:21 -070078 mCameraServiceProxyWrapper(cameraServiceProxyWrapper),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080087 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080088 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070090 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070093 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000095 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010096 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070097 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070098 mNeedFixupMonochromeTags(false),
Austin Borger18b30a72022-10-27 12:20:29 -070099 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -0800100 mOverrideToPortrait(overrideToPortrait),
101 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102{
103 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800105}
106
107Camera3Device::~Camera3Device()
108{
109 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700111 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800112}
113
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800115 return mId;
116}
117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118status_t Camera3Device::initializeCommonLocked() {
119
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700120 /** Start up status tracker thread */
121 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700123 if (res != OK) {
124 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
125 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800126 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700127 mStatusTracker.clear();
128 return res;
129 }
130
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700132 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700133
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700134 if (mUseHalBufManager) {
135 res = mRequestBufferSM.initialize(mStatusTracker);
136 if (res != OK) {
137 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
138 strerror(-res), res);
139 mInterface->close();
140 mStatusTracker.clear();
141 return res;
142 }
143 }
144
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800145 /** Create buffer manager */
146 mBufferManager = new Camera3BufferManager();
147
148 Vector<int32_t> sessionParamKeys;
149 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
150 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
151 if (sessionKeysEntry.count > 0) {
152 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
153 }
154
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700155 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
156 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
157 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
158 if (availableTestPatternModes.data.i32[i] ==
159 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
160 mSupportCameraMute = true;
161 mSupportTestPatternSolidColor = true;
162 break;
163 } else if (availableTestPatternModes.data.i32[i] ==
164 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
165 mSupportCameraMute = true;
166 mSupportTestPatternSolidColor = false;
167 }
168 }
169
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700170 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800171 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700172 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger18b30a72022-10-27 12:20:29 -0700173 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800174 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800175 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700176 SET_ERR_L("Unable to start request queue thread: %s (%d)",
177 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800178 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800179 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800180 return res;
181 }
182
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700183 mPreparerThread = new PreparerThread();
184
Ruben Brunk183f0562015-08-12 12:55:02 -0700185 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800186 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400187 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700188 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700189 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800190 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800191
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800193 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800194 camera_metadata_entry timestampSource =
195 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
196 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
197 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800198 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800199 }
200
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700201 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100202 camera_metadata_entry partialResultsCount =
203 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
204 if (partialResultsCount.count > 0) {
205 mNumPartialResults = partialResultsCount.data.i32[0];
206 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700207 }
208
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800209 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
210 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700211 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700212 if (res != OK) {
213 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
214 return res;
215 }
216 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800218 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800220
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700221 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
222 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
223 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
224 }
225
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800226 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
227 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
228 }
229
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800230 // Hidl/AidlCamera3DeviceInjectionMethods
231 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800232
Ravneetaeb20dc2022-03-30 05:33:03 +0000233 /** Start watchdog thread */
Shuzhen Wang03fe6232023-02-05 12:41:15 -0800234 mCameraServiceWatchdog = new CameraServiceWatchdog(mId, mCameraServiceProxyWrapper);
Austin Borger7b129542022-06-09 13:23:06 -0700235 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
236 if (res != OK) {
237 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
238 strerror(-res), res);
239 return res;
240 }
Ravneetaeb20dc2022-03-30 05:33:03 +0000241
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800242 return OK;
243}
244
245status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700246 return disconnectImpl();
247}
248
249status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800250 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700251 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800252
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700253 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700254 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700255 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800256 Mutex::Autolock il(mInterfaceLock);
257 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
258 {
259 Mutex::Autolock l(mLock);
260 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000262 if (mRequestThread != NULL) {
263 if (mStatus == STATUS_ACTIVE || mStatus == STATUS_ERROR) {
264 res = mRequestThread->clear();
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800265 if (res != OK) {
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000266 SET_ERR_L("Can't stop streaming");
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 // Continue to close device even in case of error
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000268 } else {
269 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
270 if (res != OK) {
271 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
272 maxExpectedDuration);
273 // Continue to close device even in case of error
274 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276 }
Jayant Chowdharya93f3462022-11-01 23:32:45 +0000277 // Signal to request thread that we're not expecting any
278 // more requests. This will be true since once we're in
279 // disconnect and we've cleared off the request queue, the
280 // request thread can't receive any new requests through
281 // binder calls - since disconnect holds
282 // mBinderSerialization lock.
283 mRequestThread->setRequestClearing();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700284 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800285
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800286 if (mStatus == STATUS_ERROR) {
287 CLOGE("Shutting down in an error state");
288 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700289
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800290 if (mStatusTracker != NULL) {
291 mStatusTracker->requestExit();
292 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700293
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 if (mRequestThread != NULL) {
295 mRequestThread->requestExit();
296 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800298 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
299 for (size_t i = 0; i < mOutputStreams.size(); i++) {
300 streams.push_back(mOutputStreams[i]);
301 }
302 if (mInputStream != nullptr) {
303 streams.push_back(mInputStream);
304 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700305 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800307 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
308 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
310 // HAL may be in a bad state, so waiting for request thread
311 // (which may be stuck in the HAL processCaptureRequest call)
312 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800313 // give up mInterfaceLock here and then lock it again. Could this lead
314 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mRequestThread->join();
316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800318 Mutex::Autolock il(mInterfaceLock);
319 if (mStatusTracker != NULL) {
320 mStatusTracker->join();
321 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800323 if (mInjectionMethods->isInjecting()) {
324 mInjectionMethods->stopInjection();
325 }
326
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800327 HalInterface* interface;
328 {
329 Mutex::Autolock l(mLock);
330 mRequestThread.clear();
331 Mutex::Autolock stLock(mTrackerLock);
332 mStatusTracker.clear();
333 interface = mInterface.get();
334 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700335
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800336 // Call close without internal mutex held, as the HAL close may need to
337 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000338 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800340 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800341
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800342 {
343 Mutex::Autolock l(mLock);
344 mInterface->clear();
345 mOutputStreams.clear();
346 mInputStream.clear();
347 mDeletedStreams.clear();
348 mBufferManager.clear();
349 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
350 }
351
352 for (auto& weakStream : streams) {
353 sp<Camera3StreamInterface> stream = weakStream.promote();
354 if (stream != nullptr) {
355 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
356 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
357 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700358 }
359 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700360 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000361
362 if (mCameraServiceWatchdog != NULL) {
363 mCameraServiceWatchdog->requestExit();
364 mCameraServiceWatchdog.clear();
365 }
366
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700367 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800368}
369
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370// For dumping/debugging only -
371// try to acquire a lock a few times, eventually give up to proceed with
372// debug/dump operations
373bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
374 bool gotLock = false;
375 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
376 if (lock.tryLock() == NO_ERROR) {
377 gotLock = true;
378 break;
379 } else {
380 usleep(kDumpSleepDuration);
381 }
382 }
383 return gotLock;
384}
385
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800386nsecs_t Camera3Device::getMonoToBoottimeOffset() {
387 // try three times to get the clock offset, choose the one
388 // with the minimum gap in measurements.
389 const int tries = 3;
390 nsecs_t bestGap, measured;
391 for (int i = 0; i < tries; ++i) {
392 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
393 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
394 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
395 const nsecs_t gap = tmono2 - tmono;
396 if (i == 0 || gap < bestGap) {
397 bestGap = gap;
398 measured = tbase - ((tmono + tmono2) >> 1);
399 }
400 }
401 return measured;
402}
403
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
405 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700406 // Get max jpeg size (area-wise) for default sensor pixel mode
407 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800408 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700409 /*isUltraHighResolutionSensor*/false);
410 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
411 // not ultra high res sensor
412 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800413 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700414 /*isUltraHighResolution*/true);
415 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
417 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700418 return BAD_VALUE;
419 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700420 bool useMaxSensorPixelModeThreshold = false;
421 if (uhrMaxJpegResolution.width != 0 &&
422 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
423 // Use the ultra high res max jpeg size and max jpeg buffer size
424 useMaxSensorPixelModeThreshold = true;
425 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700426
Zhijun Hef7da0962014-04-24 13:27:56 -0700427 // Get max jpeg buffer size
428 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800429 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700430 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800431 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
432 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700433 return BAD_VALUE;
434 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700435 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700436
437 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
438 if (useMaxSensorPixelModeThreshold) {
439 maxJpegBufferSize =
440 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
441 maxDefaultJpegResolution, maxJpegBufferSize);
442 chosenMaxJpegResolution = uhrMaxJpegResolution;
443 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800444 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700445
446 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700447 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700448 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800449 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
450 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700451 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800452 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
453 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700454 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700455 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700456 return jpegBufferSize;
457}
458
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800459ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700460 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800461 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700462 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800463 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
464 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700465 return BAD_VALUE;
466 }
467 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
468 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
469 return maxBytesForPointCloud;
470}
471
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800472ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
473 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 const int PER_CONFIGURATION_SIZE = 3;
475 const int WIDTH_OFFSET = 0;
476 const int HEIGHT_OFFSET = 1;
477 const int SIZE_OFFSET = 2;
478 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800479 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800480 camera3::SessionConfigurationUtils::getAppropriateModeTag(
481 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
482 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800483 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800484 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800485 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
486 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800487 return BAD_VALUE;
488 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700489
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800490 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
491 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
492 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
493 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
494 }
495 }
496
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800497 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
498 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800499 return BAD_VALUE;
500}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700501
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800502status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
503 ATRACE_CALL();
504 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700505
506 // Try to lock, but continue in case of failure (to avoid blocking in
507 // deadlocks)
508 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
509 bool gotLock = tryLockSpinRightRound(mLock);
510
511 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800512 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
513 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700514 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800515 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
516 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700517
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800518 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700519
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800520 String16 templatesOption("-t");
521 int n = args.size();
522 for (int i = 0; i < n; i++) {
523 if (args[i] == templatesOption) {
524 dumpTemplates = true;
525 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000526 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700527 if (i + 1 < n) {
528 String8 monitorTags = String8(args[i + 1]);
529 if (monitorTags == "off") {
530 mTagMonitor.disableMonitoring();
531 } else {
532 mTagMonitor.parseTagsToMonitor(monitorTags);
533 }
534 } else {
535 mTagMonitor.disableMonitoring();
536 }
537 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800538 }
539
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800540 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800541
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800542 const char *status =
543 mStatus == STATUS_ERROR ? "ERROR" :
544 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700545 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
546 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800547 mStatus == STATUS_ACTIVE ? "ACTIVE" :
548 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700549
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800550 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700551 if (mStatus == STATUS_ERROR) {
552 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
553 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800554 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800555 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000556 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
557 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
558 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800559 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800560
561 if (mInputStream != NULL) {
562 write(fd, lines.string(), lines.size());
563 mInputStream->dump(fd, args);
564 } else {
565 lines.appendFormat(" No input stream.\n");
566 write(fd, lines.string(), lines.size());
567 }
568 for (size_t i = 0; i < mOutputStreams.size(); i++) {
569 mOutputStreams[i]->dump(fd,args);
570 }
571
Zhijun He431503c2016-03-07 17:30:16 -0800572 if (mBufferManager != NULL) {
573 lines = String8(" Camera3 Buffer Manager:\n");
574 write(fd, lines.string(), lines.size());
575 mBufferManager->dump(fd, args);
576 }
Zhijun He125684a2015-12-26 15:07:30 -0800577
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700578 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700579 if (mInFlightLock.try_lock()) {
580 if (mInFlightMap.size() == 0) {
581 lines.append(" None\n");
582 } else {
583 for (size_t i = 0; i < mInFlightMap.size(); i++) {
584 InFlightRequest r = mInFlightMap.valueAt(i);
585 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
586 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
587 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
588 r.numBuffersLeft);
589 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700590 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700591 mInFlightLock.unlock();
592 } else {
593 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700594 }
595 write(fd, lines.string(), lines.size());
596
Shuzhen Wang686f6442017-06-20 16:16:04 -0700597 if (mRequestThread != NULL) {
598 mRequestThread->dumpCaptureRequestLatency(fd,
599 " ProcessCaptureRequest latency histogram:");
600 }
601
Igor Murashkin1e479c02013-09-06 16:55:14 -0700602 {
603 lines = String8(" Last request sent:\n");
604 write(fd, lines.string(), lines.size());
605
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700607 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
608 }
609
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700611 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 "TEMPLATE_PREVIEW",
613 "TEMPLATE_STILL_CAPTURE",
614 "TEMPLATE_VIDEO_RECORD",
615 "TEMPLATE_VIDEO_SNAPSHOT",
616 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800617 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800618 };
619
Emilian Peevf4816702020-04-03 15:44:51 -0700620 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800621 camera_metadata_t *templateRequest = nullptr;
622 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700623 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800626 lines.append(" Not supported\n");
627 write(fd, lines.string(), lines.size());
628 } else {
629 write(fd, lines.string(), lines.size());
630 dump_indented_camera_metadata(templateRequest,
631 fd, /*verbosity*/2, /*indentation*/8);
632 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800634 }
635 }
636
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700637 mTagMonitor.dumpMonitoredMetadata(fd);
638
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800639 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800640 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800642 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800644
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700645 if (gotLock) mLock.unlock();
646 if (gotInterfaceLock) mInterfaceLock.unlock();
647
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800648 return OK;
649}
650
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700651status_t Camera3Device::startWatchingTags(const String8 &tags) {
652 mTagMonitor.parseTagsToMonitor(tags);
653 return OK;
654}
655
656status_t Camera3Device::stopWatchingTags() {
657 mTagMonitor.disableMonitoring();
658 return OK;
659}
660
661status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
662 mTagMonitor.getLatestMonitoredTagEvents(out);
663 return OK;
664}
665
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800666const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800667 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800668 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
669 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700670 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800671 mStatus == STATUS_ERROR ?
672 "when in error state" : "before init");
673 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700674 if (physicalId.isEmpty()) {
675 return mDeviceInfo;
676 } else {
677 std::string id(physicalId.c_str());
678 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
679 return mPhysicalDeviceInfoMap.at(id);
680 } else {
681 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
682 return mDeviceInfo;
683 }
684 }
685}
686
687const CameraMetadata& Camera3Device::info() const {
688 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800689 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800690}
691
Jianing Wei90e59c92014-03-12 18:29:36 -0700692status_t Camera3Device::checkStatusOkToCaptureLocked() {
693 switch (mStatus) {
694 case STATUS_ERROR:
695 CLOGE("Device has encountered a serious error");
696 return INVALID_OPERATION;
697 case STATUS_UNINITIALIZED:
698 CLOGE("Device not initialized");
699 return INVALID_OPERATION;
700 case STATUS_UNCONFIGURED:
701 case STATUS_CONFIGURED:
702 case STATUS_ACTIVE:
703 // OK
704 break;
705 default:
706 SET_ERR_L("Unexpected status: %d", mStatus);
707 return INVALID_OPERATION;
708 }
709 return OK;
710}
711
712status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000713 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700714 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700715 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700716 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700717 if (requestList == NULL) {
718 CLOGE("requestList cannot be NULL.");
719 return BAD_VALUE;
720 }
721
Jianing Weicb0652e2014-03-12 18:29:36 -0700722 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000723 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700724 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
725 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
726 ++metadataIt, ++surfaceMapIt) {
727 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700728 if (newRequest == 0) {
729 CLOGE("Can't create capture request");
730 return BAD_VALUE;
731 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700732
Shuzhen Wang9d066012016-09-30 11:30:20 -0700733 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700734 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700735
Jianing Weicb0652e2014-03-12 18:29:36 -0700736 // Setup burst Id and request Id
737 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800738 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
739 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700740 CLOGE("RequestID does not exist in metadata");
741 return BAD_VALUE;
742 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800743 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700744
Jianing Wei90e59c92014-03-12 18:29:36 -0700745 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700746
747 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700748 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
750 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
751 return BAD_VALUE;
752 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700753
754 // Setup batch size if this is a high speed video recording request.
755 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
756 auto firstRequest = requestList->begin();
757 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
758 if (outputStream->isVideoStream()) {
759 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800760 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700761 break;
762 }
763 }
764 }
765
Jianing Wei90e59c92014-03-12 18:29:36 -0700766 return OK;
767}
768
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800769status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800771
Emilian Peevaebbe412018-01-15 13:53:24 +0000772 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700773 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000774 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700775
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800776 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700777}
778
Emilian Peevaebbe412018-01-15 13:53:24 +0000779void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700780 std::list<const SurfaceMap>& surfaceMaps,
781 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000782 PhysicalCameraSettingsList requestList;
783 requestList.push_back({std::string(getId().string()), request});
784 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785
786 SurfaceMap surfaceMap;
787 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
788 // With no surface list passed in, stream and surface will have 1-to-1
789 // mapping. So the surface index is 0 for each stream in the surfaceMap.
790 for (size_t i = 0; i < streams.count; i++) {
791 surfaceMap[streams.data.i32[i]].push_back(0);
792 }
793 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800794}
795
Jianing Wei90e59c92014-03-12 18:29:36 -0700796status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000797 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700798 const std::list<const SurfaceMap> &surfaceMaps,
799 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 /*out*/
801 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700802 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700803 nsecs_t requestTimeNs = systemTime();
804
Jianing Wei90e59c92014-03-12 18:29:36 -0700805 Mutex::Autolock il(mInterfaceLock);
806 Mutex::Autolock l(mLock);
807
808 status_t res = checkStatusOkToCaptureLocked();
809 if (res != OK) {
810 // error logged by previous call
811 return res;
812 }
813
814 RequestList requestList;
815
Shuzhen Wang0129d522016-10-30 22:43:41 -0700816 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700817 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700818 if (res != OK) {
819 // error logged by previous call
820 return res;
821 }
822
823 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700824 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700825 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700826 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 }
828
829 if (res == OK) {
830 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
831 if (res != OK) {
832 SET_ERR_L("Can't transition to active in %f seconds!",
833 kActiveTimeout/1e9);
834 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800835 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700836 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837 } else {
838 CLOGE("Cannot queue request. Impossible.");
839 return BAD_VALUE;
840 }
841
842 return res;
843}
844
Emilian Peevaebbe412018-01-15 13:53:24 +0000845status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700847 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 ATRACE_CALL();
849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700851}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
854 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000859 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863}
864
Emilian Peevaebbe412018-01-15 13:53:24 +0000865status_t Camera3Device::setStreamingRequestList(
866 const List<const PhysicalCameraSettingsList> &requestsList,
867 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 ATRACE_CALL();
869
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700871}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872
873sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800875 status_t res;
876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700877 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800878 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
879 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000880 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700881 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700882 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800883 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700884 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700886 } else if (mStatus == STATUS_UNCONFIGURED) {
887 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700888 CLOGE("No streams configured");
889 return NULL;
890 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 }
892
Shuzhen Wang0129d522016-10-30 22:43:41 -0700893 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800895}
896
Jianing Weicb0652e2014-03-12 18:29:36 -0700897status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800900 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800901
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 switch (mStatus) {
903 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700904 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800905 return INVALID_OPERATION;
906 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700907 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800908 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 case STATUS_UNCONFIGURED:
910 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800911 case STATUS_ACTIVE:
912 // OK
913 break;
914 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700915 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800916 return INVALID_OPERATION;
917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700919
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700920 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800921}
922
923status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
924 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700927 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800928}
929
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700930status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800931 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700934 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700935 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800936 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
937 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700938
939 status_t res;
940 bool wasActive = false;
941
942 switch (mStatus) {
943 case STATUS_ERROR:
944 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
945 return INVALID_OPERATION;
946 case STATUS_UNINITIALIZED:
947 ALOGE("%s: Device not initialized", __FUNCTION__);
948 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 case STATUS_UNCONFIGURED:
950 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700951 // OK
952 break;
953 case STATUS_ACTIVE:
954 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700955 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700956 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700957 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700958 return res;
959 }
960 wasActive = true;
961 break;
962 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700963 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700964 return INVALID_OPERATION;
965 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700966 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700967
968 if (mInputStream != 0) {
969 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
970 return INVALID_OPERATION;
971 }
972
973 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
974 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700975 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700976
977 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800978 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979
980 *id = mNextStreamId++;
981
982 // Continue captures if active at start
983 if (wasActive) {
984 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100985 // Reuse current operating mode and session parameters for new stream config
986 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700987 if (res != OK) {
988 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
989 __FUNCTION__, mNextStreamId, strerror(-res), res);
990 return res;
991 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700992 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700993 }
994
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800995 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700996 return OK;
997}
998
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700999status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001000 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001001 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001002 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001003 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1004 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001005 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001006 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001007 ATRACE_CALL();
1008
1009 if (consumer == nullptr) {
1010 ALOGE("%s: consumer must not be null", __FUNCTION__);
1011 return BAD_VALUE;
1012 }
1013
1014 std::vector<sp<Surface>> consumers;
1015 consumers.push_back(consumer);
1016
1017 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001018 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001019 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001020 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001021}
1022
1023static bool isRawFormat(int format) {
1024 switch (format) {
1025 case HAL_PIXEL_FORMAT_RAW16:
1026 case HAL_PIXEL_FORMAT_RAW12:
1027 case HAL_PIXEL_FORMAT_RAW10:
1028 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1029 return true;
1030 default:
1031 return false;
1032 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001033}
1034
1035status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1036 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001037 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001038 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001039 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001040 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001041 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001042 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001043
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001044 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001045 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001046 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001047 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001048 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001049 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001050 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001051 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001052 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001053 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1054 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001055
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001056 status_t res;
1057 bool wasActive = false;
1058
1059 switch (mStatus) {
1060 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001061 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 return INVALID_OPERATION;
1063 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001064 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001065 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001066 case STATUS_UNCONFIGURED:
1067 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001068 // OK
1069 break;
1070 case STATUS_ACTIVE:
1071 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001072 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001074 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001075 return res;
1076 }
1077 wasActive = true;
1078 break;
1079 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001080 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001081 return INVALID_OPERATION;
1082 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001083 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001084
1085 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001086
Shuzhen Wang0129d522016-10-30 22:43:41 -07001087 if (consumers.size() == 0 && !hasDeferredConsumer) {
1088 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1089 return BAD_VALUE;
1090 }
Zhijun He5d677d12016-05-29 16:52:39 -07001091
Shuzhen Wang0129d522016-10-30 22:43:41 -07001092 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001093 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1094 return BAD_VALUE;
1095 }
1096
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001097 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1098 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1099 // be found in only one sensor pixel mode.
1100 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1101 return BAD_VALUE;
1102 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001103 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001104 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001105 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001106 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001107 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001108 if (blobBufferSize <= 0) {
1109 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1110 return BAD_VALUE;
1111 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001112 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1113 blobBufferSize = width * height;
1114 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001115 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001116 if (blobBufferSize <= 0) {
1117 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1118 return BAD_VALUE;
1119 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001120 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001121 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001122 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001123 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001124 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001125 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001126 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001127 bool maxResolution =
1128 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1129 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001130 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1131 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001132 if (rawOpaqueBufferSize <= 0) {
1133 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1134 return BAD_VALUE;
1135 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001136 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001137 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001138 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001139 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001140 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001141 } else if (isShared) {
1142 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1143 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001144 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001145 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001146 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001147 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001148 newStream = new Camera3OutputStream(mNextStreamId,
1149 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001150 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001151 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001152 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001154 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001155 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001156 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001157 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001158 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001159 }
Emilian Peev40ead602017-09-26 15:46:36 +01001160
1161 size_t consumerCount = consumers.size();
1162 for (size_t i = 0; i < consumerCount; i++) {
1163 int id = newStream->getSurfaceId(consumers[i]);
1164 if (id < 0) {
1165 SET_ERR_L("Invalid surface id");
1166 return BAD_VALUE;
1167 }
1168 if (surfaceIds != nullptr) {
1169 surfaceIds->push_back(id);
1170 }
1171 }
1172
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174
Emilian Peev08dd2452017-04-06 16:55:14 +01001175 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001176
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001177 newStream->setImageDumpMask(mImageDumpMask);
1178
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179 res = mOutputStreams.add(mNextStreamId, newStream);
1180 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001181 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182 return res;
1183 }
1184
Shuzhen Wang316781a2020-08-18 18:11:01 -07001185 mSessionStatsBuilder.addStream(mNextStreamId);
1186
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001188 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189
1190 // Continue captures if active at start
1191 if (wasActive) {
1192 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001193 // Reuse current operating mode and session parameters for new stream config
1194 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001196 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1197 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 return res;
1199 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001202 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001204}
1205
Emilian Peev710c1422017-08-30 11:19:38 +01001206status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001207 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001208 if (nullptr == streamInfo) {
1209 return BAD_VALUE;
1210 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 switch (mStatus) {
1215 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001219 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001221 case STATUS_UNCONFIGURED:
1222 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 case STATUS_ACTIVE:
1224 // OK
1225 break;
1226 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001227 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 return INVALID_OPERATION;
1229 }
1230
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001231 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1232 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001234 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 }
1236
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001237 streamInfo->width = stream->getWidth();
1238 streamInfo->height = stream->getHeight();
1239 streamInfo->format = stream->getFormat();
1240 streamInfo->dataSpace = stream->getDataSpace();
1241 streamInfo->formatOverridden = stream->isFormatOverridden();
1242 streamInfo->originalFormat = stream->getOriginalFormat();
1243 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1244 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001245 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001246 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248}
1249
1250status_t Camera3Device::setStreamTransform(int id,
1251 int transform) {
1252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 switch (mStatus) {
1257 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 case STATUS_ACTIVE:
1266 // OK
1267 break;
1268 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
1271 }
1272
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001273 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1274 if (stream == nullptr) {
1275 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 return BAD_VALUE;
1277 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001278 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001279}
1280
1281status_t Camera3Device::deleteStream(int id) {
1282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 Mutex::Autolock l(mLock);
1285 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001286
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001287 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001288
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001289 // CameraDevice semantics require device to already be idle before
1290 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001292 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001293 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001294 }
1295
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001296 if (mStatus == STATUS_ERROR) {
1297 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1298 __FUNCTION__, mId.string());
1299 return -EBUSY;
1300 }
1301
Igor Murashkin2fba5842013-04-22 14:03:54 -07001302 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001303 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001304 if (mInputStream != NULL && id == mInputStream->getId()) {
1305 deletedStream = mInputStream;
1306 mInputStream.clear();
1307 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001308 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001309 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001310 return BAD_VALUE;
1311 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001312 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001313 }
1314
1315 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001316 if (stream != nullptr) {
1317 deletedStream = stream;
1318 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001319 }
1320
1321 // Free up the stream endpoint so that it can be used by some other stream
1322 res = deletedStream->disconnect();
1323 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001324 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001325 // fall through since we want to still list the stream as deleted.
1326 }
1327 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001328 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001329
1330 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001331}
1332
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001333status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001334 ATRACE_CALL();
1335 ALOGV("%s: E", __FUNCTION__);
1336
1337 Mutex::Autolock il(mInterfaceLock);
1338 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001339
Emilian Peev811d2952018-05-25 11:08:40 +01001340 // In case the client doesn't include any session parameter, try a
1341 // speculative configuration using the values from the last cached
1342 // default request.
1343 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001344 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001345 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1346 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1347 mLastTemplateId);
1348 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1349 operatingMode);
1350 }
1351
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001352 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1353}
1354
1355status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1356 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001357 //Filter out any incoming session parameters
1358 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001359 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1360 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001361 CameraMetadata filteredParams(availableSessionKeys.count);
1362 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1363 filteredParams.getAndLock());
1364 set_camera_metadata_vendor_id(meta, mVendorTagId);
1365 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001366 if (availableSessionKeys.count > 0) {
1367 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1368 camera_metadata_ro_entry entry = params.find(
1369 availableSessionKeys.data.i32[i]);
1370 if (entry.count > 0) {
1371 filteredParams.update(entry);
1372 }
1373 }
1374 }
1375
1376 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001377}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001378
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001379status_t Camera3Device::getInputBufferProducer(
1380 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001381 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001382 Mutex::Autolock il(mInterfaceLock);
1383 Mutex::Autolock l(mLock);
1384
1385 if (producer == NULL) {
1386 return BAD_VALUE;
1387 } else if (mInputStream == NULL) {
1388 return INVALID_OPERATION;
1389 }
1390
1391 return mInputStream->getInputBufferProducer(producer);
1392}
1393
Emilian Peevf4816702020-04-03 15:44:51 -07001394status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001395 CameraMetadata *request) {
1396 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001397 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001398
Emilian Peevf4816702020-04-03 15:44:51 -07001399 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001400 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001401 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001402 return BAD_VALUE;
1403 }
1404
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001405 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001407 {
1408 Mutex::Autolock l(mLock);
1409 switch (mStatus) {
1410 case STATUS_ERROR:
1411 CLOGE("Device has encountered a serious error");
1412 return INVALID_OPERATION;
1413 case STATUS_UNINITIALIZED:
1414 CLOGE("Device is not initialized!");
1415 return INVALID_OPERATION;
1416 case STATUS_UNCONFIGURED:
1417 case STATUS_CONFIGURED:
1418 case STATUS_ACTIVE:
1419 // OK
1420 break;
1421 default:
1422 SET_ERR_L("Unexpected status: %d", mStatus);
1423 return INVALID_OPERATION;
1424 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001425
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001426 if (!mRequestTemplateCache[templateId].isEmpty()) {
1427 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001428 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001429 return OK;
1430 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001431 }
1432
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001433 camera_metadata_t *rawRequest;
1434 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001435 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001436
1437 {
1438 Mutex::Autolock l(mLock);
1439 if (res == BAD_VALUE) {
1440 ALOGI("%s: template %d is not supported on this camera device",
1441 __FUNCTION__, templateId);
1442 return res;
1443 } else if (res != OK) {
1444 CLOGE("Unable to construct request template %d: %s (%d)",
1445 templateId, strerror(-res), res);
1446 return res;
1447 }
1448
1449 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1450 mRequestTemplateCache[templateId].acquire(rawRequest);
1451
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001452 // Override the template request with zoomRatioMapper
1453 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1454 &mRequestTemplateCache[templateId]);
1455 if (res != OK) {
1456 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1457 templateId, strerror(-res), res);
1458 return res;
1459 }
1460
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001461 // Fill in JPEG_QUALITY if not available
1462 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1463 static const uint8_t kDefaultJpegQuality = 95;
1464 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1465 &kDefaultJpegQuality, 1);
1466 }
1467
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001468 // Fill in AUTOFRAMING if not available
1469 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1470 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1471 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1472 &kDefaultAutoframingMode, 1);
1473 }
1474
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001475 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001476 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001477 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478 return OK;
1479}
1480
1481status_t Camera3Device::waitUntilDrained() {
1482 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001483 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001484 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001487 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001488}
1489
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001490status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 switch (mStatus) {
1492 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 ALOGV("%s: Already idle", __FUNCTION__);
1495 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 case STATUS_CONFIGURED:
1497 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 case STATUS_ERROR:
1499 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 break;
1502 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001503 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 return INVALID_OPERATION;
1505 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001506 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1507 maxExpectedDuration);
1508 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001509 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001510 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001511 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1512 res);
1513 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001514 return res;
1515}
1516
Ruben Brunk183f0562015-08-12 12:55:02 -07001517void Camera3Device::internalUpdateStatusLocked(Status status) {
1518 mStatus = status;
1519 mRecentStatusUpdates.add(mStatus);
1520 mStatusChanged.broadcast();
1521}
1522
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001524status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001525 if (mRequestThread.get() != nullptr) {
1526 mRequestThread->setPaused(true);
1527 } else {
1528 return NO_INIT;
1529 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001530
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001531 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1532 maxExpectedDuration);
1533 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001534 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001535 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001537 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 }
1539
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 return res;
1541}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543// Resume after internalPauseAndWaitLocked
1544status_t Camera3Device::internalResumeLocked() {
1545 status_t res;
1546
1547 mRequestThread->setPaused(false);
1548
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001549 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1550 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1552 if (res != OK) {
1553 SET_ERR_L("Can't transition to active in %f seconds!",
1554 kActiveTimeout/1e9);
1555 }
1556 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001558}
1559
Ruben Brunk183f0562015-08-12 12:55:02 -07001560status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001562
1563 size_t startIndex = 0;
1564 if (mStatusWaiters == 0) {
1565 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1566 // this status list
1567 mRecentStatusUpdates.clear();
1568 } else {
1569 // If other threads are waiting on updates to this status list, set the position of the
1570 // first element that this list will check rather than clearing the list.
1571 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 }
1573
Ruben Brunk183f0562015-08-12 12:55:02 -07001574 mStatusWaiters++;
1575
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001576 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001577 if (!active && mUseHalBufManager) {
1578 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001579 if (mStatus == STATUS_ACTIVE) {
1580 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001581 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001582 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001583 mRequestBufferSM.onWaitUntilIdle();
1584 }
1585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001587 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001588 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001589 if (active == (mStatus == STATUS_ACTIVE)) {
1590 // Desired state is current
1591 break;
1592 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001593
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001594 nsecs_t timeElapsed = systemTime() - startTime;
1595 nsecs_t timeToWait = timeout - timeElapsed;
1596 if (timeToWait <= 0) {
1597 // Thread woke up spuriously but has timed out since.
1598 // Force out of loop with TIMED_OUT result.
1599 res = TIMED_OUT;
1600 break;
1601 }
1602 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 if (res != OK) break;
1604
Ruben Brunk183f0562015-08-12 12:55:02 -07001605 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1606 // transitions.
1607 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1608 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1609 __FUNCTION__);
1610
1611 // Encountered desired state since we began waiting
1612 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1614 stateSeen = true;
1615 break;
1616 }
1617 }
1618 } while (!stateSeen);
1619
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001620 if (signalPipelineDrain) {
1621 mRequestThread->resetPipelineDrain();
1622 }
1623
Ruben Brunk183f0562015-08-12 12:55:02 -07001624 mStatusWaiters--;
1625
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001626 return res;
1627}
1628
1629
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001630status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001632 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001633
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001634 if (listener != NULL && mListener != NULL) {
1635 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1636 }
1637 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001638 mRequestThread->setNotificationListener(listener);
1639 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001640
1641 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642}
1643
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001644bool Camera3Device::willNotify3A() {
1645 return false;
1646}
1647
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001649 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001650 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001651
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001652 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001653 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1654 if (st == std::cv_status::timeout) {
1655 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001656 }
1657 }
1658 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659}
1660
Jianing Weicb0652e2014-03-12 18:29:36 -07001661status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001663 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001665 if (mResultQueue.empty()) {
1666 return NOT_ENOUGH_DATA;
1667 }
1668
Jianing Weicb0652e2014-03-12 18:29:36 -07001669 if (frame == NULL) {
1670 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1671 return BAD_VALUE;
1672 }
1673
1674 CaptureResult &result = *(mResultQueue.begin());
1675 frame->mResultExtras = result.mResultExtras;
1676 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001677 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001678 mResultQueue.erase(mResultQueue.begin());
1679
1680 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001681}
1682
1683status_t Camera3Device::triggerAutofocus(uint32_t id) {
1684 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001685 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1688 // Mix-in this trigger into the next request and only the next request.
1689 RequestTrigger trigger[] = {
1690 {
1691 ANDROID_CONTROL_AF_TRIGGER,
1692 ANDROID_CONTROL_AF_TRIGGER_START
1693 },
1694 {
1695 ANDROID_CONTROL_AF_TRIGGER_ID,
1696 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001697 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001698 };
1699
1700 return mRequestThread->queueTrigger(trigger,
1701 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001702}
1703
1704status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1705 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001708 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1709 // Mix-in this trigger into the next request and only the next request.
1710 RequestTrigger trigger[] = {
1711 {
1712 ANDROID_CONTROL_AF_TRIGGER,
1713 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1714 },
1715 {
1716 ANDROID_CONTROL_AF_TRIGGER_ID,
1717 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001718 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001719 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001721 return mRequestThread->queueTrigger(trigger,
1722 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723}
1724
1725status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1726 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001729 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1730 // Mix-in this trigger into the next request and only the next request.
1731 RequestTrigger trigger[] = {
1732 {
1733 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1734 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1735 },
1736 {
1737 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1738 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001739 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001740 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001742 return mRequestThread->queueTrigger(trigger,
1743 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744}
1745
Jianing Weicb0652e2014-03-12 18:29:36 -07001746status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001747 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001748 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001749 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001750
Zhijun He7ef20392014-04-21 16:04:17 -07001751 {
1752 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001753
1754 // b/116514106 "disconnect()" can get called twice for the same device. The
1755 // camera device will not be initialized during the second run.
1756 if (mStatus == STATUS_UNINITIALIZED) {
1757 return OK;
1758 }
1759
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001760 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001761
1762 // Stop session and stream counter
1763 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001764 }
1765
Ravneetdbd5b242022-03-02 07:22:46 +00001766 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001767 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001768 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1769 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1770
1771 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001772}
1773
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001774status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001775 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1776}
1777
1778status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001779 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001780 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001781 Mutex::Autolock il(mInterfaceLock);
1782 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001783
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001784 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1785 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001786 CLOGE("Stream %d does not exist", streamId);
1787 return BAD_VALUE;
1788 }
1789
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001790 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001791 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001792 return BAD_VALUE;
1793 }
1794
1795 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001796 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001797 return BAD_VALUE;
1798 }
1799
Ruben Brunkc78ac262015-08-13 17:58:46 -07001800 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001801}
1802
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001803status_t Camera3Device::tearDown(int streamId) {
1804 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001805 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001806 Mutex::Autolock il(mInterfaceLock);
1807 Mutex::Autolock l(mLock);
1808
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001809 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1810 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001811 CLOGE("Stream %d does not exist", streamId);
1812 return BAD_VALUE;
1813 }
1814
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001815 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1816 CLOGE("Stream %d is a target of a in-progress request", streamId);
1817 return BAD_VALUE;
1818 }
1819
1820 return stream->tearDown();
1821}
1822
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001823status_t Camera3Device::addBufferListenerForStream(int streamId,
1824 wp<Camera3StreamBufferListener> listener) {
1825 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001826 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001827 Mutex::Autolock il(mInterfaceLock);
1828 Mutex::Autolock l(mLock);
1829
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001830 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1831 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001832 CLOGE("Stream %d does not exist", streamId);
1833 return BAD_VALUE;
1834 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001835 stream->addBufferListener(listener);
1836
1837 return OK;
1838}
1839
Austin Borger4a870a32022-02-25 01:48:41 +00001840float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1841 camera_metadata_entry minDurations =
1842 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1843 for (size_t i = 0; i < minDurations.count; i += 4) {
1844 if (minDurations.data.i64[i] == stream->getFormat()
1845 && minDurations.data.i64[i+1] == stream->getWidth()
1846 && minDurations.data.i64[i+2] == stream->getHeight()) {
1847 int64_t minFrameDuration = minDurations.data.i64[i+3];
1848 return 1e9f / minFrameDuration;
1849 }
1850 }
1851 return 0.0f;
1852}
1853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 * Methods called by subclasses
1856 */
1857
1858void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001859 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001860 std::vector<int> streamIds;
1861 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001862 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001863
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 {
1865 // Need mLock to safely update state and synchronize to current
1866 // state of methods in flight.
1867 Mutex::Autolock l(mLock);
1868 // We can get various system-idle notices from the status tracker
1869 // while starting up. Only care about them if we've actually sent
1870 // in some requests recently.
1871 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1872 return;
1873 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001874 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1875 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001876 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877
1878 // Skip notifying listener if we're doing some user-transparent
1879 // state changes
1880 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001881
Austin Borger4a870a32022-02-25 01:48:41 +00001882 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1883 auto stream = mOutputStreams[i];
1884 if (stream.get() == nullptr) continue;
1885
1886 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1887 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1888
1889 // Populate stream statistics in case of Idle
1890 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001891 streamIds.push_back(stream->getId());
1892 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1893 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001894 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001895 if (camera3Stream != nullptr) {
1896 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001897 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001898 }
1899 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001900 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001901 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001902 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001903 stream->getDynamicRangeProfile(), streamUseCase,
1904 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001905 }
1906 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001907 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001908
1909 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001910 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001911 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001912 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001914 status_t res = OK;
1915 if (listener != nullptr) {
1916 if (idle) {
1917 // Get session stats from the builder, and notify the listener.
1918 int64_t requestCount, resultErrorCount;
1919 bool deviceError;
1920 std::map<int, StreamStats> streamStatsMap;
1921 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1922 &deviceError, &streamStatsMap);
1923 for (size_t i = 0; i < streamIds.size(); i++) {
1924 int streamId = streamIds[i];
1925 auto stats = streamStatsMap.find(streamId);
1926 if (stats != streamStatsMap.end()) {
1927 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1928 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1929 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1930 streamStats[i].mHistogramType =
1931 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1932 streamStats[i].mHistogramBins.assign(
1933 stats->second.mCaptureLatencyBins.begin(),
1934 stats->second.mCaptureLatencyBins.end());
1935 streamStats[i].mHistogramCounts.assign(
1936 stats->second.mCaptureLatencyHistogram.begin(),
1937 stats->second.mCaptureLatencyHistogram.end());
1938 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001939 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001940 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1941 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001942 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001943 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001944 }
1945 if (res != OK) {
1946 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1947 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 }
1949}
1950
Shuzhen Wang758c2152017-01-10 18:26:18 -08001951status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001952 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001953 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001954 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1955 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001956
1957 if (surfaceIds == nullptr) {
1958 return BAD_VALUE;
1959 }
1960
Zhijun He5d677d12016-05-29 16:52:39 -07001961 Mutex::Autolock il(mInterfaceLock);
1962 Mutex::Autolock l(mLock);
1963
Shuzhen Wang758c2152017-01-10 18:26:18 -08001964 if (consumers.size() == 0) {
1965 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001966 return BAD_VALUE;
1967 }
1968
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001969 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1970 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001971 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001972 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001973 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001974
1975 // isConsumerConfigurationDeferred will be off after setConsumers
1976 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001977 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001978 if (res != OK) {
1979 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1980 return res;
1981 }
1982
Emilian Peev40ead602017-09-26 15:46:36 +01001983 for (auto &consumer : consumers) {
1984 int id = stream->getSurfaceId(consumer);
1985 if (id < 0) {
1986 CLOGE("Invalid surface id!");
1987 return BAD_VALUE;
1988 }
1989 surfaceIds->push_back(id);
1990 }
1991
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001992 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001993 if (!stream->isConfiguring()) {
1994 CLOGE("Stream %d was already fully configured.", streamId);
1995 return INVALID_OPERATION;
1996 }
Zhijun He5d677d12016-05-29 16:52:39 -07001997
Shuzhen Wang0129d522016-10-30 22:43:41 -07001998 res = stream->finishConfiguration();
1999 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002000 // If finishConfiguration fails due to abandoned surface, do not set
2001 // device to error state.
2002 bool isSurfaceAbandoned =
2003 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2004 if (!isSurfaceAbandoned) {
2005 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2006 stream->getId(), strerror(-res), res);
2007 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002008 return res;
2009 }
Zhijun He5d677d12016-05-29 16:52:39 -07002010 }
2011
2012 return OK;
2013}
2014
Emilian Peev40ead602017-09-26 15:46:36 +01002015status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2016 const std::vector<OutputStreamInfo> &outputInfo,
2017 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2018 Mutex::Autolock il(mInterfaceLock);
2019 Mutex::Autolock l(mLock);
2020
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002021 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2022 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002023 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002024 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002025 }
2026
2027 for (const auto &it : removedSurfaceIds) {
2028 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2029 CLOGE("Shared surface still part of a pending request!");
2030 return -EBUSY;
2031 }
2032 }
2033
Emilian Peev40ead602017-09-26 15:46:36 +01002034 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2035 if (res != OK) {
2036 CLOGE("Stream %d failed to update stream (error %d %s) ",
2037 streamId, res, strerror(-res));
2038 if (res == UNKNOWN_ERROR) {
2039 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2040 __FUNCTION__);
2041 }
2042 return res;
2043 }
2044
2045 return res;
2046}
2047
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002048status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002052 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2053 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002054 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2055 return BAD_VALUE;
2056 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002057
2058 if (dropping) {
2059 mSessionStatsBuilder.stopCounter(streamId);
2060 } else {
2061 mSessionStatsBuilder.startCounter(streamId);
2062 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002063 return stream->dropBuffers(dropping);
2064}
2065
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 * Camera3Device private methods
2068 */
2069
2070sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002071 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002074 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002075 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076
2077 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002078 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 if (inputStreams.count > 0) {
2080 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002081 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002082 CLOGE("Request references unknown input stream %d",
2083 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084 return NULL;
2085 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002086
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002088 SET_ERR_L("%s: input stream %d is not configured!",
2089 __FUNCTION__, mInputStream->getId());
2090 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002091 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002092 // Check if stream prepare is blocking requests.
2093 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002094 CLOGE("Request references an input stream that's being prepared!");
2095 return NULL;
2096 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097
2098 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002099 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 }
2101
2102 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002103 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002105 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002106 return NULL;
2107 }
2108
2109 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002110 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2111 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002112 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002113 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002114 return NULL;
2115 }
Zhijun He5d677d12016-05-29 16:52:39 -07002116 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002117 auto iter = surfaceMap.find(streams.data.i32[i]);
2118 if (iter != surfaceMap.end()) {
2119 const std::vector<size_t>& surfaces = iter->second;
2120 for (const auto& surface : surfaces) {
2121 if (stream->isConsumerConfigurationDeferred(surface)) {
2122 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2123 "due to deferred consumer", stream->getId(), surface);
2124 return NULL;
2125 }
2126 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002127 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002128 }
2129
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002131 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2132 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002133 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002134 // Check if stream prepare is blocking requests.
2135 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002136 CLOGE("Request references an output stream that's being prepared!");
2137 return NULL;
2138 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139
2140 newRequest->mOutputStreams.push(stream);
2141 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002142 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002143 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002144
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002145 auto rotateAndCropEntry =
2146 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2147 if (rotateAndCropEntry.count > 0 &&
2148 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2149 newRequest->mRotateAndCropAuto = true;
2150 } else {
2151 newRequest->mRotateAndCropAuto = false;
2152 }
2153
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002154 auto autoframingEntry =
2155 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2156 if (autoframingEntry.count > 0 &&
2157 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2158 newRequest->mAutoframingAuto = true;
2159 } else {
2160 newRequest->mAutoframingAuto = false;
2161 }
2162
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002163 auto zoomRatioEntry =
2164 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2165 if (zoomRatioEntry.count > 0 &&
2166 zoomRatioEntry.data.f[0] == 1.0f) {
2167 newRequest->mZoomRatioIs1x = true;
2168 } else {
2169 newRequest->mZoomRatioIs1x = false;
2170 }
2171
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002172 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002173 for (auto& settings : newRequest->mSettingsList) {
2174 auto testPatternModeEntry =
2175 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2176 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2177 testPatternModeEntry.data.i32[0] :
2178 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002179
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002180 auto testPatternDataEntry =
2181 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2182 if (testPatternDataEntry.count >= 4) {
2183 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2184 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2185 } else {
2186 settings.mOriginalTestPatternData[0] = 0;
2187 settings.mOriginalTestPatternData[1] = 0;
2188 settings.mOriginalTestPatternData[2] = 0;
2189 settings.mOriginalTestPatternData[3] = 0;
2190 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002191 }
2192 }
2193
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002195}
2196
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002197void Camera3Device::cancelStreamsConfigurationLocked() {
2198 int res = OK;
2199 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2200 res = mInputStream->cancelConfiguration();
2201 if (res != OK) {
2202 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2203 mInputStream->getId(), strerror(-res), res);
2204 }
2205 }
2206
2207 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002208 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002209 if (outputStream->isConfiguring()) {
2210 res = outputStream->cancelConfiguration();
2211 if (res != OK) {
2212 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2213 outputStream->getId(), strerror(-res), res);
2214 }
2215 }
2216 }
2217
2218 // Return state to that at start of call, so that future configures
2219 // properly clean things up
2220 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2221 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002222
2223 res = mPreparerThread->resume();
2224 if (res != OK) {
2225 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2226 }
2227}
2228
Emilian Peev0d0191e2020-04-21 17:01:18 -07002229bool Camera3Device::checkAbandonedStreamsLocked() {
2230 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2231 return true;
2232 }
2233
2234 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2235 auto stream = mOutputStreams[i];
2236 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2237 return true;
2238 }
2239 }
2240
2241 return false;
2242}
2243
Emilian Peev3bead5f2020-05-28 17:29:08 -07002244bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002245 ATRACE_CALL();
2246 bool ret = false;
2247
Shuzhen Wang316781a2020-08-18 18:11:01 -07002248 nsecs_t startTime = systemTime();
2249
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002250 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002251 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2252
2253 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002254 if (checkAbandonedStreamsLocked()) {
2255 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2256 __FUNCTION__);
2257 return true;
2258 }
2259
Emilian Peev3bead5f2020-05-28 17:29:08 -07002260 status_t rc = NO_ERROR;
2261 bool markClientActive = false;
2262 if (mStatus == STATUS_ACTIVE) {
2263 markClientActive = true;
2264 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002265
2266 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2267 }
2268
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002269 if (rc == NO_ERROR) {
2270 mNeedConfig = true;
2271 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2272 if (rc == NO_ERROR) {
2273 ret = true;
2274 mPauseStateNotify = false;
2275 //Moving to active state while holding 'mLock' is important.
2276 //There could be pending calls to 'create-/deleteStream' which
2277 //will trigger another stream configuration while the already
2278 //present streams end up with outstanding buffers that will
2279 //not get drained.
2280 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002281 } else if (rc == DEAD_OBJECT) {
2282 // DEAD_OBJECT can be returned if either the consumer surface is
2283 // abandoned, or the HAL has died.
2284 // - If the HAL has died, configureStreamsLocked call will set
2285 // device to error state,
2286 // - If surface is abandoned, we should not set device to error
2287 // state.
2288 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002289 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002290 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002291 }
2292 } else {
2293 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2294 }
2295
Austin Borger74fca042022-05-23 12:41:21 -07002296 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002297 ns2ms(systemTime() - startTime));
2298
Emilian Peev3bead5f2020-05-28 17:29:08 -07002299 if (markClientActive) {
2300 mStatusTracker->markComponentActive(clientStatusId);
2301 }
2302
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002303 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002304}
2305
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002306status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002307 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 ATRACE_CALL();
2309 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002310
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002311 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002312 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 return INVALID_OPERATION;
2314 }
2315
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002316 if (operatingMode < 0) {
2317 CLOGE("Invalid operating mode: %d", operatingMode);
2318 return BAD_VALUE;
2319 }
2320
2321 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002322 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002323
2324 if (mOperatingMode != operatingMode) {
2325 mNeedConfig = true;
2326 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2327 mOperatingMode = operatingMode;
2328 }
2329
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002330 // Reset min expected duration when session is reconfigured.
2331 mMinExpectedDuration = 0;
2332
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002333 // In case called from configureStreams, abort queued input buffers not belonging to
2334 // any pending requests.
2335 if (mInputStream != NULL && notifyRequestThread) {
2336 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002337 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002338 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002339 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002340 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002341 if (res != OK) {
2342 // Exhausted acquiring all input buffers.
2343 break;
2344 }
2345
Emilian Peevf4816702020-04-03 15:44:51 -07002346 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002347 res = mInputStream->returnInputBuffer(inputBuffer);
2348 if (res != OK) {
2349 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2350 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2351 }
2352 }
2353 }
2354
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002355 if (!mNeedConfig) {
2356 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2357 return OK;
2358 }
2359
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002360 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002361 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002362 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2363 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002364 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002365 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002366 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002367 }
2368
Shuzhen Wang16610a62022-12-15 22:38:07 -08002369 // Override stream use case based on "adb shell command"
2370 overrideStreamUseCaseLocked();
2371
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002372 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002373 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002375 mPreparerThread->pause();
2376
Emilian Peevf4816702020-04-03 15:44:51 -07002377 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002378 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002380 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381
Emilian Peevf4816702020-04-03 15:44:51 -07002382 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002384 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002385
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386
2387 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002388 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389 inputStream = mInputStream->startConfiguration();
2390 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002391 CLOGE("Can't start input stream configuration");
2392 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 return INVALID_OPERATION;
2394 }
2395 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002396
2397 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 }
2399
Shuzhen Wang99080502021-03-07 21:08:20 -08002400 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002401 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002402 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002403
2404 // Don't configure bidi streams twice, nor add them twice to the list
2405 if (mOutputStreams[i].get() ==
2406 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2407
2408 config.num_streams--;
2409 continue;
2410 }
2411
Emilian Peevf4816702020-04-03 15:44:51 -07002412 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002413 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002414 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002415 CLOGE("Can't start output stream configuration");
2416 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417 return INVALID_OPERATION;
2418 }
2419 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002420
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002421 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002422 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2423 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002424 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2425 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002426 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2427 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002428 } else if (outputStream->data_space ==
2429 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2430 bufferSizes[k] = outputStream->width * outputStream->height;
2431 } else {
2432 ALOGW("%s: Blob dataSpace %d not supported",
2433 __FUNCTION__, outputStream->data_space);
2434 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002435 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002436
2437 if (mOutputStreams[i]->isMultiResolution()) {
2438 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2439 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2440 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2441 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002442
2443 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2444 composerSurfacePresent = true;
2445 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 }
2447
2448 config.streams = streams.editArray();
2449
2450 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002451 // max_buffers, usage, and priv fields, as well as data_space and format
2452 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002453
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002454 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002455 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002456 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002458 if (res == BAD_VALUE) {
2459 // HAL rejected this set of streams as unsupported, clean up config
2460 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002461 CLOGE("Set of requested inputs/outputs not supported by HAL");
2462 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002463 return BAD_VALUE;
2464 } else if (res != OK) {
2465 // Some other kind of error from configure_streams - this is not
2466 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002467 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2468 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002469 return res;
2470 }
2471
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002472 // Finish all stream configuration immediately.
2473 // TODO: Try to relax this later back to lazy completion, which should be
2474 // faster
2475
Igor Murashkin073f8572013-05-02 14:59:28 -07002476 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002477 bool streamReConfigured = false;
2478 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002479 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002480 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002481 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002482 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002483 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2484 return DEAD_OBJECT;
2485 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002486 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002487 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002488 if (streamReConfigured) {
2489 mInterface->onStreamReConfigured(mInputStream->getId());
2490 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002491 }
2492
2493 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002494 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002495 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002496 bool streamReConfigured = false;
2497 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002498 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002499 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002500 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002501 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002502 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2503 return DEAD_OBJECT;
2504 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002505 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002506 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002507 if (streamReConfigured) {
2508 mInterface->onStreamReConfigured(outputStream->getId());
2509 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002510 }
2511 }
2512
Emilian Peeve23f1d92021-09-20 14:56:01 -07002513 mRequestThread->setComposerSurface(composerSurfacePresent);
2514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002515 // Request thread needs to know to avoid using repeat-last-settings protocol
2516 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002517 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002518 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2519 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002520 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002521
Zhijun He90f7c372016-08-16 16:19:43 -07002522 char value[PROPERTY_VALUE_MAX];
2523 property_get("camera.fifo.disable", value, "0");
2524 int32_t disableFifo = atoi(value);
2525 if (disableFifo != 1) {
2526 // Boost priority of request thread to SCHED_FIFO.
2527 pid_t requestThreadTid = mRequestThread->getTid();
2528 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002529 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002530 if (res != OK) {
2531 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2532 strerror(-res), res);
2533 } else {
2534 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2535 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002536 }
2537
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002538 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002539 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2540 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2541 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2542 sessionParams.unlock(newSessionParams);
2543 mSessionParams.unlock(currentSessionParams);
2544 if (updateSessionParams) {
2545 mSessionParams = sessionParams;
2546 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002547
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002548 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002549
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002551 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002553 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002554
Zhijun He0a210512014-07-24 13:45:15 -07002555 // tear down the deleted streams after configure streams.
2556 mDeletedStreams.clear();
2557
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002558 auto rc = mPreparerThread->resume();
2559 if (rc != OK) {
2560 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2561 return rc;
2562 }
2563
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002564 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002565 mRequestBufferSM.onStreamsConfigured();
2566 }
2567
Cliff Wu3b268182021-07-06 15:44:43 +08002568 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002569 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002570 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002571 // configure the injection streams.
2572 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002573 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002574 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2575 res = mInjectionMethods->injectCamera(config, bufferSizes);
2576 if (res != OK) {
2577 ALOGE("Can't finish inject camera process!");
2578 return res;
2579 }
Cliff Wu3b268182021-07-06 15:44:43 +08002580 } else {
2581 // First run configureStreamsLocked() and then call injectCamera() case:
2582 // If the stream configuration has been completed and camera deive is active, but the
2583 // injection camera has not been injected yet, we need to store the stream configuration of
2584 // the internal camera (because the stream configuration of the injection camera is based
2585 // on the internal camera). When injecting occurs later, this configuration can be used by
2586 // the injection camera.
2587 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2588 " injection camera has not been injected yet.", __FUNCTION__);
2589 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002590 }
2591
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002593}
2594
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002595status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002596 ATRACE_CALL();
2597 status_t res;
2598
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002599 if (mFakeStreamId != NO_STREAM) {
2600 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002601 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002602 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002603 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002604 return INVALID_OPERATION;
2605 }
2606
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002607 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002608
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002609 sp<Camera3OutputStreamInterface> fakeStream =
2610 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002611
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002612 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002613 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002614 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002615 return res;
2616 }
2617
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002618 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619 mNextStreamId++;
2620
2621 return OK;
2622}
2623
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002624status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002625 ATRACE_CALL();
2626 status_t res;
2627
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002628 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002629 if (mOutputStreams.size() == 1) return OK;
2630
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002631 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002632
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002633 // Ok, have a fake stream and there's at least one other output stream,
2634 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002635
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002636 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002637 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002638 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002639 return INVALID_OPERATION;
2640 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002641 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642
2643 // Free up the stream endpoint so that it can be used by some other stream
2644 res = deletedStream->disconnect();
2645 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002646 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002647 // fall through since we want to still list the stream as deleted.
2648 }
2649 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002650 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002651
2652 return res;
2653}
2654
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002655void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002656 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002657 Mutex::Autolock l(mLock);
2658 va_list args;
2659 va_start(args, fmt);
2660
2661 setErrorStateLockedV(fmt, args);
2662
2663 va_end(args);
2664}
2665
2666void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002667 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002668 Mutex::Autolock l(mLock);
2669 setErrorStateLockedV(fmt, args);
2670}
2671
2672void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2673 va_list args;
2674 va_start(args, fmt);
2675
2676 setErrorStateLockedV(fmt, args);
2677
2678 va_end(args);
2679}
2680
2681void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002682 // Print out all error messages to log
2683 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002684 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002685
2686 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002687 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002688
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002689 mErrorCause = errorCause;
2690
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002691 if (mRequestThread != nullptr) {
2692 mRequestThread->setPaused(true);
2693 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002694 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002695
2696 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002697 sp<NotificationListener> listener = mListener.promote();
2698 if (listener != NULL) {
2699 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002700 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002701 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002702 }
2703
2704 // Save stack trace. View by dumping it later.
2705 CameraTraces::saveTrace();
2706 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002707}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002708
2709/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002710 * In-flight request management
2711 */
2712
Jianing Weicb0652e2014-03-12 18:29:36 -07002713status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002714 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002715 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002716 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002717 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto, bool autoframingAuto,
Shuzhen Wang99080502021-03-07 21:08:20 -08002718 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002719 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002720 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002721 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002722
2723 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002724 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002725 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002726 isStillCapture, isZslCapture, rotateAndCropAuto, autoframingAuto, cameraIdsWithZoom,
2727 requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002728 if (res < 0) return res;
2729
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002730 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002731 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2732 // avoid a deadlock during reprocess requests.
2733 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002734 if (mStatusTracker != nullptr) {
2735 mStatusTracker->markComponentActive(mInFlightStatusId);
2736 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002737 }
2738
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002739 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002740 return OK;
2741}
2742
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002743void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002744 // Indicate idle inFlightMap to the status tracker
2745 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002746 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002747 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2748 // avoid a deadlock during reprocess requests.
2749 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002750 if (mStatusTracker != nullptr) {
2751 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2752 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002753 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002754 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002755}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002756
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002757void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002758 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002759 // something has likely gone wrong. This might still be legit only if application send in
2760 // a long burst of long exposure requests.
2761 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2762 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2763 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2764 mInFlightMap.size(), mExpectedInflightDuration);
2765 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2766 kInFlightWarnLimitHighSpeed) {
2767 CLOGW("In-flight list too large for high speed configuration: %zu,"
2768 "total inflight duration %" PRIu64,
2769 mInFlightMap.size(), mExpectedInflightDuration);
2770 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002771 }
2772}
2773
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002774void Camera3Device::onInflightMapFlushedLocked() {
2775 mExpectedInflightDuration = 0;
2776}
2777
2778void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002779 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002780 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2781 mInFlightMap.removeItemsAt(idx, 1);
2782
2783 onInflightEntryRemovedLocked(duration);
2784}
2785
2786
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002787void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002788 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002789 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002790 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002791 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002792 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002793 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002794
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002795 FlushInflightReqStates states {
2796 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002797 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002798
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002799 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002800}
2801
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002802CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002803 ALOGV("%s", __FUNCTION__);
2804
Igor Murashkin1e479c02013-09-06 16:55:14 -07002805 CameraMetadata retVal;
2806
2807 if (mRequestThread != NULL) {
2808 retVal = mRequestThread->getLatestRequest();
2809 }
2810
Igor Murashkin1e479c02013-09-06 16:55:14 -07002811 return retVal;
2812}
2813
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002814void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002815 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002816 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002817 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2818 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002819
2820 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002821 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002822}
2823
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002824void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002825 std::vector<native_handle_t*> *handles, bool closeFd) {
2826 if (handles == nullptr) {
2827 return;
2828 }
2829 if (closeFd) {
2830 for (auto& handle : *handles) {
2831 native_handle_close(handle);
2832 }
2833 }
2834 for (auto& handle : *handles) {
2835 native_handle_delete(handle);
2836 }
2837 handles->clear();
2838 return;
2839}
2840
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002841/**
2842 * HalInterface inner class methods
2843 */
2844
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002845void Camera3Device::HalInterface::getInflightBufferKeys(
2846 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002847 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002848 return;
2849}
2850
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002851void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2852 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002853 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002854 return;
2855}
2856
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002857bool Camera3Device::HalInterface::verifyBufferIds(
2858 int32_t streamId, std::vector<uint64_t>& bufIds) {
2859 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002860}
2861
2862status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002863 int32_t frameNumber, int32_t streamId,
2864 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002865 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002866}
2867
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002868status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002869 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002870 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002871}
2872
2873// Find and pop a buffer_handle_t based on bufferId
2874status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002875 uint64_t bufferId,
2876 /*out*/ buffer_handle_t** buffer,
2877 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002878 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002879}
2880
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002881std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2882 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002883 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002884}
2885
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002886uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2887 const native_handle_t* handle) {
2888 return mBufferRecords.removeOneBufferCache(streamId, handle);
2889}
2890
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002891void Camera3Device::HalInterface::onBufferFreed(
2892 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002893 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2894 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2895 if (bufferId != BUFFER_ID_NO_BUFFER) {
2896 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002897 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002898}
2899
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002900void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002901 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2902 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2903 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002904 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2905 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002906}
2907
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002908/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002909 * RequestThread inner class methods
2910 */
2911
2912Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002913 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002914 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002915 bool useHalBufManager,
Austin Borger18b30a72022-10-27 12:20:29 -07002916 bool supportCameraMute,
2917 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002918 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002919 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002920 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002921 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002922 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002923 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002924 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002925 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002926 mReconfigured(false),
2927 mDoPause(false),
2928 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002929 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002930 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002931 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002932 mCurrentAfTriggerId(0),
2933 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002934 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Bharatt Kukreja0e13db32022-12-07 21:38:45 +00002935 mAutoframingOverride(ANDROID_CONTROL_AUTOFRAMING_OFF),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002936 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002937 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002938 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002939 mRepeatingLastFrameNumber(
2940 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002941 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002942 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002943 mRequestLatency(kRequestLatencyBinSize),
2944 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002945 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002946 mUseHalBufManager(useHalBufManager),
Austin Borger18b30a72022-10-27 12:20:29 -07002947 mSupportCameraMute(supportCameraMute),
2948 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002949 mStatusId = statusTracker->addComponent("RequestThread");
Emilian Peeva1b26262023-02-06 17:27:41 -08002950 mVndkVersion = property_get_int32("ro.vndk.version", __ANDROID_API_FUTURE__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002951}
2952
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953Camera3Device::RequestThread::~RequestThread() {}
2954
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002955void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002956 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002957 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002958 Mutex::Autolock l(mRequestLock);
2959 mListener = listener;
2960}
2961
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002962void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002963 const CameraMetadata& sessionParams,
2964 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002965 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002966 Mutex::Autolock l(mRequestLock);
2967 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002968 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002969 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002970 // Prepare video stream for high speed recording.
2971 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002972 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002973}
2974
Jianing Wei90e59c92014-03-12 18:29:36 -07002975status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002976 List<sp<CaptureRequest> > &requests,
2977 /*out*/
2978 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002979 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002980 Mutex::Autolock l(mRequestLock);
2981 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2982 ++it) {
2983 mRequestQueue.push_back(*it);
2984 }
2985
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002986 if (lastFrameNumber != NULL) {
2987 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2988 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2989 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2990 *lastFrameNumber);
2991 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002992
Jianing Wei90e59c92014-03-12 18:29:36 -07002993 unpauseForNewRequests();
2994
2995 return OK;
2996}
2997
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002998
2999status_t Camera3Device::RequestThread::queueTrigger(
3000 RequestTrigger trigger[],
3001 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003002 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003003 Mutex::Autolock l(mTriggerMutex);
3004 status_t ret;
3005
3006 for (size_t i = 0; i < count; ++i) {
3007 ret = queueTriggerLocked(trigger[i]);
3008
3009 if (ret != OK) {
3010 return ret;
3011 }
3012 }
3013
3014 return OK;
3015}
3016
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003017const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3018 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003019 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003020 if (d != nullptr) return d->mId;
3021 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003022}
3023
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003024status_t Camera3Device::RequestThread::queueTriggerLocked(
3025 RequestTrigger trigger) {
3026
3027 uint32_t tag = trigger.metadataTag;
3028 ssize_t index = mTriggerMap.indexOfKey(tag);
3029
3030 switch (trigger.getTagType()) {
3031 case TYPE_BYTE:
3032 // fall-through
3033 case TYPE_INT32:
3034 break;
3035 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003036 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3037 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003038 return INVALID_OPERATION;
3039 }
3040
3041 /**
3042 * Collect only the latest trigger, since we only have 1 field
3043 * in the request settings per trigger tag, and can't send more than 1
3044 * trigger per request.
3045 */
3046 if (index != NAME_NOT_FOUND) {
3047 mTriggerMap.editValueAt(index) = trigger;
3048 } else {
3049 mTriggerMap.add(tag, trigger);
3050 }
3051
3052 return OK;
3053}
3054
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003055status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003056 const RequestList &requests,
3057 /*out*/
3058 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003059 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003060 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003061 if (lastFrameNumber != NULL) {
3062 *lastFrameNumber = mRepeatingLastFrameNumber;
3063 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003064 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003065 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003066 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3067 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003068
3069 unpauseForNewRequests();
3070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003072 return OK;
3073}
3074
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003075bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003076 if (mRepeatingRequests.empty()) {
3077 return false;
3078 }
3079 int32_t requestId = requestIn->mResultExtras.requestId;
3080 const RequestList &repeatRequests = mRepeatingRequests;
3081 // All repeating requests are guaranteed to have same id so only check first quest
3082 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3083 return (firstRequest->mResultExtras.requestId == requestId);
3084}
3085
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003086status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003087 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003088 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003089 return clearRepeatingRequestsLocked(lastFrameNumber);
3090
3091}
3092
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003093status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(
3094 /*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003095 std::vector<int32_t> streamIds;
3096 for (const auto& request : mRepeatingRequests) {
3097 for (const auto& stream : request->mOutputStreams) {
3098 streamIds.push_back(stream->getId());
3099 }
3100 }
3101
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003102 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003103 if (lastFrameNumber != NULL) {
3104 *lastFrameNumber = mRepeatingLastFrameNumber;
3105 }
Emilian Peev2295df72021-11-12 18:14:10 -08003106
3107 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003109 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003110 return OK;
3111}
3112
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003113status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003114 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003115 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003116 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003117 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003118
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119 // Send errors for all requests pending in the request queue, including
3120 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003121 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003122 if (listener != NULL) {
3123 for (RequestList::iterator it = mRequestQueue.begin();
3124 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003125 // Abort the input buffers for reprocess requests.
3126 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003127 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003128 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003129 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003130 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003131 if (res != OK) {
3132 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3133 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3134 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003135 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003136 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3137 if (res != OK) {
3138 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3139 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3140 }
3141 }
3142 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003143 // Set the frame number this request would have had, if it
3144 // had been submitted; this frame number will not be reused.
3145 // The requestId and burstId fields were set when the request was
3146 // submitted originally (in convertMetadataListToRequestListLocked)
3147 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003148 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003149 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003150 }
3151 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003152 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003153
3154 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003155 mTriggerMap.clear();
Jayant Chowdharya93f3462022-11-01 23:32:45 +00003156 clearRepeatingRequestsLocked(lastFrameNumber);
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003157 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003158 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003159 return OK;
3160}
3161
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003162status_t Camera3Device::RequestThread::flush() {
3163 ATRACE_CALL();
3164 Mutex::Autolock l(mFlushLock);
3165
Emilian Peev08dd2452017-04-06 16:55:14 +01003166 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003167}
3168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003169void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003170 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003171 Mutex::Autolock l(mPauseLock);
3172 mDoPause = paused;
3173 mDoPauseSignal.signal();
3174}
3175
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003176status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3177 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003178 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003179 Mutex::Autolock l(mLatestRequestMutex);
3180 status_t res;
3181 while (mLatestRequestId != requestId) {
3182 nsecs_t startTime = systemTime();
3183
3184 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3185 if (res != OK) return res;
3186
3187 timeout -= (systemTime() - startTime);
3188 }
3189
3190 return OK;
3191}
3192
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003193void Camera3Device::RequestThread::requestExit() {
3194 // Call parent to set up shutdown
3195 Thread::requestExit();
3196 // The exit from any possible waits
3197 mDoPauseSignal.signal();
3198 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003199
3200 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3201 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003202}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003203
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003204void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003205 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003206 bool surfaceAbandoned = false;
3207 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003208 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003209 {
3210 Mutex::Autolock l(mRequestLock);
3211 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3212 // repeating requests.
3213 for (const auto& request : mRepeatingRequests) {
3214 for (const auto& s : request->mOutputStreams) {
3215 if (s->isAbandoned()) {
3216 surfaceAbandoned = true;
3217 clearRepeatingRequestsLocked(&lastFrameNumber);
3218 break;
3219 }
3220 }
3221 if (surfaceAbandoned) {
3222 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003223 }
3224 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003225 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003226 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003227
3228 if (listener != NULL && surfaceAbandoned) {
3229 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003230 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003231}
3232
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003233bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003234 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003235 status_t res;
3236 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003237 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003238 uint32_t numRequestProcessed = 0;
3239 for (size_t i = 0; i < batchSize; i++) {
3240 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003241 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003242 }
3243
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003244 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3245
3246 bool triggerRemoveFailed = false;
3247 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3248 for (size_t i = 0; i < numRequestProcessed; i++) {
3249 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3250 nextRequest.submitted = true;
3251
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003252 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003253
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003254 if (!triggerRemoveFailed) {
3255 // Remove any previously queued triggers (after unlock)
3256 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3257 if (removeTriggerRes != OK) {
3258 triggerRemoveFailed = true;
3259 triggerFailedRequest = nextRequest;
3260 }
3261 }
3262 }
3263
3264 if (triggerRemoveFailed) {
3265 SET_ERR("RequestThread: Unable to remove triggers "
3266 "(capture request %d, HAL device: %s (%d)",
3267 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3268 cleanUpFailedRequests(/*sendRequestError*/ false);
3269 return false;
3270 }
3271
3272 if (res != OK) {
3273 // Should only get a failure here for malformed requests or device-level
3274 // errors, so consider all errors fatal. Bad metadata failures should
3275 // come through notify.
3276 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3277 mNextRequests[numRequestProcessed].halRequest.frame_number,
3278 strerror(-res), res);
3279 cleanUpFailedRequests(/*sendRequestError*/ false);
3280 return false;
3281 }
3282 return true;
3283}
3284
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003285Camera3Device::RequestThread::ExpectedDurationInfo
3286 Camera3Device::RequestThread::calculateExpectedDurationRange(
3287 const camera_metadata_t *request) {
3288 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003289 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003290 InFlightRequest::kDefaultMaxExpectedDuration,
3291 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003292 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3293 find_camera_metadata_ro_entry(request,
3294 ANDROID_CONTROL_AE_MODE,
3295 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003296 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003297
3298 switch (e.data.u8[0]) {
3299 case ANDROID_CONTROL_AE_MODE_OFF:
3300 find_camera_metadata_ro_entry(request,
3301 ANDROID_SENSOR_EXPOSURE_TIME,
3302 &e);
3303 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003304 expectedDurationInfo.minDuration = e.data.i64[0];
3305 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003306 }
3307 find_camera_metadata_ro_entry(request,
3308 ANDROID_SENSOR_FRAME_DURATION,
3309 &e);
3310 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003311 expectedDurationInfo.minDuration =
3312 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3313 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003314 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003315 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003316 break;
3317 default:
3318 find_camera_metadata_ro_entry(request,
3319 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3320 &e);
3321 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003322 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3323 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003324 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003325 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003326 break;
3327 }
3328
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003329 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003330}
3331
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003332bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3333 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3334 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3335 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3336 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3337 return true;
3338 }
3339
3340 return false;
3341}
3342
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003343void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3344 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003345 camera_capture_request_t& halRequest = nextRequest.halRequest;
3346 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003347 Mutex::Autolock al(mLatestRequestMutex);
3348
Shuzhen Wang83bff122020-11-20 15:51:39 -08003349 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003350 mLatestRequest.acquire(cloned);
3351
3352 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003353 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3354 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3355 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003356 CameraMetadata(cloned));
3357 }
3358
3359 sp<Camera3Device> parent = mParent.promote();
3360 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003361 int32_t inputStreamId = -1;
3362 if (halRequest.input_buffer != nullptr) {
3363 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3364 }
3365
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003366 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003367 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003368 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3369 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003370 }
3371 }
3372
Shuzhen Wang83bff122020-11-20 15:51:39 -08003373 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003374 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003375 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003376 }
3377
Shuzhen Wang83bff122020-11-20 15:51:39 -08003378 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003379}
3380
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003381bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3382 ATRACE_CALL();
3383 bool updatesDetected = false;
3384
Emilian Peev4ec17882019-01-24 17:16:58 -08003385 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003386 for (auto tag : mSessionParamKeys) {
3387 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003388 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003389
3390 if (entry.count > 0) {
3391 bool isDifferent = false;
3392 if (lastEntry.count > 0) {
3393 // Have a last value, compare to see if changed
3394 if (lastEntry.type == entry.type &&
3395 lastEntry.count == entry.count) {
3396 // Same type and count, compare values
3397 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3398 size_t entryBytes = bytesPerValue * lastEntry.count;
3399 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3400 if (cmp != 0) {
3401 isDifferent = true;
3402 }
3403 } else {
3404 // Count or type has changed
3405 isDifferent = true;
3406 }
3407 } else {
3408 // No last entry, so always consider to be different
3409 isDifferent = true;
3410 }
3411
3412 if (isDifferent) {
3413 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003414 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3415 updatesDetected = true;
3416 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003417 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003418 }
3419 } else if (lastEntry.count > 0) {
3420 // Value has been removed
3421 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003422 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003423 updatesDetected = true;
3424 }
3425 }
3426
Emilian Peev4ec17882019-01-24 17:16:58 -08003427 bool reconfigureRequired;
3428 if (updatesDetected) {
3429 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3430 updatedParams);
3431 mLatestSessionParams = updatedParams;
3432 } else {
3433 reconfigureRequired = false;
3434 }
3435
3436 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003437}
3438
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003439bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003440 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003441 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003442 // Any function called from threadLoop() must not hold mInterfaceLock since
3443 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3444 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003445
3446 // Handle paused state.
3447 if (waitIfPaused()) {
3448 return true;
3449 }
3450
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003451 // Wait for the next batch of requests.
3452 waitForNextRequestBatch();
3453 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003454 return true;
3455 }
3456
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003457 // Get the latest request ID, if any
3458 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003459 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003460 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003461 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003462 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003463 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003464 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3465 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003466 }
3467
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003468 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3469 // or a single request from streaming or burst. In either case the first element
3470 // should contain the latest camera settings that we need to check for any session
3471 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003472 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003473 res = OK;
3474
3475 //Input stream buffers are already acquired at this point so an input stream
3476 //will not be able to move to idle state unless we force it.
3477 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3478 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3479 if (res != OK) {
3480 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3481 cleanUpFailedRequests(/*sendRequestError*/ false);
3482 return false;
3483 }
3484 }
3485
3486 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003487 sp<Camera3Device> parent = mParent.promote();
3488 if (parent != nullptr) {
Bharatt Kukrejad55c7a52022-08-16 00:48:40 +00003489 sp<StatusTracker> statusTracker = mStatusTracker.promote();
3490 if (statusTracker != nullptr) {
3491 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
3492 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003493 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003494 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003495 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003496
3497 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3498 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3499 if (res != OK) {
3500 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3501 cleanUpFailedRequests(/*sendRequestError*/ false);
3502 return false;
3503 }
3504 }
3505 }
3506 }
3507
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003508 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003509 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003510 if (res == TIMED_OUT) {
3511 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003512 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003513 // Check if any stream is abandoned.
3514 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003515 return true;
3516 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003517 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003518 return false;
3519 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003520
Zhijun Hecc27e112013-10-03 16:12:43 -07003521 // Inform waitUntilRequestProcessed thread of a new request ID
3522 {
3523 Mutex::Autolock al(mLatestRequestMutex);
3524
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003525 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003526 mLatestRequestSignal.signal();
3527 }
3528
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003529 // Submit a batch of requests to HAL.
3530 // Use flush lock only when submitting multilple requests in a batch.
3531 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3532 // which may take a long time to finish so synchronizing flush() and
3533 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3534 // For now, only synchronize for high speed recording and we should figure something out for
3535 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003536 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003537
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003538 if (useFlushLock) {
3539 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003540 }
3541
Zhijun Hef0645c12016-08-02 00:58:11 -07003542 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003543 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003544
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003545 sp<Camera3Device> parent = mParent.promote();
3546 if (parent != nullptr) {
3547 parent->mRequestBufferSM.onSubmittingRequest();
3548 }
3549
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003550 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003551 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003552 submitRequestSuccess = sendRequestsBatch();
3553
Shuzhen Wang686f6442017-06-20 16:16:04 -07003554 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3555 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003556
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003557 if (useFlushLock) {
3558 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003559 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003560
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003561 // Unset as current request
3562 {
3563 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003564 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003565 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003566 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003567
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003568 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003569}
3570
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003571status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3572 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3573 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3574 ANDROID_SCALER_CROP_REGION_SET};
3575 if (request == nullptr) {
3576 ALOGE("%s request metadata nullptr", __FUNCTION__);
3577 return BAD_VALUE;
3578 }
3579 status_t res = OK;
3580 for (const auto &key : kFwkOnlyRegionKeys) {
3581 if (request->exists(key)) {
3582 res = request->erase(key);
3583 if (res != OK) {
3584 return res;
3585 }
3586 }
3587 }
3588 return OK;
3589}
3590
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003591status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003592 ATRACE_CALL();
3593
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003594 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003595 for (size_t i = 0; i < mNextRequests.size(); i++) {
3596 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003597 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003598 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3599 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003600
3601 // Prepare a request to HAL
3602 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3603
3604 // Insert any queued triggers (before metadata is locked)
3605 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003606 if (res < 0) {
3607 SET_ERR("RequestThread: Unable to insert triggers "
3608 "(capture request %d, HAL device: %s (%d)",
3609 halRequest->frame_number, strerror(-res), res);
3610 return INVALID_OPERATION;
3611 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003612
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003613 int triggerCount = res;
3614 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3615 mPrevTriggers = triggerCount;
3616
Emilian Peeve23f1d92021-09-20 14:56:01 -07003617 // Do not override rotate&crop for stream configurations that include
Austin Borger18b30a72022-10-27 12:20:29 -07003618 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3619 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3620 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003621 overrideAutoRotateAndCrop(captureRequest);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003622 bool autoframingChanged = overrideAutoframing(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003623 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003624
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003625 // If the request is the same as last, or we had triggers now or last time or
3626 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003627 bool newRequest =
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003628 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged ||
3629 autoframingChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003630 // Request settings are all the same within one batch, so only treat the first
3631 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003632 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003633 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003634 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003635 /**
3636 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003637 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003638 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003639 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003641 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003642 "(capture request %d, HAL device: %s (%d)",
3643 halRequest->frame_number, strerror(-res), res);
3644 return INVALID_OPERATION;
3645 }
3646
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003647 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003648 sp<Camera3Device> parent = mParent.promote();
3649 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003650 List<PhysicalCameraSettings>::iterator it;
3651 for (it = captureRequest->mSettingsList.begin();
3652 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003653 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3654 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003655 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3656 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3657 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3658 res);
3659 return INVALID_OPERATION;
3660 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003661 continue;
3662 }
3663
3664 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3665 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3666 updateCaptureRequest(&(it->metadata));
3667 if (res != OK) {
3668 SET_ERR("RequestThread: Unable to correct capture requests "
3669 "for scaler crop region and metering regions for request "
3670 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3671 res);
3672 return INVALID_OPERATION;
3673 }
3674 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003675 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3676 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3677 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3678 res);
3679 return INVALID_OPERATION;
3680 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003681 }
3682 }
3683
3684 // Correct metadata regions for distortion correction if enabled
3685 for (it = captureRequest->mSettingsList.begin();
3686 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003687 if (parent->mDistortionMappers.find(it->cameraId) ==
3688 parent->mDistortionMappers.end()) {
3689 continue;
3690 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003691
3692 if (!captureRequest->mDistortionCorrectionUpdated) {
3693 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3694 &(it->metadata));
3695 if (res != OK) {
3696 SET_ERR("RequestThread: Unable to correct capture requests "
3697 "for lens distortion for request %d: %s (%d)",
3698 halRequest->frame_number, strerror(-res), res);
3699 return INVALID_OPERATION;
3700 }
3701 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003702 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003703 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003704
3705 for (it = captureRequest->mSettingsList.begin();
3706 it != captureRequest->mSettingsList.end(); it++) {
3707 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3708 parent->mZoomRatioMappers.end()) {
3709 continue;
3710 }
3711
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003712 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003713 cameraIdsWithZoom.insert(it->cameraId);
3714 }
3715
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003716 if (!captureRequest->mZoomRatioUpdated) {
3717 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3718 &(it->metadata));
3719 if (res != OK) {
3720 SET_ERR("RequestThread: Unable to correct capture requests "
3721 "for zoom ratio for request %d: %s (%d)",
3722 halRequest->frame_number, strerror(-res), res);
3723 return INVALID_OPERATION;
3724 }
3725 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003726 }
3727 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003728 if (captureRequest->mRotateAndCropAuto &&
3729 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003730 for (it = captureRequest->mSettingsList.begin();
3731 it != captureRequest->mSettingsList.end(); it++) {
3732 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3733 if (mapper != parent->mRotateAndCropMappers.end()) {
3734 res = mapper->second.updateCaptureRequest(&(it->metadata));
3735 if (res != OK) {
3736 SET_ERR("RequestThread: Unable to correct capture requests "
3737 "for rotate-and-crop for request %d: %s (%d)",
3738 halRequest->frame_number, strerror(-res), res);
3739 return INVALID_OPERATION;
3740 }
3741 }
3742 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003743 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003744 }
Emilian Peeva1b26262023-02-06 17:27:41 -08003745
3746 for (it = captureRequest->mSettingsList.begin();
3747 it != captureRequest->mSettingsList.end(); it++) {
3748 res = hardware::cameraservice::utils::conversion::aidl::filterVndkKeys(
3749 mVndkVersion, it->metadata, false /*isStatic*/);
3750 if (res != OK) {
3751 SET_ERR("RequestThread: Failed during VNDK filter of capture requests "
3752 "%d: %s (%d)", halRequest->frame_number, strerror(-res), res);
3753 return INVALID_OPERATION;
3754 }
3755 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003756 }
3757 }
3758
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003759 /**
3760 * The request should be presorted so accesses in HAL
3761 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3762 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003763 captureRequest->mSettingsList.begin()->metadata.sort();
3764 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003765 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003766 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003767 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3768
3769 IF_ALOGV() {
3770 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3771 find_camera_metadata_ro_entry(
3772 halRequest->settings,
3773 ANDROID_CONTROL_AF_TRIGGER,
3774 &e
3775 );
3776 if (e.count > 0) {
3777 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3778 __FUNCTION__,
3779 halRequest->frame_number,
3780 e.data.u8[0]);
3781 }
3782 }
3783 } else {
3784 // leave request.settings NULL to indicate 'reuse latest given'
3785 ALOGVV("%s: Request settings are REUSED",
3786 __FUNCTION__);
3787 }
3788
Emilian Peevaebbe412018-01-15 13:53:24 +00003789 if (captureRequest->mSettingsList.size() > 1) {
3790 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3791 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003792 if (newRequest) {
3793 halRequest->physcam_settings =
3794 new const camera_metadata* [halRequest->num_physcam_settings];
3795 } else {
3796 halRequest->physcam_settings = nullptr;
3797 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003798 auto it = ++captureRequest->mSettingsList.begin();
3799 size_t i = 0;
3800 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3801 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003802 if (newRequest) {
3803 it->metadata.sort();
3804 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3805 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003806 }
3807 }
3808
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003809 uint32_t totalNumBuffers = 0;
3810
3811 // Fill in buffers
3812 if (captureRequest->mInputStream != NULL) {
3813 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003814
3815 halRequest->input_width = captureRequest->mInputBufferSize.width;
3816 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003817 totalNumBuffers += 1;
3818 } else {
3819 halRequest->input_buffer = NULL;
3820 }
3821
Emilian Peevf4816702020-04-03 15:44:51 -07003822 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003823 captureRequest->mOutputStreams.size());
3824 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003825 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003826
3827 sp<Camera3Device> parent = mParent.promote();
3828 if (parent == NULL) {
3829 // Should not happen, and nowhere to send errors to, so just log it
3830 CLOGE("RequestThread: Parent is gone");
3831 return INVALID_OPERATION;
3832 }
3833 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3834
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003835 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003836 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003837 sp<Camera3OutputStreamInterface> outputStream =
3838 captureRequest->mOutputStreams.editItemAt(j);
3839 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003840
3841 // Prepare video buffers for high speed recording on the first video request.
3842 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3843 // Only try to prepare video stream on the first video request.
3844 mPrepareVideoStream = false;
3845
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003846 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3847 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003848 while (res == NOT_ENOUGH_DATA) {
3849 res = outputStream->prepareNextBuffer();
3850 }
3851 if (res != OK) {
3852 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3853 __FUNCTION__, strerror(-res), res);
3854 outputStream->cancelPrepare();
3855 }
3856 }
3857
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003858 std::vector<size_t> uniqueSurfaceIds;
3859 res = outputStream->getUniqueSurfaceIds(
3860 captureRequest->mOutputSurfaces[streamId],
3861 &uniqueSurfaceIds);
3862 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3863 if (res != OK && res != INVALID_OPERATION) {
3864 ALOGE("%s: failed to query stream %d unique surface IDs",
3865 __FUNCTION__, streamId);
3866 return res;
3867 }
3868 if (res == OK) {
3869 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3870 }
3871
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003872 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003873 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003874 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003875 return TIMED_OUT;
3876 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003877 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003878 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003879 buffer.stream = outputStream->asHalStream();
3880 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003881 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003882 buffer.acquire_fence = -1;
3883 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003884 // Mark the output stream as unpreparable to block clients from calling
3885 // 'prepare' after this request reaches CameraHal and before the respective
3886 // buffers are requested.
3887 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003888 } else {
3889 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3890 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003891 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003892 if (res != OK) {
3893 // Can't get output buffer from gralloc queue - this could be due to
3894 // abandoned queue or other consumer misbehavior, so not a fatal
3895 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003896 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003897 " %s (%d)", strerror(-res), res);
3898
3899 return TIMED_OUT;
3900 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003901 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003902
3903 {
3904 sp<Camera3Device> parent = mParent.promote();
3905 if (parent != nullptr) {
3906 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3907 for (const auto& settings : captureRequest->mSettingsList) {
3908 if ((streamCameraId.isEmpty() &&
3909 parent->getId() == settings.cameraId.c_str()) ||
3910 streamCameraId == settings.cameraId.c_str()) {
3911 outputStream->fireBufferRequestForFrameNumber(
3912 captureRequest->mResultExtras.frameNumber,
3913 settings.metadata);
3914 }
3915 }
3916 }
3917 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003918
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003919 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003920 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3921 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3922 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3923 } else if (!physicalCameraId.isEmpty()) {
3924 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003925 }
3926 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003927 }
3928 totalNumBuffers += halRequest->num_output_buffers;
3929
3930 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003931 // If this request list is for constrained high speed recording (not
3932 // preview), and the current request is not the last one in the batch,
3933 // do not send callback to the app.
3934 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003935 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003936 hasCallback = false;
3937 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003938 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003939 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003940 const camera_metadata_t* settings = halRequest->settings;
3941 bool shouldUnlockSettings = false;
3942 if (settings == nullptr) {
3943 shouldUnlockSettings = true;
3944 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3945 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003946 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3947 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003948 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003949 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3950 isStillCapture = true;
3951 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3952 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003953
Emilian Peevaf8416e2021-02-04 17:52:43 -08003954 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003955 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003956 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3957 isZslCapture = true;
3958 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003959 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003960 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003961 res = parent->registerInFlight(halRequest->frame_number,
3962 totalNumBuffers, captureRequest->mResultExtras,
3963 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003964 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003965 expectedDurationInfo.minDuration,
3966 expectedDurationInfo.maxDuration,
3967 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003968 requestedPhysicalCameras, isStillCapture, isZslCapture,
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00003969 captureRequest->mRotateAndCropAuto, captureRequest->mAutoframingAuto,
3970 mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003971 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003972 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003973 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3974 ", burstId = %" PRId32 ".",
3975 __FUNCTION__,
3976 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3977 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003978
3979 if (shouldUnlockSettings) {
3980 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3981 }
3982
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003983 if (res != OK) {
3984 SET_ERR("RequestThread: Unable to register new in-flight request:"
3985 " %s (%d)", strerror(-res), res);
3986 return INVALID_OPERATION;
3987 }
3988 }
3989
3990 return OK;
3991}
3992
Igor Murashkin1e479c02013-09-06 16:55:14 -07003993CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003994 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003995 Mutex::Autolock al(mLatestRequestMutex);
3996
3997 ALOGV("RequestThread::%s", __FUNCTION__);
3998
3999 return mLatestRequest;
4000}
4001
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004002bool Camera3Device::RequestThread::isStreamPending(
4003 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004004 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004005 Mutex::Autolock l(mRequestLock);
4006
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004007 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004008 if (!nextRequest.submitted) {
4009 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4010 if (stream == s) return true;
4011 }
4012 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004013 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004014 }
4015
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004016 for (const auto& request : mRequestQueue) {
4017 for (const auto& s : request->mOutputStreams) {
4018 if (stream == s) return true;
4019 }
4020 if (stream == request->mInputStream) return true;
4021 }
4022
4023 for (const auto& request : mRepeatingRequests) {
4024 for (const auto& s : request->mOutputStreams) {
4025 if (stream == s) return true;
4026 }
4027 if (stream == request->mInputStream) return true;
4028 }
4029
4030 return false;
4031}
Jianing Weicb0652e2014-03-12 18:29:36 -07004032
Emilian Peev40ead602017-09-26 15:46:36 +01004033bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4034 ATRACE_CALL();
4035 Mutex::Autolock l(mRequestLock);
4036
4037 for (const auto& nextRequest : mNextRequests) {
4038 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4039 if (s.first == streamId) {
4040 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4041 if (it != s.second.end()) {
4042 return true;
4043 }
4044 }
4045 }
4046 }
4047
4048 for (const auto& request : mRequestQueue) {
4049 for (const auto& s : request->mOutputSurfaces) {
4050 if (s.first == streamId) {
4051 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4052 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004053 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004054 }
4055 }
4056 }
4057 }
4058
4059 for (const auto& request : mRepeatingRequests) {
4060 for (const auto& s : request->mOutputSurfaces) {
4061 if (s.first == streamId) {
4062 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4063 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004064 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004065 }
4066 }
4067 }
4068 }
4069
4070 return false;
4071}
4072
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004073void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4074 if (!mUseHalBufManager) {
4075 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4076 return;
4077 }
4078
4079 Mutex::Autolock pl(mPauseLock);
4080 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004081 mInterface->signalPipelineDrain(streamIds);
4082 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004083 }
4084 // If request thread is still busy, wait until paused then notify HAL
4085 mNotifyPipelineDrain = true;
4086 mStreamIdsToBeDrained = streamIds;
4087}
4088
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004089void Camera3Device::RequestThread::resetPipelineDrain() {
4090 Mutex::Autolock pl(mPauseLock);
4091 mNotifyPipelineDrain = false;
4092 mStreamIdsToBeDrained.clear();
4093}
4094
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004095void Camera3Device::RequestThread::clearPreviousRequest() {
4096 Mutex::Autolock l(mRequestLock);
4097 mPrevRequest.clear();
4098}
4099
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004100status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4101 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4102 ATRACE_CALL();
4103 Mutex::Autolock l(mTriggerMutex);
4104 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4105 return BAD_VALUE;
4106 }
4107 mRotateAndCropOverride = rotateAndCropValue;
4108 return OK;
4109}
4110
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004111status_t Camera3Device::RequestThread::setAutoframingAutoBehaviour(
4112 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
4113 ATRACE_CALL();
4114 Mutex::Autolock l(mTriggerMutex);
4115 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
4116 return BAD_VALUE;
4117 }
4118 mAutoframingOverride = autoframingValue;
4119 return OK;
4120}
4121
Emilian Peeve23f1d92021-09-20 14:56:01 -07004122status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4123 ATRACE_CALL();
4124 Mutex::Autolock l(mTriggerMutex);
4125 mComposerOutput = composerSurfacePresent;
4126 return OK;
4127}
4128
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004129status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004130 ATRACE_CALL();
4131 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004132 if (muteMode != mCameraMute) {
4133 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004134 mCameraMuteChanged = true;
4135 }
4136 return OK;
4137}
4138
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004139nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004140 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004141 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004142 return mExpectedInflightDuration > kMinInflightDuration ?
4143 mExpectedInflightDuration : kMinInflightDuration;
4144}
4145
Emilian Peevaebbe412018-01-15 13:53:24 +00004146void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004147 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004148 if ((request == nullptr) || (halRequest == nullptr)) {
4149 ALOGE("%s: Invalid request!", __FUNCTION__);
4150 return;
4151 }
4152
4153 if (halRequest->num_physcam_settings > 0) {
4154 if (halRequest->physcam_id != nullptr) {
4155 delete [] halRequest->physcam_id;
4156 halRequest->physcam_id = nullptr;
4157 }
4158 if (halRequest->physcam_settings != nullptr) {
4159 auto it = ++(request->mSettingsList.begin());
4160 size_t i = 0;
4161 for (; it != request->mSettingsList.end(); it++, i++) {
4162 it->metadata.unlock(halRequest->physcam_settings[i]);
4163 }
4164 delete [] halRequest->physcam_settings;
4165 halRequest->physcam_settings = nullptr;
4166 }
4167 }
4168}
4169
Ravneetaeb20dc2022-03-30 05:33:03 +00004170status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4171 Mutex::Autolock il(mInterfaceLock);
4172 Mutex::Autolock l(mLock);
4173
4174 if (mCameraServiceWatchdog != NULL) {
4175 mCameraServiceWatchdog->setEnabled(enabled);
4176 }
4177
4178 return OK;
4179}
4180
Shuzhen Wang16610a62022-12-15 22:38:07 -08004181void Camera3Device::setStreamUseCaseOverrides(
4182 const std::vector<int64_t>& useCaseOverrides) {
4183 Mutex::Autolock il(mInterfaceLock);
4184 Mutex::Autolock l(mLock);
4185 mStreamUseCaseOverrides = useCaseOverrides;
4186}
4187
4188void Camera3Device::clearStreamUseCaseOverrides() {
4189 Mutex::Autolock il(mInterfaceLock);
4190 Mutex::Autolock l(mLock);
4191 mStreamUseCaseOverrides.clear();
4192}
4193
Shuzhen Wang03fe6232023-02-05 12:41:15 -08004194bool Camera3Device::hasDeviceError() {
4195 Mutex::Autolock il(mInterfaceLock);
4196 Mutex::Autolock l(mLock);
4197 return mStatus == STATUS_ERROR;
4198}
4199
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004200void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4201 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004202 return;
4203 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004204
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004205 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004206 // Skip the ones that have been submitted successfully.
4207 if (nextRequest.submitted) {
4208 continue;
4209 }
4210
4211 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004212 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4213 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004214
4215 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004216 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004217 }
4218
Emilian Peevaebbe412018-01-15 13:53:24 +00004219 cleanupPhysicalSettings(captureRequest, halRequest);
4220
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004221 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004222 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004223 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4224 }
4225
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004226 // No output buffer can be returned when using HAL buffer manager
4227 if (!mUseHalBufManager) {
4228 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4229 //Buffers that failed processing could still have
4230 //valid acquire fence.
4231 int acquireFence = (*outputBuffers)[i].acquire_fence;
4232 if (0 <= acquireFence) {
4233 close(acquireFence);
4234 outputBuffers->editItemAt(i).acquire_fence = -1;
4235 }
Emilian Peevf4816702020-04-03 15:44:51 -07004236 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004237 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4238 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004239 /*timestampIncreasing*/true, std::vector<size_t> (),
4240 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004241 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004242 }
4243
4244 if (sendRequestError) {
4245 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004246 sp<NotificationListener> listener = mListener.promote();
4247 if (listener != NULL) {
4248 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004249 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004250 captureRequest->mResultExtras);
4251 }
4252 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004253
4254 // Remove yet-to-be submitted inflight request from inflightMap
4255 {
4256 sp<Camera3Device> parent = mParent.promote();
4257 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004258 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004259 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4260 if (idx >= 0) {
4261 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4262 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4263 parent->removeInFlightMapEntryLocked(idx);
4264 }
4265 }
4266 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004267 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004268
4269 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004270 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004271}
4272
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004273void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004274 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004275 // Optimized a bit for the simple steady-state case (single repeating
4276 // request), to avoid putting that request in the queue temporarily.
4277 Mutex::Autolock l(mRequestLock);
4278
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004279 assert(mNextRequests.empty());
4280
4281 NextRequest nextRequest;
4282 nextRequest.captureRequest = waitForNextRequestLocked();
4283 if (nextRequest.captureRequest == nullptr) {
4284 return;
4285 }
4286
Emilian Peevf4816702020-04-03 15:44:51 -07004287 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004288 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004289 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004290
4291 // Wait for additional requests
4292 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4293
4294 for (size_t i = 1; i < batchSize; i++) {
4295 NextRequest additionalRequest;
4296 additionalRequest.captureRequest = waitForNextRequestLocked();
4297 if (additionalRequest.captureRequest == nullptr) {
4298 break;
4299 }
4300
Emilian Peevf4816702020-04-03 15:44:51 -07004301 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004302 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004303 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004304 }
4305
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004306 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004307 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004308 mNextRequests.size(), batchSize);
4309 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004310 }
4311
4312 return;
4313}
4314
Jayant Chowdharya93f3462022-11-01 23:32:45 +00004315void Camera3Device::RequestThread::setRequestClearing() {
4316 Mutex::Autolock l(mRequestLock);
4317 mRequestClearing = true;
4318}
4319
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004320sp<Camera3Device::CaptureRequest>
4321 Camera3Device::RequestThread::waitForNextRequestLocked() {
4322 status_t res;
4323 sp<CaptureRequest> nextRequest;
4324
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004325 while (mRequestQueue.empty()) {
4326 if (!mRepeatingRequests.empty()) {
4327 // Always atomically enqueue all requests in a repeating request
4328 // list. Guarantees a complete in-sequence set of captures to
4329 // application.
4330 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004331 if (mFirstRepeating) {
4332 mFirstRepeating = false;
4333 } else {
4334 for (auto& request : requests) {
4335 // For repeating requests, override timestamp request using
4336 // the time a request is inserted into the request queue,
4337 // because the original repeating request will have an old
4338 // fixed timestamp.
4339 request->mRequestTimeNs = systemTime();
4340 }
4341 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004342 RequestList::const_iterator firstRequest =
4343 requests.begin();
4344 nextRequest = *firstRequest;
4345 mRequestQueue.insert(mRequestQueue.end(),
4346 ++firstRequest,
4347 requests.end());
4348 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004349
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004350 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004351
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004352 break;
4353 }
4354
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004355 if (!mRequestClearing) {
4356 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4357 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004358
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004359 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4360 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004361 Mutex::Autolock pl(mPauseLock);
4362 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004363 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004364 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004365 if (mNotifyPipelineDrain) {
4366 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4367 mNotifyPipelineDrain = false;
4368 mStreamIdsToBeDrained.clear();
4369 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004370 // Let the tracker know
4371 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4372 if (statusTracker != 0) {
4373 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4374 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004375 sp<Camera3Device> parent = mParent.promote();
4376 if (parent != nullptr) {
4377 parent->mRequestBufferSM.onRequestThreadPaused();
4378 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004379 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004380 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004381 // Stop waiting for now and let thread management happen
4382 return NULL;
4383 }
4384 }
4385
4386 if (nextRequest == NULL) {
4387 // Don't have a repeating request already in hand, so queue
4388 // must have an entry now.
4389 RequestList::iterator firstRequest =
4390 mRequestQueue.begin();
4391 nextRequest = *firstRequest;
4392 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004393 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4394 sp<NotificationListener> listener = mListener.promote();
4395 if (listener != NULL) {
4396 listener->notifyRequestQueueEmpty();
4397 }
4398 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004399 }
4400
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004401 // In case we've been unpaused by setPaused clearing mDoPause, need to
4402 // update internal pause state (capture/setRepeatingRequest unpause
4403 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004404 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004405 if (mPaused) {
4406 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4407 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4408 if (statusTracker != 0) {
4409 statusTracker->markComponentActive(mStatusId);
4410 }
4411 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004412 mPaused = false;
4413
4414 // Check if we've reconfigured since last time, and reset the preview
4415 // request if so. Can't use 'NULL request == repeat' across configure calls.
4416 if (mReconfigured) {
4417 mPrevRequest.clear();
4418 mReconfigured = false;
4419 }
4420
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004421 if (nextRequest != NULL) {
4422 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004423 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4424 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004425
4426 // Since RequestThread::clear() removes buffers from the input stream,
4427 // get the right buffer here before unlocking mRequestLock
4428 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004429 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4430 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004431 if (res != OK) {
4432 // Can't get input buffer from gralloc queue - this could be due to
4433 // disconnected queue or other producer misbehavior, so not a fatal
4434 // error
4435 ALOGE("%s: Can't get input buffer, skipping request:"
4436 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004437
4438 sp<NotificationListener> listener = mListener.promote();
4439 if (listener != NULL) {
4440 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004441 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004442 nextRequest->mResultExtras);
4443 }
4444 return NULL;
4445 }
4446 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004447 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004448
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004449 return nextRequest;
4450}
4451
4452bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004453 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004454 status_t res;
4455 Mutex::Autolock l(mPauseLock);
4456 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457 if (mPaused == false) {
4458 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004459 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004460 if (mNotifyPipelineDrain) {
4461 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4462 mNotifyPipelineDrain = false;
4463 mStreamIdsToBeDrained.clear();
4464 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004465 // Let the tracker know
4466 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4467 if (statusTracker != 0) {
4468 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4469 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004470 sp<Camera3Device> parent = mParent.promote();
4471 if (parent != nullptr) {
4472 parent->mRequestBufferSM.onRequestThreadPaused();
4473 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004474 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004476 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004477 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004478 return true;
4479 }
4480 }
4481 // We don't set mPaused to false here, because waitForNextRequest needs
4482 // to further manage the paused state in case of starvation.
4483 return false;
4484}
4485
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004486void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004487 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004488 // With work to do, mark thread as unpaused.
4489 // If paused by request (setPaused), don't resume, to avoid
4490 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004491 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004492 Mutex::Autolock p(mPauseLock);
4493 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004494 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4495 if (mPaused) {
4496 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4497 if (statusTracker != 0) {
4498 statusTracker->markComponentActive(mStatusId);
4499 }
4500 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004501 mPaused = false;
4502 }
4503}
4504
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004505void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4506 sp<Camera3Device> parent = mParent.promote();
4507 if (parent != NULL) {
4508 va_list args;
4509 va_start(args, fmt);
4510
4511 parent->setErrorStateV(fmt, args);
4512
4513 va_end(args);
4514 }
4515}
4516
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004517status_t Camera3Device::RequestThread::insertTriggers(
4518 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004519 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004520 Mutex::Autolock al(mTriggerMutex);
4521
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004522 sp<Camera3Device> parent = mParent.promote();
4523 if (parent == NULL) {
4524 CLOGE("RequestThread: Parent is gone");
4525 return DEAD_OBJECT;
4526 }
4527
Emilian Peevaebbe412018-01-15 13:53:24 +00004528 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004529 size_t count = mTriggerMap.size();
4530
4531 for (size_t i = 0; i < count; ++i) {
4532 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004533 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004534
4535 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4536 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4537 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004538 if (isAeTrigger) {
4539 request->mResultExtras.precaptureTriggerId = triggerId;
4540 mCurrentPreCaptureTriggerId = triggerId;
4541 } else {
4542 request->mResultExtras.afTriggerId = triggerId;
4543 mCurrentAfTriggerId = triggerId;
4544 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004545 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004546 }
4547
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004548 camera_metadata_entry entry = metadata.find(tag);
4549
4550 if (entry.count > 0) {
4551 /**
4552 * Already has an entry for this trigger in the request.
4553 * Rewrite it with our requested trigger value.
4554 */
4555 RequestTrigger oldTrigger = trigger;
4556
4557 oldTrigger.entryValue = entry.data.u8[0];
4558
4559 mTriggerReplacedMap.add(tag, oldTrigger);
4560 } else {
4561 /**
4562 * More typical, no trigger entry, so we just add it
4563 */
4564 mTriggerRemovedMap.add(tag, trigger);
4565 }
4566
4567 status_t res;
4568
4569 switch (trigger.getTagType()) {
4570 case TYPE_BYTE: {
4571 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4572 res = metadata.update(tag,
4573 &entryValue,
4574 /*count*/1);
4575 break;
4576 }
4577 case TYPE_INT32:
4578 res = metadata.update(tag,
4579 &trigger.entryValue,
4580 /*count*/1);
4581 break;
4582 default:
4583 ALOGE("%s: Type not supported: 0x%x",
4584 __FUNCTION__,
4585 trigger.getTagType());
4586 return INVALID_OPERATION;
4587 }
4588
4589 if (res != OK) {
4590 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4591 ", value %d", __FUNCTION__, trigger.getTagName(),
4592 trigger.entryValue);
4593 return res;
4594 }
4595
4596 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4597 trigger.getTagName(),
4598 trigger.entryValue);
4599 }
4600
4601 mTriggerMap.clear();
4602
4603 return count;
4604}
4605
4606status_t Camera3Device::RequestThread::removeTriggers(
4607 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004608 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004609 Mutex::Autolock al(mTriggerMutex);
4610
Emilian Peevaebbe412018-01-15 13:53:24 +00004611 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004612
4613 /**
4614 * Replace all old entries with their old values.
4615 */
4616 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4617 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4618
4619 status_t res;
4620
4621 uint32_t tag = trigger.metadataTag;
4622 switch (trigger.getTagType()) {
4623 case TYPE_BYTE: {
4624 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4625 res = metadata.update(tag,
4626 &entryValue,
4627 /*count*/1);
4628 break;
4629 }
4630 case TYPE_INT32:
4631 res = metadata.update(tag,
4632 &trigger.entryValue,
4633 /*count*/1);
4634 break;
4635 default:
4636 ALOGE("%s: Type not supported: 0x%x",
4637 __FUNCTION__,
4638 trigger.getTagType());
4639 return INVALID_OPERATION;
4640 }
4641
4642 if (res != OK) {
4643 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4644 ", trigger value %d", __FUNCTION__,
4645 trigger.getTagName(), trigger.entryValue);
4646 return res;
4647 }
4648 }
4649 mTriggerReplacedMap.clear();
4650
4651 /**
4652 * Remove all new entries.
4653 */
4654 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4655 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4656 status_t res = metadata.erase(trigger.metadataTag);
4657
4658 if (res != OK) {
4659 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4660 ", trigger value %d", __FUNCTION__,
4661 trigger.getTagName(), trigger.entryValue);
4662 return res;
4663 }
4664 }
4665 mTriggerRemovedMap.clear();
4666
4667 return OK;
4668}
4669
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004670status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004671 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004672 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004673 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004674 status_t res;
4675
Emilian Peevaebbe412018-01-15 13:53:24 +00004676 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004677
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004678 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004679 // exists
4680 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4681 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4682 if (afTrigger.count > 0 &&
4683 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4684 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004685 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004686 if (res != OK) return res;
4687 }
4688
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004689 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004690 // if none already exists
4691 camera_metadata_entry pcTrigger =
4692 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4693 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4694 if (pcTrigger.count > 0 &&
4695 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4696 pcId.count == 0) {
4697 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004698 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004699 if (res != OK) return res;
4700 }
4701
4702 return OK;
4703}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004704
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004705bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4706 const sp<CaptureRequest> &request) {
4707 ATRACE_CALL();
4708
Austin Borger18b30a72022-10-27 12:20:29 -07004709 if (mOverrideToPortrait) {
4710 Mutex::Autolock l(mTriggerMutex);
4711 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4712 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4713 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4714 &rotateAndCrop_u8, 1);
4715 return true;
4716 }
4717
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004718 if (request->mRotateAndCropAuto) {
4719 Mutex::Autolock l(mTriggerMutex);
4720 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4721
4722 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4723 if (rotateAndCropEntry.count > 0) {
4724 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4725 return false;
4726 } else {
4727 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4728 return true;
4729 }
4730 } else {
4731 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4732 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4733 &rotateAndCrop_u8, 1);
4734 return true;
4735 }
4736 }
4737 return false;
4738}
4739
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004740bool Camera3Device::RequestThread::overrideAutoframing(const sp<CaptureRequest> &request) {
4741 ATRACE_CALL();
4742
4743 if (request->mAutoframingAuto) {
4744 Mutex::Autolock l(mTriggerMutex);
4745 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4746
4747 auto autoframingEntry = metadata.find(ANDROID_CONTROL_AUTOFRAMING);
4748 if (autoframingEntry.count > 0) {
4749 if (autoframingEntry.data.u8[0] == mAutoframingOverride) {
4750 return false;
4751 } else {
4752 autoframingEntry.data.u8[0] = mAutoframingOverride;
4753 return true;
4754 }
4755 } else {
4756 uint8_t autoframing_u8 = mAutoframingOverride;
4757 metadata.update(ANDROID_CONTROL_AUTOFRAMING,
4758 &autoframing_u8, 1);
4759 return true;
4760 }
4761 }
4762 return false;
4763}
4764
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004765bool Camera3Device::RequestThread::overrideTestPattern(
4766 const sp<CaptureRequest> &request) {
4767 ATRACE_CALL();
4768
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004769 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004770
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004771 Mutex::Autolock l(mTriggerMutex);
4772
4773 bool changed = false;
4774
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004775 // For a multi-camera, the physical cameras support the same set of
4776 // test pattern modes as the logical camera.
4777 for (auto& settings : request->mSettingsList) {
4778 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004779
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004780 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4781 int32_t testPatternData[4] = {
4782 settings.mOriginalTestPatternData[0],
4783 settings.mOriginalTestPatternData[1],
4784 settings.mOriginalTestPatternData[2],
4785 settings.mOriginalTestPatternData[3]
4786 };
4787 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4788 testPatternMode = mCameraMute;
4789 testPatternData[0] = 0;
4790 testPatternData[1] = 0;
4791 testPatternData[2] = 0;
4792 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004793 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004794
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004795 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4796 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4797 if (testPatternEntry.count > 0) {
4798 if (testPatternEntry.data.i32[0] != testPatternMode) {
4799 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004800 changed = true;
4801 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004802 } else if (supportTestPatternModeKey) {
4803 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4804 &testPatternMode, 1);
4805 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004806 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004807
4808 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4809 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4810 if (testPatternColor.count >= 4) {
4811 for (size_t i = 0; i < 4; i++) {
4812 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4813 testPatternColor.data.i32[i] = testPatternData[i];
4814 changed = true;
4815 }
4816 }
4817 } else if (supportTestPatternDataKey) {
4818 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4819 testPatternData, 4);
4820 changed = true;
4821 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004822 }
4823
4824 return changed;
4825}
4826
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004827status_t Camera3Device::RequestThread::setHalInterface(
4828 sp<HalInterface> newHalInterface) {
4829 if (newHalInterface.get() == nullptr) {
4830 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4831 return DEAD_OBJECT;
4832 }
4833
4834 mInterface = newHalInterface;
4835
4836 return OK;
4837}
4838
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004839/**
4840 * PreparerThread inner class methods
4841 */
4842
4843Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004844 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004845 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004846}
4847
4848Camera3Device::PreparerThread::~PreparerThread() {
4849 Thread::requestExitAndWait();
4850 if (mCurrentStream != nullptr) {
4851 mCurrentStream->cancelPrepare();
4852 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4853 mCurrentStream.clear();
4854 }
4855 clear();
4856}
4857
Ruben Brunkc78ac262015-08-13 17:58:46 -07004858status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004859 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004860 status_t res;
4861
4862 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004863 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004864
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004865 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004866 if (res == OK) {
4867 // No preparation needed, fire listener right off
4868 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004869 if (listener != NULL) {
4870 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 }
4872 return OK;
4873 } else if (res != NOT_ENOUGH_DATA) {
4874 return res;
4875 }
4876
4877 // Need to prepare, start up thread if necessary
4878 if (!mActive) {
4879 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4880 // isn't running
4881 Thread::requestExitAndWait();
4882 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4883 if (res != OK) {
4884 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004885 if (listener != NULL) {
4886 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004887 }
4888 return res;
4889 }
4890 mCancelNow = false;
4891 mActive = true;
4892 ALOGV("%s: Preparer stream started", __FUNCTION__);
4893 }
4894
4895 // queue up the work
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004896 mPendingStreams.push_back(
4897 std::tuple<int, sp<camera3::Camera3StreamInterface>>(maxCount, stream));
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004898 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4899
4900 return OK;
4901}
4902
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004903void Camera3Device::PreparerThread::pause() {
4904 ATRACE_CALL();
4905
4906 Mutex::Autolock l(mLock);
4907
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004908 std::list<std::tuple<int, sp<camera3::Camera3StreamInterface>>> pendingStreams;
4909 pendingStreams.insert(pendingStreams.begin(), mPendingStreams.begin(), mPendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004910 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4911 int currentMaxCount = mCurrentMaxCount;
4912 mPendingStreams.clear();
4913 mCancelNow = true;
4914 while (mActive) {
4915 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4916 if (res == TIMED_OUT) {
4917 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4918 return;
4919 } else if (res != OK) {
4920 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4921 return;
4922 }
4923 }
4924
4925 //Check whether the prepare thread was able to complete the current
4926 //stream. In case work is still pending emplace it along with the rest
4927 //of the streams in the pending list.
4928 if (currentStream != nullptr) {
4929 if (!mCurrentPrepareComplete) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004930 pendingStreams.push_back(std::tuple(currentMaxCount, currentStream));
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004931 }
4932 }
4933
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004934 mPendingStreams.insert(mPendingStreams.begin(), pendingStreams.begin(), pendingStreams.end());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004935 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004936 std::get<1>(it)->cancelPrepare();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004937 }
4938}
4939
4940status_t Camera3Device::PreparerThread::resume() {
4941 ATRACE_CALL();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004942 ALOGV("%s: PreparerThread", __FUNCTION__);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004943 status_t res;
4944
4945 Mutex::Autolock l(mLock);
4946 sp<NotificationListener> listener = mListener.promote();
4947
4948 if (mActive) {
4949 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4950 return NO_INIT;
4951 }
4952
4953 auto it = mPendingStreams.begin();
4954 for (; it != mPendingStreams.end();) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004955 res = std::get<1>(*it)->startPrepare(std::get<0>(*it), true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004956 if (res == OK) {
4957 if (listener != NULL) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004958 listener->notifyPrepared(std::get<1>(*it)->getId());
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004959 }
4960 it = mPendingStreams.erase(it);
4961 } else if (res != NOT_ENOUGH_DATA) {
4962 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4963 res, strerror(-res));
4964 it = mPendingStreams.erase(it);
4965 } else {
4966 it++;
4967 }
4968 }
4969
4970 if (mPendingStreams.empty()) {
4971 return OK;
4972 }
4973
4974 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4975 if (res != OK) {
4976 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4977 __FUNCTION__, res, strerror(-res));
4978 return res;
4979 }
4980 mCancelNow = false;
4981 mActive = true;
4982 ALOGV("%s: Preparer stream started", __FUNCTION__);
4983
4984 return OK;
4985}
4986
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004987status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004988 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004989 Mutex::Autolock l(mLock);
4990
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004991 for (const auto& it : mPendingStreams) {
Jayant Chowdhary57184d52023-02-14 20:54:39 +00004992 std::get<1>(it)->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004993 }
4994 mPendingStreams.clear();
4995 mCancelNow = true;
4996
4997 return OK;
4998}
4999
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005000void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005001 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005002 Mutex::Autolock l(mLock);
5003 mListener = listener;
5004}
5005
5006bool Camera3Device::PreparerThread::threadLoop() {
5007 status_t res;
5008 {
5009 Mutex::Autolock l(mLock);
5010 if (mCurrentStream == nullptr) {
5011 // End thread if done with work
5012 if (mPendingStreams.empty()) {
5013 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5014 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5015 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5016 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005017 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005018 return false;
5019 }
5020
5021 // Get next stream to prepare
5022 auto it = mPendingStreams.begin();
Jayant Chowdhary57184d52023-02-14 20:54:39 +00005023 mCurrentMaxCount = std::get<0>(*it);
5024 mCurrentStream = std::get<1>(*it);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005025 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005026 mPendingStreams.erase(it);
5027 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5028 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5029 } else if (mCancelNow) {
5030 mCurrentStream->cancelPrepare();
5031 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5032 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5033 mCurrentStream.clear();
5034 mCancelNow = false;
5035 return true;
5036 }
5037 }
5038
5039 res = mCurrentStream->prepareNextBuffer();
5040 if (res == NOT_ENOUGH_DATA) return true;
5041 if (res != OK) {
5042 // Something bad happened; try to recover by cancelling prepare and
5043 // signalling listener anyway
5044 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5045 mCurrentStream->getId(), res, strerror(-res));
5046 mCurrentStream->cancelPrepare();
5047 }
5048
5049 // This stream has finished, notify listener
5050 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005051 sp<NotificationListener> listener = mListener.promote();
5052 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005053 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5054 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005055 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005056 }
5057
5058 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5059 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005060 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005061
5062 return true;
5063}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005064
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005065status_t Camera3Device::RequestBufferStateMachine::initialize(
5066 sp<camera3::StatusTracker> statusTracker) {
5067 if (statusTracker == nullptr) {
5068 ALOGE("%s: statusTracker is null", __FUNCTION__);
5069 return BAD_VALUE;
5070 }
5071
5072 std::lock_guard<std::mutex> lock(mLock);
5073 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005074 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005075 return OK;
5076}
5077
5078bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5079 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005080 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005081 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005082 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005083 return true;
5084 }
5085 return false;
5086}
5087
5088void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5089 std::lock_guard<std::mutex> lock(mLock);
5090 if (!mRequestBufferOngoing) {
5091 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5092 return;
5093 }
5094 mRequestBufferOngoing = false;
5095 if (mStatus == RB_STATUS_PENDING_STOP) {
5096 checkSwitchToStopLocked();
5097 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005098 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005099}
5100
5101void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5102 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005103 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005104 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005105 return;
5106}
5107
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005108void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005109 std::lock_guard<std::mutex> lock(mLock);
5110 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005111 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5112 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005113 mInflightMapEmpty = false;
5114 if (mStatus == RB_STATUS_STOPPED) {
5115 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005116 }
5117 return;
5118}
5119
5120void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5121 std::lock_guard<std::mutex> lock(mLock);
5122 mRequestThreadPaused = true;
5123 if (mStatus == RB_STATUS_PENDING_STOP) {
5124 checkSwitchToStopLocked();
5125 }
5126 return;
5127}
5128
5129void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5130 std::lock_guard<std::mutex> lock(mLock);
5131 mInflightMapEmpty = true;
5132 if (mStatus == RB_STATUS_PENDING_STOP) {
5133 checkSwitchToStopLocked();
5134 }
5135 return;
5136}
5137
5138void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5139 std::lock_guard<std::mutex> lock(mLock);
5140 if (!checkSwitchToStopLocked()) {
5141 mStatus = RB_STATUS_PENDING_STOP;
5142 }
5143 return;
5144}
5145
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005146bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5147 std::lock_guard<std::mutex> lock(mLock);
5148 if (mRequestBufferOngoing) {
5149 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5150 __FUNCTION__);
5151 return false;
5152 }
5153 mSwitchedToOffline = true;
5154 mInflightMapEmpty = true;
5155 mRequestThreadPaused = true;
5156 mStatus = RB_STATUS_STOPPED;
5157 return true;
5158}
5159
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005160void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5161 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5162 if (statusTracker != nullptr) {
5163 if (active) {
5164 statusTracker->markComponentActive(mRequestBufferStatusId);
5165 } else {
5166 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5167 }
5168 }
5169}
5170
5171bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5172 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5173 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005174 return true;
5175 }
5176 return false;
5177}
5178
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005179bool Camera3Device::startRequestBuffer() {
5180 return mRequestBufferSM.startRequestBuffer();
5181}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005182
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005183void Camera3Device::endRequestBuffer() {
5184 mRequestBufferSM.endRequestBuffer();
5185}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005186
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005187nsecs_t Camera3Device::getWaitDuration() {
5188 return kBaseGetBufferWait + getExpectedInFlightDuration();
5189}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005190
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005191void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5192 mInterface->getInflightBufferKeys(out);
5193}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005194
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005195void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5196 mInterface->getInflightRequestBufferKeys(out);
5197}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005198
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005199std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5200 std::vector<sp<Camera3StreamInterface>> ret;
5201 bool hasInputStream = mInputStream != nullptr;
5202 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5203 if (hasInputStream) {
5204 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005205 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005206 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5207 ret.push_back(mOutputStreams[i]);
5208 }
5209 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5210 ret.push_back(mDeletedStreams[i]);
5211 }
5212 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005213}
5214
Emilian Peevcc0b7952020-01-07 13:54:47 -08005215void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5216 ATRACE_CALL();
5217
5218 if (offlineStreamIds == nullptr) {
5219 return;
5220 }
5221
5222 Mutex::Autolock il(mInterfaceLock);
5223
5224 auto streamIds = mOutputStreams.getStreamIds();
5225 bool hasInputStream = mInputStream != nullptr;
5226 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5227 offlineStreamIds->push_back(mInputStream->getId());
5228 }
5229
5230 for (const auto & streamId : streamIds) {
5231 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5232 // Streams that use the camera buffer manager are currently not supported in
5233 // offline mode
5234 if (stream->getOfflineProcessingSupport() &&
5235 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5236 offlineStreamIds->push_back(streamId);
5237 }
5238 }
5239}
5240
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005241status_t Camera3Device::setRotateAndCropAutoBehavior(
5242 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5243 ATRACE_CALL();
5244 Mutex::Autolock il(mInterfaceLock);
5245 Mutex::Autolock l(mLock);
5246 if (mRequestThread == nullptr) {
5247 return INVALID_OPERATION;
5248 }
5249 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5250}
5251
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005252status_t Camera3Device::setAutoframingAutoBehavior(
5253 camera_metadata_enum_android_control_autoframing_t autoframingValue) {
5254 ATRACE_CALL();
5255 Mutex::Autolock il(mInterfaceLock);
5256 Mutex::Autolock l(mLock);
5257 if (mRequestThread == nullptr) {
5258 return INVALID_OPERATION;
5259 }
5260 return mRequestThread->setAutoframingAutoBehaviour(autoframingValue);
5261}
5262
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005263bool Camera3Device::supportsCameraMute() {
5264 Mutex::Autolock il(mInterfaceLock);
5265 Mutex::Autolock l(mLock);
5266
5267 return mSupportCameraMute;
5268}
5269
5270status_t Camera3Device::setCameraMute(bool enabled) {
5271 ATRACE_CALL();
5272 Mutex::Autolock il(mInterfaceLock);
5273 Mutex::Autolock l(mLock);
5274
5275 if (mRequestThread == nullptr || !mSupportCameraMute) {
5276 return INVALID_OPERATION;
5277 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005278 int32_t muteMode =
5279 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5280 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5281 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5282 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005283}
5284
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005285status_t Camera3Device::injectCamera(const String8& injectedCamId,
5286 sp<CameraProviderManager> manager) {
5287 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5288 ATRACE_CALL();
5289 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005290 // When the camera device is active, injectCamera() and stopInjection() will call
5291 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5292 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5293 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5294 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5295 // waitUntilStateThenRelock().
5296 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005297
5298 status_t res = NO_ERROR;
5299 if (mInjectionMethods->isInjecting()) {
5300 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5301 return OK;
5302 } else {
5303 res = mInjectionMethods->stopInjection();
5304 if (res != OK) {
5305 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5306 __FUNCTION__, res);
5307 return res;
5308 }
5309 }
5310 }
5311
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005312 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005313 if (res != OK) {
5314 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5315 __FUNCTION__, res);
5316 return res;
5317 }
5318
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005319 // When the second display of android is cast to the remote device, and the opened camera is
5320 // also cast to the second display, in this case, because the camera has configured the streams
5321 // at this time, we can directly call injectCamera() to replace the internal camera with
5322 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005323 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5324 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5325
5326 camera3::camera_stream_configuration injectionConfig;
5327 std::vector<uint32_t> injectionBufferSizes;
5328 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5329 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5330 || injectionBufferSizes.size() <= 0) {
5331 ALOGE("Failed to inject camera due to abandoned configuration! "
5332 "mOperatingMode: %d injectionConfig.num_streams: %d "
5333 "injectionBufferSizes.size(): %zu", mOperatingMode,
5334 injectionConfig.num_streams, injectionBufferSizes.size());
5335 return DEAD_OBJECT;
5336 }
5337
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005338 res = mInjectionMethods->injectCamera(
5339 injectionConfig, injectionBufferSizes);
5340 if (res != OK) {
5341 ALOGE("Can't finish inject camera process!");
5342 return res;
5343 }
5344 }
5345
5346 return OK;
5347}
5348
5349status_t Camera3Device::stopInjection() {
5350 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5351 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005352 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005353 return mInjectionMethods->stopInjection();
5354}
5355
Shuzhen Wang16610a62022-12-15 22:38:07 -08005356void Camera3Device::overrideStreamUseCaseLocked() {
5357 if (mStreamUseCaseOverrides.size() == 0) {
5358 return;
5359 }
5360
5361 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5362 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5363 // Refer to CameraService::printHelp for details.
5364 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5365 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5366 outputStreamsIndices[i] = i;
5367 }
5368
5369 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5370 [&](int a, int b) -> bool {
5371
5372 auto formatScore = [](int format) {
5373 switch (format) {
5374 case HAL_PIXEL_FORMAT_BLOB:
5375 return 4;
5376 case HAL_PIXEL_FORMAT_RAW16:
5377 case HAL_PIXEL_FORMAT_RAW10:
5378 case HAL_PIXEL_FORMAT_RAW12:
5379 return 3;
5380 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5381 return 2;
5382 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5383 return 1;
5384 default:
5385 return 0;
5386 }
5387 };
5388
5389 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5390 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5391 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5392 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5393 if (sizeA > sizeB ||
5394 (sizeA == sizeB && formatAScore >= formatBScore)) {
5395 return true;
5396 } else {
5397 return false;
5398 }
5399 });
5400
5401 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5402 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5403 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5404 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5405 }
5406}
5407
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005408}; // namespace android