blob: f2c74d0082e2d3a173a5ff414a3bb620f234f7d9 [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 Chowdharydbd1efb2023-02-07 16:14:48 -0800221 if (SessionConfigurationUtils::supportsUltraHighResolutionCapture(mDeviceInfo)) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700222 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 Chowdharydbd1efb2023-02-07 16:14:48 -0800409 /*supportsUltraHighResolutionCapture*/false);
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700410 // 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
Jing Mikec7f9b132023-03-12 11:12:04 +0800502status_t Camera3Device::dump(int fd, [[maybe_unused]] const Vector<String16> &args) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800503 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700504
505 // Try to lock, but continue in case of failure (to avoid blocking in
506 // deadlocks)
507 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
508 bool gotLock = tryLockSpinRightRound(mLock);
509
510 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
512 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700513 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800514 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
515 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700516
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800517 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700518
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800519 String16 templatesOption("-t");
520 int n = args.size();
521 for (int i = 0; i < n; i++) {
522 if (args[i] == templatesOption) {
523 dumpTemplates = true;
524 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000525 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700526 if (i + 1 < n) {
527 String8 monitorTags = String8(args[i + 1]);
528 if (monitorTags == "off") {
529 mTagMonitor.disableMonitoring();
530 } else {
531 mTagMonitor.parseTagsToMonitor(monitorTags);
532 }
533 } else {
534 mTagMonitor.disableMonitoring();
535 }
536 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800537 }
538
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800539 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800541 const char *status =
542 mStatus == STATUS_ERROR ? "ERROR" :
543 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700544 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
545 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800546 mStatus == STATUS_ACTIVE ? "ACTIVE" :
547 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700548
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800549 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700550 if (mStatus == STATUS_ERROR) {
551 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
552 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800553 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800554 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000555 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
556 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
557 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800558 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800559
560 if (mInputStream != NULL) {
561 write(fd, lines.string(), lines.size());
562 mInputStream->dump(fd, args);
563 } else {
564 lines.appendFormat(" No input stream.\n");
565 write(fd, lines.string(), lines.size());
566 }
567 for (size_t i = 0; i < mOutputStreams.size(); i++) {
568 mOutputStreams[i]->dump(fd,args);
569 }
570
Zhijun He431503c2016-03-07 17:30:16 -0800571 if (mBufferManager != NULL) {
572 lines = String8(" Camera3 Buffer Manager:\n");
573 write(fd, lines.string(), lines.size());
574 mBufferManager->dump(fd, args);
575 }
Zhijun He125684a2015-12-26 15:07:30 -0800576
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700577 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700578 if (mInFlightLock.try_lock()) {
579 if (mInFlightMap.size() == 0) {
580 lines.append(" None\n");
581 } else {
582 for (size_t i = 0; i < mInFlightMap.size(); i++) {
583 InFlightRequest r = mInFlightMap.valueAt(i);
584 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
585 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
586 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
587 r.numBuffersLeft);
588 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700589 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700590 mInFlightLock.unlock();
591 } else {
592 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700593 }
594 write(fd, lines.string(), lines.size());
595
Shuzhen Wang686f6442017-06-20 16:16:04 -0700596 if (mRequestThread != NULL) {
597 mRequestThread->dumpCaptureRequestLatency(fd,
598 " ProcessCaptureRequest latency histogram:");
599 }
600
Igor Murashkin1e479c02013-09-06 16:55:14 -0700601 {
602 lines = String8(" Last request sent:\n");
603 write(fd, lines.string(), lines.size());
604
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700605 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700606 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
607 }
608
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800609 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700610 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800611 "TEMPLATE_PREVIEW",
612 "TEMPLATE_STILL_CAPTURE",
613 "TEMPLATE_VIDEO_RECORD",
614 "TEMPLATE_VIDEO_SNAPSHOT",
615 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800616 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800617 };
618
Emilian Peevf4816702020-04-03 15:44:51 -0700619 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 camera_metadata_t *templateRequest = nullptr;
621 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700622 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800623 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800624 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800625 lines.append(" Not supported\n");
626 write(fd, lines.string(), lines.size());
627 } else {
628 write(fd, lines.string(), lines.size());
629 dump_indented_camera_metadata(templateRequest,
630 fd, /*verbosity*/2, /*indentation*/8);
631 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800633 }
634 }
635
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700636 mTagMonitor.dumpMonitoredMetadata(fd);
637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800639 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800642 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700644 if (gotLock) mLock.unlock();
645 if (gotInterfaceLock) mInterfaceLock.unlock();
646
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800647 return OK;
648}
649
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700650status_t Camera3Device::startWatchingTags(const String8 &tags) {
651 mTagMonitor.parseTagsToMonitor(tags);
652 return OK;
653}
654
655status_t Camera3Device::stopWatchingTags() {
656 mTagMonitor.disableMonitoring();
657 return OK;
658}
659
660status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
661 mTagMonitor.getLatestMonitoredTagEvents(out);
662 return OK;
663}
664
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800667 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
668 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700669 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800670 mStatus == STATUS_ERROR ?
671 "when in error state" : "before init");
672 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700673 if (physicalId.isEmpty()) {
674 return mDeviceInfo;
675 } else {
676 std::string id(physicalId.c_str());
677 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
678 return mPhysicalDeviceInfoMap.at(id);
679 } else {
680 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
681 return mDeviceInfo;
682 }
683 }
684}
685
686const CameraMetadata& Camera3Device::info() const {
687 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800688 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800689}
690
Jianing Wei90e59c92014-03-12 18:29:36 -0700691status_t Camera3Device::checkStatusOkToCaptureLocked() {
692 switch (mStatus) {
693 case STATUS_ERROR:
694 CLOGE("Device has encountered a serious error");
695 return INVALID_OPERATION;
696 case STATUS_UNINITIALIZED:
697 CLOGE("Device not initialized");
698 return INVALID_OPERATION;
699 case STATUS_UNCONFIGURED:
700 case STATUS_CONFIGURED:
701 case STATUS_ACTIVE:
702 // OK
703 break;
704 default:
705 SET_ERR_L("Unexpected status: %d", mStatus);
706 return INVALID_OPERATION;
707 }
708 return OK;
709}
710
711status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000712 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700713 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700714 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700715 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700716 if (requestList == NULL) {
717 CLOGE("requestList cannot be NULL.");
718 return BAD_VALUE;
719 }
720
Jianing Weicb0652e2014-03-12 18:29:36 -0700721 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000722 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700723 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
724 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
725 ++metadataIt, ++surfaceMapIt) {
726 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700727 if (newRequest == 0) {
728 CLOGE("Can't create capture request");
729 return BAD_VALUE;
730 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700731
Shuzhen Wang9d066012016-09-30 11:30:20 -0700732 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700733 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700734
Jianing Weicb0652e2014-03-12 18:29:36 -0700735 // Setup burst Id and request Id
736 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800737 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
738 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700739 CLOGE("RequestID does not exist in metadata");
740 return BAD_VALUE;
741 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800742 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700743
Jianing Wei90e59c92014-03-12 18:29:36 -0700744 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700745
746 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700747 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700748 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
749 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
750 return BAD_VALUE;
751 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700752
753 // Setup batch size if this is a high speed video recording request.
754 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
755 auto firstRequest = requestList->begin();
756 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
757 if (outputStream->isVideoStream()) {
758 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800759 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700760 break;
761 }
762 }
763 }
764
Jianing Wei90e59c92014-03-12 18:29:36 -0700765 return OK;
766}
767
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800768status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800769 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770
Emilian Peevaebbe412018-01-15 13:53:24 +0000771 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700772 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800775 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700776}
777
Emilian Peevaebbe412018-01-15 13:53:24 +0000778void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700779 std::list<const SurfaceMap>& surfaceMaps,
780 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000781 PhysicalCameraSettingsList requestList;
782 requestList.push_back({std::string(getId().string()), request});
783 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784
785 SurfaceMap surfaceMap;
786 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
787 // With no surface list passed in, stream and surface will have 1-to-1
788 // mapping. So the surface index is 0 for each stream in the surfaceMap.
789 for (size_t i = 0; i < streams.count; i++) {
790 surfaceMap[streams.data.i32[i]].push_back(0);
791 }
792 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800793}
794
Jianing Wei90e59c92014-03-12 18:29:36 -0700795status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000796 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700797 const std::list<const SurfaceMap> &surfaceMaps,
798 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700799 /*out*/
800 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700802 nsecs_t requestTimeNs = systemTime();
803
Jianing Wei90e59c92014-03-12 18:29:36 -0700804 Mutex::Autolock il(mInterfaceLock);
805 Mutex::Autolock l(mLock);
806
807 status_t res = checkStatusOkToCaptureLocked();
808 if (res != OK) {
809 // error logged by previous call
810 return res;
811 }
812
813 RequestList requestList;
814
Shuzhen Wang0129d522016-10-30 22:43:41 -0700815 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700816 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700817 if (res != OK) {
818 // error logged by previous call
819 return res;
820 }
821
822 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700823 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700825 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 }
827
828 if (res == OK) {
829 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
830 if (res != OK) {
831 SET_ERR_L("Can't transition to active in %f seconds!",
832 kActiveTimeout/1e9);
833 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800834 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700835 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700836 } else {
837 CLOGE("Cannot queue request. Impossible.");
838 return BAD_VALUE;
839 }
840
841 return res;
842}
843
Emilian Peevaebbe412018-01-15 13:53:24 +0000844status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700845 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700846 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700847 ATRACE_CALL();
848
Emilian Peevaebbe412018-01-15 13:53:24 +0000849 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700850}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800851
Jianing Weicb0652e2014-03-12 18:29:36 -0700852status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
853 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800854 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700857 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700861 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800862}
863
Emilian Peevaebbe412018-01-15 13:53:24 +0000864status_t Camera3Device::setStreamingRequestList(
865 const List<const PhysicalCameraSettingsList> &requestsList,
866 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700867 ATRACE_CALL();
868
Emilian Peevaebbe412018-01-15 13:53:24 +0000869 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800871
872sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000873 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800874 status_t res;
875
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700876 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800877 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
878 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700880 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700881 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800882 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700883 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700885 } else if (mStatus == STATUS_UNCONFIGURED) {
886 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700887 CLOGE("No streams configured");
888 return NULL;
889 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800890 }
891
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800893 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800894}
895
Jianing Weicb0652e2014-03-12 18:29:36 -0700896status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700898 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800899 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800900
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800901 switch (mStatus) {
902 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700903 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800904 return INVALID_OPERATION;
905 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700906 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800907 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700908 case STATUS_UNCONFIGURED:
909 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800910 case STATUS_ACTIVE:
911 // OK
912 break;
913 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700914 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800915 return INVALID_OPERATION;
916 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800917 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700918
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800920}
921
922status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
923 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700924 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700926 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800927}
928
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700929status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800930 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700931 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700932 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700933 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800935 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
936 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700937
938 status_t res;
939 bool wasActive = false;
940
941 switch (mStatus) {
942 case STATUS_ERROR:
943 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
944 return INVALID_OPERATION;
945 case STATUS_UNINITIALIZED:
946 ALOGE("%s: Device not initialized", __FUNCTION__);
947 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700948 case STATUS_UNCONFIGURED:
949 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950 // OK
951 break;
952 case STATUS_ACTIVE:
953 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700954 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700956 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700957 return res;
958 }
959 wasActive = true;
960 break;
961 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700962 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 return INVALID_OPERATION;
964 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700965 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700966
967 if (mInputStream != 0) {
968 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
969 return INVALID_OPERATION;
970 }
971
972 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
973 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700974 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700975
976 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800977 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700978
979 *id = mNextStreamId++;
980
981 // Continue captures if active at start
982 if (wasActive) {
983 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100984 // Reuse current operating mode and session parameters for new stream config
985 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700986 if (res != OK) {
987 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
988 __FUNCTION__, mNextStreamId, strerror(-res), res);
989 return res;
990 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700991 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700992 }
993
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800994 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700995 return OK;
996}
997
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700998status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700999 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001000 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001001 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001002 const std::unordered_set<int32_t> &sensorPixelModesUsed,
1003 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001004 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001005 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001006 ATRACE_CALL();
1007
1008 if (consumer == nullptr) {
1009 ALOGE("%s: consumer must not be null", __FUNCTION__);
1010 return BAD_VALUE;
1011 }
1012
1013 std::vector<sp<Surface>> consumers;
1014 consumers.push_back(consumer);
1015
1016 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001017 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001018 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001019 streamUseCase, timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001020}
1021
1022static bool isRawFormat(int format) {
1023 switch (format) {
1024 case HAL_PIXEL_FORMAT_RAW16:
1025 case HAL_PIXEL_FORMAT_RAW12:
1026 case HAL_PIXEL_FORMAT_RAW10:
1027 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1028 return true;
1029 default:
1030 return false;
1031 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001032}
1033
1034status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1035 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001036 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001037 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001038 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001039 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001040 int timestampBase, int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001041 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001042
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001043 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001044 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001045 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001046 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001047 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001048 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001049 " mirrorMode %d, colorSpace %d, useReadoutTimestamp %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001050 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001051 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001052 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode, colorSpace,
1053 useReadoutTimestamp);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001054
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 status_t res;
1056 bool wasActive = false;
1057
1058 switch (mStatus) {
1059 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001060 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001061 return INVALID_OPERATION;
1062 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001063 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001065 case STATUS_UNCONFIGURED:
1066 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001067 // OK
1068 break;
1069 case STATUS_ACTIVE:
1070 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001071 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001072 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001073 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074 return res;
1075 }
1076 wasActive = true;
1077 break;
1078 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001079 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001080 return INVALID_OPERATION;
1081 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001082 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001083
1084 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001085
Shuzhen Wang0129d522016-10-30 22:43:41 -07001086 if (consumers.size() == 0 && !hasDeferredConsumer) {
1087 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1088 return BAD_VALUE;
1089 }
Zhijun He5d677d12016-05-29 16:52:39 -07001090
Shuzhen Wang0129d522016-10-30 22:43:41 -07001091 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001092 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1093 return BAD_VALUE;
1094 }
1095
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001096 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1097 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1098 // be found in only one sensor pixel mode.
1099 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1100 return BAD_VALUE;
1101 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001102 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001103 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001104 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001105 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001106 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001107 if (blobBufferSize <= 0) {
1108 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1109 return BAD_VALUE;
1110 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001111 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1112 blobBufferSize = width * height;
1113 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001114 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001115 if (blobBufferSize <= 0) {
1116 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1117 return BAD_VALUE;
1118 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001119 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001121 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001122 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001123 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001124 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001125 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001126 bool maxResolution =
1127 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1128 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001129 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1130 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001131 if (rawOpaqueBufferSize <= 0) {
1132 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1133 return BAD_VALUE;
1134 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001135 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001136 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001137 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001138 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001139 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001140 } else if (isShared) {
1141 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1142 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001143 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001144 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001145 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001146 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001147 newStream = new Camera3OutputStream(mNextStreamId,
1148 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001149 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001150 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001151 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001153 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001154 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001155 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001156 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wangbce53db2022-12-03 00:38:20 +00001157 timestampBase, mirrorMode, colorSpace, useReadoutTimestamp);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 }
Emilian Peev40ead602017-09-26 15:46:36 +01001159
1160 size_t consumerCount = consumers.size();
1161 for (size_t i = 0; i < consumerCount; i++) {
1162 int id = newStream->getSurfaceId(consumers[i]);
1163 if (id < 0) {
1164 SET_ERR_L("Invalid surface id");
1165 return BAD_VALUE;
1166 }
1167 if (surfaceIds != nullptr) {
1168 surfaceIds->push_back(id);
1169 }
1170 }
1171
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001172 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173
Emilian Peev08dd2452017-04-06 16:55:14 +01001174 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001175
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001176 newStream->setImageDumpMask(mImageDumpMask);
1177
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 res = mOutputStreams.add(mNextStreamId, newStream);
1179 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181 return res;
1182 }
1183
Shuzhen Wang316781a2020-08-18 18:11:01 -07001184 mSessionStatsBuilder.addStream(mNextStreamId);
1185
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001187 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188
1189 // Continue captures if active at start
1190 if (wasActive) {
1191 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001192 // Reuse current operating mode and session parameters for new stream config
1193 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001195 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1196 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 return res;
1198 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001199 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001201 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001203}
1204
Emilian Peev710c1422017-08-30 11:19:38 +01001205status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001207 if (nullptr == streamInfo) {
1208 return BAD_VALUE;
1209 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 switch (mStatus) {
1214 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001215 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 return INVALID_OPERATION;
1217 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001220 case STATUS_UNCONFIGURED:
1221 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 case STATUS_ACTIVE:
1223 // OK
1224 break;
1225 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001226 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 return INVALID_OPERATION;
1228 }
1229
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001230 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1231 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001233 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 }
1235
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001236 streamInfo->width = stream->getWidth();
1237 streamInfo->height = stream->getHeight();
1238 streamInfo->format = stream->getFormat();
1239 streamInfo->dataSpace = stream->getDataSpace();
1240 streamInfo->formatOverridden = stream->isFormatOverridden();
1241 streamInfo->originalFormat = stream->getOriginalFormat();
1242 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1243 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001244 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Austin Borger9e2b27c2022-07-15 11:27:24 -07001245 streamInfo->colorSpace = stream->getColorSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247}
1248
1249status_t Camera3Device::setStreamTransform(int id,
1250 int transform) {
1251 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 switch (mStatus) {
1256 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001260 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001262 case STATUS_UNCONFIGURED:
1263 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 case STATUS_ACTIVE:
1265 // OK
1266 break;
1267 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001268 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001269 return INVALID_OPERATION;
1270 }
1271
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001272 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1273 if (stream == nullptr) {
1274 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001275 return BAD_VALUE;
1276 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001277 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
1280status_t Camera3Device::deleteStream(int id) {
1281 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 Mutex::Autolock l(mLock);
1284 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001285
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001287
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 // CameraDevice semantics require device to already be idle before
1289 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001290 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001291 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001292 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 }
1294
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001295 if (mStatus == STATUS_ERROR) {
1296 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1297 __FUNCTION__, mId.string());
1298 return -EBUSY;
1299 }
1300
Igor Murashkin2fba5842013-04-22 14:03:54 -07001301 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001302 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001303 if (mInputStream != NULL && id == mInputStream->getId()) {
1304 deletedStream = mInputStream;
1305 mInputStream.clear();
1306 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001307 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001308 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001309 return BAD_VALUE;
1310 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001311 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001312 }
1313
1314 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001315 if (stream != nullptr) {
1316 deletedStream = stream;
1317 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318 }
1319
1320 // Free up the stream endpoint so that it can be used by some other stream
1321 res = deletedStream->disconnect();
1322 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001323 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001324 // fall through since we want to still list the stream as deleted.
1325 }
1326 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001327 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001328
1329 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001330}
1331
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001332status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001333 ATRACE_CALL();
1334 ALOGV("%s: E", __FUNCTION__);
1335
1336 Mutex::Autolock il(mInterfaceLock);
1337 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001338
Emilian Peev811d2952018-05-25 11:08:40 +01001339 // In case the client doesn't include any session parameter, try a
1340 // speculative configuration using the values from the last cached
1341 // default request.
1342 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001343 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001344 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1345 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1346 mLastTemplateId);
1347 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1348 operatingMode);
1349 }
1350
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001351 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1352}
1353
1354status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1355 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001356 //Filter out any incoming session parameters
1357 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001358 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1359 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001360 CameraMetadata filteredParams(availableSessionKeys.count);
1361 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1362 filteredParams.getAndLock());
1363 set_camera_metadata_vendor_id(meta, mVendorTagId);
1364 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001365 if (availableSessionKeys.count > 0) {
1366 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1367 camera_metadata_ro_entry entry = params.find(
1368 availableSessionKeys.data.i32[i]);
1369 if (entry.count > 0) {
1370 filteredParams.update(entry);
1371 }
1372 }
1373 }
1374
1375 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001376}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001378status_t Camera3Device::getInputBufferProducer(
1379 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001380 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001381 Mutex::Autolock il(mInterfaceLock);
1382 Mutex::Autolock l(mLock);
1383
1384 if (producer == NULL) {
1385 return BAD_VALUE;
1386 } else if (mInputStream == NULL) {
1387 return INVALID_OPERATION;
1388 }
1389
1390 return mInputStream->getInputBufferProducer(producer);
1391}
1392
Emilian Peevf4816702020-04-03 15:44:51 -07001393status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001394 CameraMetadata *request) {
1395 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001396 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001397
Emilian Peevf4816702020-04-03 15:44:51 -07001398 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001399 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001400 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001401 return BAD_VALUE;
1402 }
1403
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001404 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001405
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001406 {
1407 Mutex::Autolock l(mLock);
1408 switch (mStatus) {
1409 case STATUS_ERROR:
1410 CLOGE("Device has encountered a serious error");
1411 return INVALID_OPERATION;
1412 case STATUS_UNINITIALIZED:
1413 CLOGE("Device is not initialized!");
1414 return INVALID_OPERATION;
1415 case STATUS_UNCONFIGURED:
1416 case STATUS_CONFIGURED:
1417 case STATUS_ACTIVE:
1418 // OK
1419 break;
1420 default:
1421 SET_ERR_L("Unexpected status: %d", mStatus);
1422 return INVALID_OPERATION;
1423 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001424
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001425 if (!mRequestTemplateCache[templateId].isEmpty()) {
1426 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001427 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001428 return OK;
1429 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001430 }
1431
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001432 camera_metadata_t *rawRequest;
1433 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001434 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001435
1436 {
1437 Mutex::Autolock l(mLock);
1438 if (res == BAD_VALUE) {
1439 ALOGI("%s: template %d is not supported on this camera device",
1440 __FUNCTION__, templateId);
1441 return res;
1442 } else if (res != OK) {
1443 CLOGE("Unable to construct request template %d: %s (%d)",
1444 templateId, strerror(-res), res);
1445 return res;
1446 }
1447
1448 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1449 mRequestTemplateCache[templateId].acquire(rawRequest);
1450
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001451 // Override the template request with zoomRatioMapper
1452 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1453 &mRequestTemplateCache[templateId]);
1454 if (res != OK) {
1455 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1456 templateId, strerror(-res), res);
1457 return res;
1458 }
1459
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001460 // Fill in JPEG_QUALITY if not available
1461 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1462 static const uint8_t kDefaultJpegQuality = 95;
1463 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1464 &kDefaultJpegQuality, 1);
1465 }
1466
Bharatt Kukrejad33fe9f2022-11-23 21:52:52 +00001467 // Fill in AUTOFRAMING if not available
1468 if (!mRequestTemplateCache[templateId].exists(ANDROID_CONTROL_AUTOFRAMING)) {
1469 static const uint8_t kDefaultAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_OFF;
1470 mRequestTemplateCache[templateId].update(ANDROID_CONTROL_AUTOFRAMING,
1471 &kDefaultAutoframingMode, 1);
1472 }
1473
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001474 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001475 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001476 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477 return OK;
1478}
1479
1480status_t Camera3Device::waitUntilDrained() {
1481 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001483 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001485
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001486 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001487}
1488
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 switch (mStatus) {
1491 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 ALOGV("%s: Already idle", __FUNCTION__);
1494 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 case STATUS_CONFIGURED:
1496 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 case STATUS_ERROR:
1498 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 break;
1501 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001502 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return INVALID_OPERATION;
1504 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001505 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1506 maxExpectedDuration);
1507 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001508 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001509 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001510 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1511 res);
1512 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001513 return res;
1514}
1515
Ruben Brunk183f0562015-08-12 12:55:02 -07001516void Camera3Device::internalUpdateStatusLocked(Status status) {
1517 mStatus = status;
1518 mRecentStatusUpdates.add(mStatus);
1519 mStatusChanged.broadcast();
1520}
1521
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001523status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001524 if (mRequestThread.get() != nullptr) {
1525 mRequestThread->setPaused(true);
1526 } else {
1527 return NO_INIT;
1528 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001529
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001530 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1531 maxExpectedDuration);
1532 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 if (res != OK) {
Bharatt Kukreja086e57f2022-08-13 00:56:10 +00001534 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001536 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 }
1538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 return res;
1540}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542// Resume after internalPauseAndWaitLocked
1543status_t Camera3Device::internalResumeLocked() {
1544 status_t res;
1545
1546 mRequestThread->setPaused(false);
1547
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001548 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1549 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1551 if (res != OK) {
1552 SET_ERR_L("Can't transition to active in %f seconds!",
1553 kActiveTimeout/1e9);
1554 }
1555 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557}
1558
Ruben Brunk183f0562015-08-12 12:55:02 -07001559status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001561
1562 size_t startIndex = 0;
1563 if (mStatusWaiters == 0) {
1564 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1565 // this status list
1566 mRecentStatusUpdates.clear();
1567 } else {
1568 // If other threads are waiting on updates to this status list, set the position of the
1569 // first element that this list will check rather than clearing the list.
1570 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 }
1572
Ruben Brunk183f0562015-08-12 12:55:02 -07001573 mStatusWaiters++;
1574
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001575 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001576 if (!active && mUseHalBufManager) {
1577 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001578 if (mStatus == STATUS_ACTIVE) {
1579 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001580 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001581 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001582 mRequestBufferSM.onWaitUntilIdle();
1583 }
1584
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001585 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001586 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001588 if (active == (mStatus == STATUS_ACTIVE)) {
1589 // Desired state is current
1590 break;
1591 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001593 nsecs_t timeElapsed = systemTime() - startTime;
1594 nsecs_t timeToWait = timeout - timeElapsed;
1595 if (timeToWait <= 0) {
1596 // Thread woke up spuriously but has timed out since.
1597 // Force out of loop with TIMED_OUT result.
1598 res = TIMED_OUT;
1599 break;
1600 }
1601 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 if (res != OK) break;
1603
Ruben Brunk183f0562015-08-12 12:55:02 -07001604 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1605 // transitions.
1606 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1607 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1608 __FUNCTION__);
1609
1610 // Encountered desired state since we began waiting
1611 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1613 stateSeen = true;
1614 break;
1615 }
1616 }
1617 } while (!stateSeen);
1618
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001619 if (signalPipelineDrain) {
1620 mRequestThread->resetPipelineDrain();
1621 }
1622
Ruben Brunk183f0562015-08-12 12:55:02 -07001623 mStatusWaiters--;
1624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 return res;
1626}
1627
1628
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001629status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001631 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001633 if (listener != NULL && mListener != NULL) {
1634 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1635 }
1636 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001637 mRequestThread->setNotificationListener(listener);
1638 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001639
1640 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641}
1642
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001643bool Camera3Device::willNotify3A() {
1644 return false;
1645}
1646
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001648 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001649 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001650
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001651 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001652 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1653 if (st == std::cv_status::timeout) {
1654 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001655 }
1656 }
1657 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658}
1659
Jianing Weicb0652e2014-03-12 18:29:36 -07001660status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001662 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001664 if (mResultQueue.empty()) {
1665 return NOT_ENOUGH_DATA;
1666 }
1667
Jianing Weicb0652e2014-03-12 18:29:36 -07001668 if (frame == NULL) {
1669 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1670 return BAD_VALUE;
1671 }
1672
1673 CaptureResult &result = *(mResultQueue.begin());
1674 frame->mResultExtras = result.mResultExtras;
1675 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001676 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001677 mResultQueue.erase(mResultQueue.begin());
1678
1679 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680}
1681
1682status_t Camera3Device::triggerAutofocus(uint32_t id) {
1683 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1687 // Mix-in this trigger into the next request and only the next request.
1688 RequestTrigger trigger[] = {
1689 {
1690 ANDROID_CONTROL_AF_TRIGGER,
1691 ANDROID_CONTROL_AF_TRIGGER_START
1692 },
1693 {
1694 ANDROID_CONTROL_AF_TRIGGER_ID,
1695 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001696 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 };
1698
1699 return mRequestThread->queueTrigger(trigger,
1700 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001701}
1702
1703status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1704 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001706
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001707 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1708 // Mix-in this trigger into the next request and only the next request.
1709 RequestTrigger trigger[] = {
1710 {
1711 ANDROID_CONTROL_AF_TRIGGER,
1712 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1713 },
1714 {
1715 ANDROID_CONTROL_AF_TRIGGER_ID,
1716 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001717 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001718 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001719
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001720 return mRequestThread->queueTrigger(trigger,
1721 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001722}
1723
1724status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1725 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001728 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1729 // Mix-in this trigger into the next request and only the next request.
1730 RequestTrigger trigger[] = {
1731 {
1732 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1733 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1734 },
1735 {
1736 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1737 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001738 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001739 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001741 return mRequestThread->queueTrigger(trigger,
1742 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743}
1744
Jianing Weicb0652e2014-03-12 18:29:36 -07001745status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001746 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001747 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001748 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001749
Zhijun He7ef20392014-04-21 16:04:17 -07001750 {
1751 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001752
1753 // b/116514106 "disconnect()" can get called twice for the same device. The
1754 // camera device will not be initialized during the second run.
1755 if (mStatus == STATUS_UNINITIALIZED) {
1756 return OK;
1757 }
1758
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001759 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001760
1761 // Stop session and stream counter
1762 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001763 }
1764
Ravneetdbd5b242022-03-02 07:22:46 +00001765 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal7d412d22022-06-29 01:34:01 +00001766 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneetdbd5b242022-03-02 07:22:46 +00001767 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1768 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1769
1770 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001771}
1772
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001773status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001774 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1775}
1776
1777status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001778 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001779 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001780 Mutex::Autolock il(mInterfaceLock);
1781 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001782
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001783 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1784 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001785 CLOGE("Stream %d does not exist", streamId);
1786 return BAD_VALUE;
1787 }
1788
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001789 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001790 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001791 return BAD_VALUE;
1792 }
1793
1794 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001795 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001796 return BAD_VALUE;
1797 }
1798
Ruben Brunkc78ac262015-08-13 17:58:46 -07001799 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001800}
1801
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001802status_t Camera3Device::tearDown(int streamId) {
1803 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001804 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001805 Mutex::Autolock il(mInterfaceLock);
1806 Mutex::Autolock l(mLock);
1807
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001808 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1809 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001810 CLOGE("Stream %d does not exist", streamId);
1811 return BAD_VALUE;
1812 }
1813
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001814 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1815 CLOGE("Stream %d is a target of a in-progress request", streamId);
1816 return BAD_VALUE;
1817 }
1818
1819 return stream->tearDown();
1820}
1821
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001822status_t Camera3Device::addBufferListenerForStream(int streamId,
1823 wp<Camera3StreamBufferListener> listener) {
1824 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001825 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001826 Mutex::Autolock il(mInterfaceLock);
1827 Mutex::Autolock l(mLock);
1828
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001829 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1830 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001831 CLOGE("Stream %d does not exist", streamId);
1832 return BAD_VALUE;
1833 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001834 stream->addBufferListener(listener);
1835
1836 return OK;
1837}
1838
Austin Borger4a870a32022-02-25 01:48:41 +00001839float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1840 camera_metadata_entry minDurations =
1841 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1842 for (size_t i = 0; i < minDurations.count; i += 4) {
1843 if (minDurations.data.i64[i] == stream->getFormat()
1844 && minDurations.data.i64[i+1] == stream->getWidth()
1845 && minDurations.data.i64[i+2] == stream->getHeight()) {
1846 int64_t minFrameDuration = minDurations.data.i64[i+3];
1847 return 1e9f / minFrameDuration;
1848 }
1849 }
1850 return 0.0f;
1851}
1852
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 * Methods called by subclasses
1855 */
1856
1857void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001858 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001859 std::vector<int> streamIds;
1860 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001861 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001862
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863 {
1864 // Need mLock to safely update state and synchronize to current
1865 // state of methods in flight.
1866 Mutex::Autolock l(mLock);
1867 // We can get various system-idle notices from the status tracker
1868 // while starting up. Only care about them if we've actually sent
1869 // in some requests recently.
1870 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1871 return;
1872 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001873 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1874 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001875 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876
1877 // Skip notifying listener if we're doing some user-transparent
1878 // state changes
1879 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001880
Austin Borger4a870a32022-02-25 01:48:41 +00001881 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1882 auto stream = mOutputStreams[i];
1883 if (stream.get() == nullptr) continue;
1884
1885 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1886 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1887
1888 // Populate stream statistics in case of Idle
1889 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001890 streamIds.push_back(stream->getId());
1891 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1892 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001893 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001894 if (camera3Stream != nullptr) {
1895 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001896 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001897 }
1898 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Shuzhen Wangb02d3fc2023-02-23 21:01:25 +00001899 stream->getOriginalFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001900 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001901 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Austin Borger9e2b27c2022-07-15 11:27:24 -07001902 stream->getDynamicRangeProfile(), streamUseCase,
1903 stream->getColorSpace());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001904 }
1905 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001906 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001907
1908 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001909 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001910 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001911 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001912 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001913 status_t res = OK;
1914 if (listener != nullptr) {
1915 if (idle) {
1916 // Get session stats from the builder, and notify the listener.
1917 int64_t requestCount, resultErrorCount;
1918 bool deviceError;
1919 std::map<int, StreamStats> streamStatsMap;
1920 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1921 &deviceError, &streamStatsMap);
1922 for (size_t i = 0; i < streamIds.size(); i++) {
1923 int streamId = streamIds[i];
1924 auto stats = streamStatsMap.find(streamId);
1925 if (stats != streamStatsMap.end()) {
1926 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1927 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1928 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1929 streamStats[i].mHistogramType =
1930 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1931 streamStats[i].mHistogramBins.assign(
1932 stats->second.mCaptureLatencyBins.begin(),
1933 stats->second.mCaptureLatencyBins.end());
1934 streamStats[i].mHistogramCounts.assign(
1935 stats->second.mCaptureLatencyHistogram.begin(),
1936 stats->second.mCaptureLatencyHistogram.end());
1937 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001938 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001939 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1940 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001941 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001942 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001943 }
1944 if (res != OK) {
1945 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1946 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947 }
1948}
1949
Shuzhen Wang758c2152017-01-10 18:26:18 -08001950status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001951 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001952 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001953 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1954 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001955
1956 if (surfaceIds == nullptr) {
1957 return BAD_VALUE;
1958 }
1959
Zhijun He5d677d12016-05-29 16:52:39 -07001960 Mutex::Autolock il(mInterfaceLock);
1961 Mutex::Autolock l(mLock);
1962
Shuzhen Wang758c2152017-01-10 18:26:18 -08001963 if (consumers.size() == 0) {
1964 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001965 return BAD_VALUE;
1966 }
1967
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001968 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1969 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001970 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001972 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001973
1974 // isConsumerConfigurationDeferred will be off after setConsumers
1975 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001976 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001977 if (res != OK) {
1978 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1979 return res;
1980 }
1981
Emilian Peev40ead602017-09-26 15:46:36 +01001982 for (auto &consumer : consumers) {
1983 int id = stream->getSurfaceId(consumer);
1984 if (id < 0) {
1985 CLOGE("Invalid surface id!");
1986 return BAD_VALUE;
1987 }
1988 surfaceIds->push_back(id);
1989 }
1990
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001991 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001992 if (!stream->isConfiguring()) {
1993 CLOGE("Stream %d was already fully configured.", streamId);
1994 return INVALID_OPERATION;
1995 }
Zhijun He5d677d12016-05-29 16:52:39 -07001996
Shuzhen Wang0129d522016-10-30 22:43:41 -07001997 res = stream->finishConfiguration();
1998 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001999 // If finishConfiguration fails due to abandoned surface, do not set
2000 // device to error state.
2001 bool isSurfaceAbandoned =
2002 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2003 if (!isSurfaceAbandoned) {
2004 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2005 stream->getId(), strerror(-res), res);
2006 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002007 return res;
2008 }
Zhijun He5d677d12016-05-29 16:52:39 -07002009 }
2010
2011 return OK;
2012}
2013
Emilian Peev40ead602017-09-26 15:46:36 +01002014status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2015 const std::vector<OutputStreamInfo> &outputInfo,
2016 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2017 Mutex::Autolock il(mInterfaceLock);
2018 Mutex::Autolock l(mLock);
2019
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002020 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2021 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002022 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002023 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002024 }
2025
2026 for (const auto &it : removedSurfaceIds) {
2027 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2028 CLOGE("Shared surface still part of a pending request!");
2029 return -EBUSY;
2030 }
2031 }
2032
Emilian Peev40ead602017-09-26 15:46:36 +01002033 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2034 if (res != OK) {
2035 CLOGE("Stream %d failed to update stream (error %d %s) ",
2036 streamId, res, strerror(-res));
2037 if (res == UNKNOWN_ERROR) {
2038 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2039 __FUNCTION__);
2040 }
2041 return res;
2042 }
2043
2044 return res;
2045}
2046
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002047status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2048 Mutex::Autolock il(mInterfaceLock);
2049 Mutex::Autolock l(mLock);
2050
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002051 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2052 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002053 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2054 return BAD_VALUE;
2055 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002056
2057 if (dropping) {
2058 mSessionStatsBuilder.stopCounter(streamId);
2059 } else {
2060 mSessionStatsBuilder.startCounter(streamId);
2061 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002062 return stream->dropBuffers(dropping);
2063}
2064
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002065/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066 * Camera3Device private methods
2067 */
2068
2069sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002070 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002073 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002074 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075
2076 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002077 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002078 if (inputStreams.count > 0) {
2079 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002080 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002081 CLOGE("Request references unknown input stream %d",
2082 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 return NULL;
2084 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002085
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002086 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002087 SET_ERR_L("%s: input stream %d is not configured!",
2088 __FUNCTION__, mInputStream->getId());
2089 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002090 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002091 // Check if stream prepare is blocking requests.
2092 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002093 CLOGE("Request references an input stream that's being prepared!");
2094 return NULL;
2095 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096
2097 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002098 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002099 }
2100
2101 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002102 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002104 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105 return NULL;
2106 }
2107
2108 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002109 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2110 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002111 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002112 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 return NULL;
2114 }
Zhijun He5d677d12016-05-29 16:52:39 -07002115 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002116 auto iter = surfaceMap.find(streams.data.i32[i]);
2117 if (iter != surfaceMap.end()) {
2118 const std::vector<size_t>& surfaces = iter->second;
2119 for (const auto& surface : surfaces) {
2120 if (stream->isConsumerConfigurationDeferred(surface)) {
2121 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2122 "due to deferred consumer", stream->getId(), surface);
2123 return NULL;
2124 }
2125 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002126 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002127 }
2128
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002130 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2131 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002133 // Check if stream prepare is blocking requests.
2134 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002135 CLOGE("Request references an output stream that's being prepared!");
2136 return NULL;
2137 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138
2139 newRequest->mOutputStreams.push(stream);
2140 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002141 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002142 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002144 auto rotateAndCropEntry =
2145 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2146 if (rotateAndCropEntry.count > 0 &&
2147 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2148 newRequest->mRotateAndCropAuto = true;
2149 } else {
2150 newRequest->mRotateAndCropAuto = false;
2151 }
2152
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002153 auto autoframingEntry =
2154 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_AUTOFRAMING);
2155 if (autoframingEntry.count > 0 &&
2156 autoframingEntry.data.u8[0] == ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2157 newRequest->mAutoframingAuto = true;
2158 } else {
2159 newRequest->mAutoframingAuto = false;
2160 }
2161
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002162 auto zoomRatioEntry =
2163 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2164 if (zoomRatioEntry.count > 0 &&
2165 zoomRatioEntry.data.f[0] == 1.0f) {
2166 newRequest->mZoomRatioIs1x = true;
2167 } else {
2168 newRequest->mZoomRatioIs1x = false;
2169 }
2170
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002171 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002172 for (auto& settings : newRequest->mSettingsList) {
2173 auto testPatternModeEntry =
2174 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2175 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2176 testPatternModeEntry.data.i32[0] :
2177 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002178
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002179 auto testPatternDataEntry =
2180 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2181 if (testPatternDataEntry.count >= 4) {
2182 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2183 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2184 } else {
2185 settings.mOriginalTestPatternData[0] = 0;
2186 settings.mOriginalTestPatternData[1] = 0;
2187 settings.mOriginalTestPatternData[2] = 0;
2188 settings.mOriginalTestPatternData[3] = 0;
2189 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002190 }
2191 }
2192
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002193 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194}
2195
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002196void Camera3Device::cancelStreamsConfigurationLocked() {
2197 int res = OK;
2198 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2199 res = mInputStream->cancelConfiguration();
2200 if (res != OK) {
2201 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2202 mInputStream->getId(), strerror(-res), res);
2203 }
2204 }
2205
2206 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002207 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002208 if (outputStream->isConfiguring()) {
2209 res = outputStream->cancelConfiguration();
2210 if (res != OK) {
2211 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2212 outputStream->getId(), strerror(-res), res);
2213 }
2214 }
2215 }
2216
2217 // Return state to that at start of call, so that future configures
2218 // properly clean things up
2219 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2220 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002221
2222 res = mPreparerThread->resume();
2223 if (res != OK) {
2224 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2225 }
2226}
2227
Emilian Peev0d0191e2020-04-21 17:01:18 -07002228bool Camera3Device::checkAbandonedStreamsLocked() {
2229 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2230 return true;
2231 }
2232
2233 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2234 auto stream = mOutputStreams[i];
2235 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2236 return true;
2237 }
2238 }
2239
2240 return false;
2241}
2242
Emilian Peev3bead5f2020-05-28 17:29:08 -07002243bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002244 ATRACE_CALL();
2245 bool ret = false;
2246
Shuzhen Wang316781a2020-08-18 18:11:01 -07002247 nsecs_t startTime = systemTime();
2248
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002249 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002250 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2251
2252 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002253 if (checkAbandonedStreamsLocked()) {
2254 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2255 __FUNCTION__);
2256 return true;
2257 }
2258
Emilian Peev3bead5f2020-05-28 17:29:08 -07002259 status_t rc = NO_ERROR;
2260 bool markClientActive = false;
2261 if (mStatus == STATUS_ACTIVE) {
2262 markClientActive = true;
2263 mPauseStateNotify = true;
Emilian Peev3bead5f2020-05-28 17:29:08 -07002264
2265 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2266 }
2267
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002268 if (rc == NO_ERROR) {
2269 mNeedConfig = true;
2270 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2271 if (rc == NO_ERROR) {
2272 ret = true;
2273 mPauseStateNotify = false;
2274 //Moving to active state while holding 'mLock' is important.
2275 //There could be pending calls to 'create-/deleteStream' which
2276 //will trigger another stream configuration while the already
2277 //present streams end up with outstanding buffers that will
2278 //not get drained.
2279 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002280 } else if (rc == DEAD_OBJECT) {
2281 // DEAD_OBJECT can be returned if either the consumer surface is
2282 // abandoned, or the HAL has died.
2283 // - If the HAL has died, configureStreamsLocked call will set
2284 // device to error state,
2285 // - If surface is abandoned, we should not set device to error
2286 // state.
2287 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002288 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002289 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002290 }
2291 } else {
2292 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2293 }
2294
Austin Borger74fca042022-05-23 12:41:21 -07002295 mCameraServiceProxyWrapper->logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002296 ns2ms(systemTime() - startTime));
2297
Emilian Peev3bead5f2020-05-28 17:29:08 -07002298 if (markClientActive) {
2299 mStatusTracker->markComponentActive(clientStatusId);
2300 }
2301
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002302 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002303}
2304
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002305status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002306 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 ATRACE_CALL();
2308 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002310 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002311 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 return INVALID_OPERATION;
2313 }
2314
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002315 if (operatingMode < 0) {
2316 CLOGE("Invalid operating mode: %d", operatingMode);
2317 return BAD_VALUE;
2318 }
2319
2320 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002321 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002322
2323 if (mOperatingMode != operatingMode) {
2324 mNeedConfig = true;
2325 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2326 mOperatingMode = operatingMode;
2327 }
2328
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002329 // Reset min expected duration when session is reconfigured.
2330 mMinExpectedDuration = 0;
2331
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002332 // In case called from configureStreams, abort queued input buffers not belonging to
2333 // any pending requests.
2334 if (mInputStream != NULL && notifyRequestThread) {
2335 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002336 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002337 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002338 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002339 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002340 if (res != OK) {
2341 // Exhausted acquiring all input buffers.
2342 break;
2343 }
2344
Emilian Peevf4816702020-04-03 15:44:51 -07002345 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002346 res = mInputStream->returnInputBuffer(inputBuffer);
2347 if (res != OK) {
2348 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2349 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2350 }
2351 }
2352 }
2353
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002354 if (!mNeedConfig) {
2355 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2356 return OK;
2357 }
2358
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002359 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002360 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002361 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2362 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002363 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002364 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002365 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002366 }
2367
Shuzhen Wang16610a62022-12-15 22:38:07 -08002368 // Override stream use case based on "adb shell command"
2369 overrideStreamUseCaseLocked();
2370
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002372 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002374 mPreparerThread->pause();
2375
Emilian Peevf4816702020-04-03 15:44:51 -07002376 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002377 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002378 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002379 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380
Emilian Peevf4816702020-04-03 15:44:51 -07002381 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002383 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002384
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385
2386 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002387 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 inputStream = mInputStream->startConfiguration();
2389 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002390 CLOGE("Can't start input stream configuration");
2391 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392 return INVALID_OPERATION;
2393 }
2394 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002395
2396 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002397 }
2398
Shuzhen Wang99080502021-03-07 21:08:20 -08002399 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002400 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002401 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002402
2403 // Don't configure bidi streams twice, nor add them twice to the list
2404 if (mOutputStreams[i].get() ==
2405 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2406
2407 config.num_streams--;
2408 continue;
2409 }
2410
Emilian Peevf4816702020-04-03 15:44:51 -07002411 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002412 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002414 CLOGE("Can't start output stream configuration");
2415 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002416 return INVALID_OPERATION;
2417 }
2418 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002419
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002420 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002421 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2422 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002423 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2424 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002425 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2426 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002427 } else if (outputStream->data_space ==
2428 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2429 bufferSizes[k] = outputStream->width * outputStream->height;
2430 } else {
2431 ALOGW("%s: Blob dataSpace %d not supported",
2432 __FUNCTION__, outputStream->data_space);
2433 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002434 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002435
2436 if (mOutputStreams[i]->isMultiResolution()) {
2437 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2438 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2439 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2440 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002441
2442 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2443 composerSurfacePresent = true;
2444 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002445 }
2446
2447 config.streams = streams.editArray();
2448
2449 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002450 // max_buffers, usage, and priv fields, as well as data_space and format
2451 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002452
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002453 int64_t logId = mCameraServiceProxyWrapper->getCurrentLogIdForCamera(mId);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002454 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Avichal Rakesh1fff2d12023-03-03 15:05:48 -08002455 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes, logId);
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