blob: aeffd249906ee5889cec81c817e229bf7373a790 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.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;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
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),
99 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
105Camera3Device::~Camera3Device()
106{
107 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700109 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800113 return mId;
114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116status_t Camera3Device::initializeCommonLocked() {
117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700118 /** Start up status tracker thread */
119 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700121 if (res != OK) {
122 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
123 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 mStatusTracker.clear();
126 return res;
127 }
128
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700129 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700130 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700132 if (mUseHalBufManager) {
133 res = mRequestBufferSM.initialize(mStatusTracker);
134 if (res != OK) {
135 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
136 strerror(-res), res);
137 mInterface->close();
138 mStatusTracker.clear();
139 return res;
140 }
141 }
142
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800143 /** Create buffer manager */
144 mBufferManager = new Camera3BufferManager();
145
146 Vector<int32_t> sessionParamKeys;
147 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
148 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
149 if (sessionKeysEntry.count > 0) {
150 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
151 }
152
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700153 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
154 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
155 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
156 if (availableTestPatternModes.data.i32[i] ==
157 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
158 mSupportCameraMute = true;
159 mSupportTestPatternSolidColor = true;
160 break;
161 } else if (availableTestPatternModes.data.i32[i] ==
162 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
163 mSupportCameraMute = true;
164 mSupportTestPatternSolidColor = false;
165 }
166 }
167
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700168 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800169 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700170 this, mStatusTracker, mInterface, sessionParamKeys,
171 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800173 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700174 SET_ERR_L("Unable to start request queue thread: %s (%d)",
175 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800177 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800178 return res;
179 }
180
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700181 mPreparerThread = new PreparerThread();
182
Ruben Brunk183f0562015-08-12 12:55:02 -0700183 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800184 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400185 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700186 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700187 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800188 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800190 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800191 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 camera_metadata_entry timestampSource =
193 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
194 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
195 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800196 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 }
198
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700199 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100200 camera_metadata_entry partialResultsCount =
201 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
202 if (partialResultsCount.count > 0) {
203 mNumPartialResults = partialResultsCount.data.i32[0];
204 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700205 }
206
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800207 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
208 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700209 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700210 if (res != OK) {
211 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
212 return res;
213 }
214 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800216 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700219 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
220 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
221 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
222 }
223
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800224 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
225 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
226 }
227
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800228 // Hidl/AidlCamera3DeviceInjectionMethods
229 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800230
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 return OK;
232}
233
234status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700235 return disconnectImpl();
236}
237
238status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700240 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800241
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700242 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700243 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800245 Mutex::Autolock il(mInterfaceLock);
246 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
247 {
248 Mutex::Autolock l(mLock);
249 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700250
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800251 if (mStatus == STATUS_ACTIVE ||
252 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
253 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 } else {
258 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
259 if (res != OK) {
260 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
261 maxExpectedDuration);
262 // Continue to close device even in case of error
263 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800266
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 if (mStatus == STATUS_ERROR) {
268 CLOGE("Shutting down in an error state");
269 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatusTracker != NULL) {
272 mStatusTracker->requestExit();
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mRequestThread != NULL) {
276 mRequestThread->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
280 for (size_t i = 0; i < mOutputStreams.size(); i++) {
281 streams.push_back(mOutputStreams[i]);
282 }
283 if (mInputStream != nullptr) {
284 streams.push_back(mInputStream);
285 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
289 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
291 // HAL may be in a bad state, so waiting for request thread
292 // (which may be stuck in the HAL processCaptureRequest call)
293 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 // give up mInterfaceLock here and then lock it again. Could this lead
295 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 mRequestThread->join();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 Mutex::Autolock il(mInterfaceLock);
300 if (mStatusTracker != NULL) {
301 mStatusTracker->join();
302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800304 if (mInjectionMethods->isInjecting()) {
305 mInjectionMethods->stopInjection();
306 }
307
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 HalInterface* interface;
309 {
310 Mutex::Autolock l(mLock);
311 mRequestThread.clear();
312 Mutex::Autolock stLock(mTrackerLock);
313 mStatusTracker.clear();
314 interface = mInterface.get();
315 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700316
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 // Call close without internal mutex held, as the HAL close may need to
318 // wait on assorted callbacks,etc, to complete before it can return.
319 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 {
324 Mutex::Autolock l(mLock);
325 mInterface->clear();
326 mOutputStreams.clear();
327 mInputStream.clear();
328 mDeletedStreams.clear();
329 mBufferManager.clear();
330 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
331 }
332
333 for (auto& weakStream : streams) {
334 sp<Camera3StreamInterface> stream = weakStream.promote();
335 if (stream != nullptr) {
336 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
337 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
338 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 }
340 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343}
344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345// For dumping/debugging only -
346// try to acquire a lock a few times, eventually give up to proceed with
347// debug/dump operations
348bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
349 bool gotLock = false;
350 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
351 if (lock.tryLock() == NO_ERROR) {
352 gotLock = true;
353 break;
354 } else {
355 usleep(kDumpSleepDuration);
356 }
357 }
358 return gotLock;
359}
360
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800361nsecs_t Camera3Device::getMonoToBoottimeOffset() {
362 // try three times to get the clock offset, choose the one
363 // with the minimum gap in measurements.
364 const int tries = 3;
365 nsecs_t bestGap, measured;
366 for (int i = 0; i < tries; ++i) {
367 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
369 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t gap = tmono2 - tmono;
371 if (i == 0 || gap < bestGap) {
372 bestGap = gap;
373 measured = tbase - ((tmono + tmono2) >> 1);
374 }
375 }
376 return measured;
377}
378
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800379ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
380 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700381 // Get max jpeg size (area-wise) for default sensor pixel mode
382 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800383 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700384 /*isUltraHighResolutionSensor*/false);
385 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
386 // not ultra high res sensor
387 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800388 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700389 /*isUltraHighResolution*/true);
390 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
392 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700393 return BAD_VALUE;
394 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700395 bool useMaxSensorPixelModeThreshold = false;
396 if (uhrMaxJpegResolution.width != 0 &&
397 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
398 // Use the ultra high res max jpeg size and max jpeg buffer size
399 useMaxSensorPixelModeThreshold = true;
400 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700401
Zhijun Hef7da0962014-04-24 13:27:56 -0700402 // Get max jpeg buffer size
403 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
407 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700408 return BAD_VALUE;
409 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700410 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411
412 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
413 if (useMaxSensorPixelModeThreshold) {
414 maxJpegBufferSize =
415 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
416 maxDefaultJpegResolution, maxJpegBufferSize);
417 chosenMaxJpegResolution = uhrMaxJpegResolution;
418 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800419 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700420
421 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700422 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800424 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
425 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700426 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800427 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
428 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 return jpegBufferSize;
432}
433
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700435 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800436 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700437 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800438 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
439 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700440 return BAD_VALUE;
441 }
442 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
443 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
444 return maxBytesForPointCloud;
445}
446
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800447ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
448 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800449 const int PER_CONFIGURATION_SIZE = 3;
450 const int WIDTH_OFFSET = 0;
451 const int HEIGHT_OFFSET = 1;
452 const int SIZE_OFFSET = 2;
453 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800454 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800455 camera3::SessionConfigurationUtils::getAppropriateModeTag(
456 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
457 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800458 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800460 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
461 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800462 return BAD_VALUE;
463 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800465 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
466 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
467 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
468 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
469 }
470 }
471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800472 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
473 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 return BAD_VALUE;
475}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700476
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800477status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
478 ATRACE_CALL();
479 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700480
481 // Try to lock, but continue in case of failure (to avoid blocking in
482 // deadlocks)
483 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
484 bool gotLock = tryLockSpinRightRound(mLock);
485
486 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
488 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700489 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
491 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700492
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800493 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700494
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800495 String16 templatesOption("-t");
496 int n = args.size();
497 for (int i = 0; i < n; i++) {
498 if (args[i] == templatesOption) {
499 dumpTemplates = true;
500 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000501 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700502 if (i + 1 < n) {
503 String8 monitorTags = String8(args[i + 1]);
504 if (monitorTags == "off") {
505 mTagMonitor.disableMonitoring();
506 } else {
507 mTagMonitor.parseTagsToMonitor(monitorTags);
508 }
509 } else {
510 mTagMonitor.disableMonitoring();
511 }
512 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800513 }
514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800515 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800517 const char *status =
518 mStatus == STATUS_ERROR ? "ERROR" :
519 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700520 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
521 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800522 mStatus == STATUS_ACTIVE ? "ACTIVE" :
523 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700526 if (mStatus == STATUS_ERROR) {
527 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800529 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800530 const char *mode =
531 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
532 mOperatingMode == static_cast<int>(
533 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
534 "CUSTOM";
535 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800536
537 if (mInputStream != NULL) {
538 write(fd, lines.string(), lines.size());
539 mInputStream->dump(fd, args);
540 } else {
541 lines.appendFormat(" No input stream.\n");
542 write(fd, lines.string(), lines.size());
543 }
544 for (size_t i = 0; i < mOutputStreams.size(); i++) {
545 mOutputStreams[i]->dump(fd,args);
546 }
547
Zhijun He431503c2016-03-07 17:30:16 -0800548 if (mBufferManager != NULL) {
549 lines = String8(" Camera3 Buffer Manager:\n");
550 write(fd, lines.string(), lines.size());
551 mBufferManager->dump(fd, args);
552 }
Zhijun He125684a2015-12-26 15:07:30 -0800553
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700554 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700555 if (mInFlightLock.try_lock()) {
556 if (mInFlightMap.size() == 0) {
557 lines.append(" None\n");
558 } else {
559 for (size_t i = 0; i < mInFlightMap.size(); i++) {
560 InFlightRequest r = mInFlightMap.valueAt(i);
561 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
562 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
563 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
564 r.numBuffersLeft);
565 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700566 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700567 mInFlightLock.unlock();
568 } else {
569 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700570 }
571 write(fd, lines.string(), lines.size());
572
Shuzhen Wang686f6442017-06-20 16:16:04 -0700573 if (mRequestThread != NULL) {
574 mRequestThread->dumpCaptureRequestLatency(fd,
575 " ProcessCaptureRequest latency histogram:");
576 }
577
Igor Murashkin1e479c02013-09-06 16:55:14 -0700578 {
579 lines = String8(" Last request sent:\n");
580 write(fd, lines.string(), lines.size());
581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700582 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700583 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
584 }
585
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700587 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800588 "TEMPLATE_PREVIEW",
589 "TEMPLATE_STILL_CAPTURE",
590 "TEMPLATE_VIDEO_RECORD",
591 "TEMPLATE_VIDEO_SNAPSHOT",
592 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800593 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800594 };
595
Emilian Peevf4816702020-04-03 15:44:51 -0700596 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 camera_metadata_t *templateRequest = nullptr;
598 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700599 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800601 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 lines.append(" Not supported\n");
603 write(fd, lines.string(), lines.size());
604 } else {
605 write(fd, lines.string(), lines.size());
606 dump_indented_camera_metadata(templateRequest,
607 fd, /*verbosity*/2, /*indentation*/8);
608 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 }
611 }
612
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700613 mTagMonitor.dumpMonitoredMetadata(fd);
614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800616 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800620
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700621 if (gotLock) mLock.unlock();
622 if (gotInterfaceLock) mInterfaceLock.unlock();
623
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800624 return OK;
625}
626
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700627status_t Camera3Device::startWatchingTags(const String8 &tags) {
628 mTagMonitor.parseTagsToMonitor(tags);
629 return OK;
630}
631
632status_t Camera3Device::stopWatchingTags() {
633 mTagMonitor.disableMonitoring();
634 return OK;
635}
636
637status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
638 mTagMonitor.getLatestMonitoredTagEvents(out);
639 return OK;
640}
641
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800642const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
645 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700646 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 mStatus == STATUS_ERROR ?
648 "when in error state" : "before init");
649 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700650 if (physicalId.isEmpty()) {
651 return mDeviceInfo;
652 } else {
653 std::string id(physicalId.c_str());
654 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
655 return mPhysicalDeviceInfoMap.at(id);
656 } else {
657 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
658 return mDeviceInfo;
659 }
660 }
661}
662
663const CameraMetadata& Camera3Device::info() const {
664 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666}
667
Jianing Wei90e59c92014-03-12 18:29:36 -0700668status_t Camera3Device::checkStatusOkToCaptureLocked() {
669 switch (mStatus) {
670 case STATUS_ERROR:
671 CLOGE("Device has encountered a serious error");
672 return INVALID_OPERATION;
673 case STATUS_UNINITIALIZED:
674 CLOGE("Device not initialized");
675 return INVALID_OPERATION;
676 case STATUS_UNCONFIGURED:
677 case STATUS_CONFIGURED:
678 case STATUS_ACTIVE:
679 // OK
680 break;
681 default:
682 SET_ERR_L("Unexpected status: %d", mStatus);
683 return INVALID_OPERATION;
684 }
685 return OK;
686}
687
688status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000689 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700690 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700691 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700692 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700693 if (requestList == NULL) {
694 CLOGE("requestList cannot be NULL.");
695 return BAD_VALUE;
696 }
697
Jianing Weicb0652e2014-03-12 18:29:36 -0700698 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
701 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
702 ++metadataIt, ++surfaceMapIt) {
703 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700704 if (newRequest == 0) {
705 CLOGE("Can't create capture request");
706 return BAD_VALUE;
707 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700708
Shuzhen Wang9d066012016-09-30 11:30:20 -0700709 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700710 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700711
Jianing Weicb0652e2014-03-12 18:29:36 -0700712 // Setup burst Id and request Id
713 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800714 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
715 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700716 CLOGE("RequestID does not exist in metadata");
717 return BAD_VALUE;
718 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800719 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700720
Jianing Wei90e59c92014-03-12 18:29:36 -0700721 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700722
723 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700724 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700725 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
726 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
727 return BAD_VALUE;
728 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700729
730 // Setup batch size if this is a high speed video recording request.
731 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
732 auto firstRequest = requestList->begin();
733 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
734 if (outputStream->isVideoStream()) {
735 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800736 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700737 break;
738 }
739 }
740 }
741
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 return OK;
743}
744
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800745status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800746 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800747
Emilian Peevaebbe412018-01-15 13:53:24 +0000748 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000750 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800752 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753}
754
Emilian Peevaebbe412018-01-15 13:53:24 +0000755void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 std::list<const SurfaceMap>& surfaceMaps,
757 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 PhysicalCameraSettingsList requestList;
759 requestList.push_back({std::string(getId().string()), request});
760 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
762 SurfaceMap surfaceMap;
763 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
764 // With no surface list passed in, stream and surface will have 1-to-1
765 // mapping. So the surface index is 0 for each stream in the surfaceMap.
766 for (size_t i = 0; i < streams.count; i++) {
767 surfaceMap[streams.data.i32[i]].push_back(0);
768 }
769 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770}
771
Jianing Wei90e59c92014-03-12 18:29:36 -0700772status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 const std::list<const SurfaceMap> &surfaceMaps,
775 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700776 /*out*/
777 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700779 nsecs_t requestTimeNs = systemTime();
780
Jianing Wei90e59c92014-03-12 18:29:36 -0700781 Mutex::Autolock il(mInterfaceLock);
782 Mutex::Autolock l(mLock);
783
784 status_t res = checkStatusOkToCaptureLocked();
785 if (res != OK) {
786 // error logged by previous call
787 return res;
788 }
789
790 RequestList requestList;
791
Shuzhen Wang0129d522016-10-30 22:43:41 -0700792 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700793 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700794 if (res != OK) {
795 // error logged by previous call
796 return res;
797 }
798
799 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700802 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 }
804
805 if (res == OK) {
806 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
807 if (res != OK) {
808 SET_ERR_L("Can't transition to active in %f seconds!",
809 kActiveTimeout/1e9);
810 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 } else {
814 CLOGE("Cannot queue request. Impossible.");
815 return BAD_VALUE;
816 }
817
818 return res;
819}
820
Emilian Peevaebbe412018-01-15 13:53:24 +0000821status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700823 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 ATRACE_CALL();
825
Emilian Peevaebbe412018-01-15 13:53:24 +0000826 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828
Jianing Weicb0652e2014-03-12 18:29:36 -0700829status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
830 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836
Emilian Peevaebbe412018-01-15 13:53:24 +0000837 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700838 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839}
840
Emilian Peevaebbe412018-01-15 13:53:24 +0000841status_t Camera3Device::setStreamingRequestList(
842 const List<const PhysicalCameraSettingsList> &requestsList,
843 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 ATRACE_CALL();
845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700847}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800848
849sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 status_t res;
852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700853 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800854 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
855 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700857 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700858 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700862 } else if (mStatus == STATUS_UNCONFIGURED) {
863 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700864 CLOGE("No streams configured");
865 return NULL;
866 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800867 }
868
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800870 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800871}
872
Jianing Weicb0652e2014-03-12 18:29:36 -0700873status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700875 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 switch (mStatus) {
879 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700880 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700883 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700891 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 return INVALID_OPERATION;
893 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700895
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897}
898
899status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
900 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700901 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700903 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904}
905
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700906status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800907 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700908 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700910 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700911 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800912 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
913 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700914
915 status_t res;
916 bool wasActive = false;
917
918 switch (mStatus) {
919 case STATUS_ERROR:
920 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
921 return INVALID_OPERATION;
922 case STATUS_UNINITIALIZED:
923 ALOGE("%s: Device not initialized", __FUNCTION__);
924 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 case STATUS_UNCONFIGURED:
926 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700927 // OK
928 break;
929 case STATUS_ACTIVE:
930 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700931 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 return res;
935 }
936 wasActive = true;
937 break;
938 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700940 return INVALID_OPERATION;
941 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700942 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700943
944 if (mInputStream != 0) {
945 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
946 return INVALID_OPERATION;
947 }
948
949 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
950 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700951 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952
953 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800954 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955
956 *id = mNextStreamId++;
957
958 // Continue captures if active at start
959 if (wasActive) {
960 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100961 // Reuse current operating mode and session parameters for new stream config
962 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 if (res != OK) {
964 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
965 __FUNCTION__, mNextStreamId, strerror(-res), res);
966 return res;
967 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700968 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700969 }
970
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700972 return OK;
973}
974
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700975status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700976 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700977 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800978 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800979 const std::unordered_set<int32_t> &sensorPixelModesUsed,
980 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800981 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800982 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 ATRACE_CALL();
984
985 if (consumer == nullptr) {
986 ALOGE("%s: consumer must not be null", __FUNCTION__);
987 return BAD_VALUE;
988 }
989
990 std::vector<sp<Surface>> consumers;
991 consumers.push_back(consumer);
992
993 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800994 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800995 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800996 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800997}
998
999static bool isRawFormat(int format) {
1000 switch (format) {
1001 case HAL_PIXEL_FORMAT_RAW16:
1002 case HAL_PIXEL_FORMAT_RAW12:
1003 case HAL_PIXEL_FORMAT_RAW10:
1004 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1005 return true;
1006 default:
1007 return false;
1008 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001009}
1010
1011status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1012 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001013 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001014 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001015 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001016 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1017 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001018 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001019
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001020 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001021 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001022 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001024 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001025 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1026 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001027 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001028 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001029 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001030
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001031 status_t res;
1032 bool wasActive = false;
1033
1034 switch (mStatus) {
1035 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001036 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001037 return INVALID_OPERATION;
1038 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001039 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001040 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001041 case STATUS_UNCONFIGURED:
1042 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001043 // OK
1044 break;
1045 case STATUS_ACTIVE:
1046 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001047 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001048 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001049 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 return res;
1051 }
1052 wasActive = true;
1053 break;
1054 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001055 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001056 return INVALID_OPERATION;
1057 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001058 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001059
1060 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001061
Shuzhen Wang0129d522016-10-30 22:43:41 -07001062 if (consumers.size() == 0 && !hasDeferredConsumer) {
1063 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1064 return BAD_VALUE;
1065 }
Zhijun He5d677d12016-05-29 16:52:39 -07001066
Shuzhen Wang0129d522016-10-30 22:43:41 -07001067 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001068 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1069 return BAD_VALUE;
1070 }
1071
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001072 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1073 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1074 // be found in only one sensor pixel mode.
1075 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1076 return BAD_VALUE;
1077 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001078 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001079 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001080 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001081 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001082 if (blobBufferSize <= 0) {
1083 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1084 return BAD_VALUE;
1085 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001086 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1087 blobBufferSize = width * height;
1088 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001089 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001090 if (blobBufferSize <= 0) {
1091 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1092 return BAD_VALUE;
1093 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001094 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001096 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001097 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001098 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001099 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001100 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001101 bool maxResolution =
1102 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1103 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001104 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1105 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001106 if (rawOpaqueBufferSize <= 0) {
1107 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1108 return BAD_VALUE;
1109 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001110 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001111 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001112 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001113 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001114 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001115 } else if (isShared) {
1116 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1117 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001118 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001119 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001120 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001121 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001122 newStream = new Camera3OutputStream(mNextStreamId,
1123 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001124 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001125 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001126 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001127 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001128 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001129 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001130 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001131 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001132 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001133 }
Emilian Peev40ead602017-09-26 15:46:36 +01001134
1135 size_t consumerCount = consumers.size();
1136 for (size_t i = 0; i < consumerCount; i++) {
1137 int id = newStream->getSurfaceId(consumers[i]);
1138 if (id < 0) {
1139 SET_ERR_L("Invalid surface id");
1140 return BAD_VALUE;
1141 }
1142 if (surfaceIds != nullptr) {
1143 surfaceIds->push_back(id);
1144 }
1145 }
1146
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001147 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148
Emilian Peev08dd2452017-04-06 16:55:14 +01001149 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001150
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001151 newStream->setImageDumpMask(mImageDumpMask);
1152
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153 res = mOutputStreams.add(mNextStreamId, newStream);
1154 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001155 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001156 return res;
1157 }
1158
Shuzhen Wang316781a2020-08-18 18:11:01 -07001159 mSessionStatsBuilder.addStream(mNextStreamId);
1160
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001161 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001162 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163
1164 // Continue captures if active at start
1165 if (wasActive) {
1166 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001167 // Reuse current operating mode and session parameters for new stream config
1168 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001169 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001170 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1171 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001172 return res;
1173 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001176 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001178}
1179
Emilian Peev710c1422017-08-30 11:19:38 +01001180status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001182 if (nullptr == streamInfo) {
1183 return BAD_VALUE;
1184 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188 switch (mStatus) {
1189 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001190 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 return INVALID_OPERATION;
1192 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001193 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 case STATUS_UNCONFIGURED:
1196 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 case STATUS_ACTIVE:
1198 // OK
1199 break;
1200 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001201 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return INVALID_OPERATION;
1203 }
1204
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001205 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1206 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001207 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001208 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 }
1210
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001211 streamInfo->width = stream->getWidth();
1212 streamInfo->height = stream->getHeight();
1213 streamInfo->format = stream->getFormat();
1214 streamInfo->dataSpace = stream->getDataSpace();
1215 streamInfo->formatOverridden = stream->isFormatOverridden();
1216 streamInfo->originalFormat = stream->getOriginalFormat();
1217 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1218 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001219 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221}
1222
1223status_t Camera3Device::setStreamTransform(int id,
1224 int transform) {
1225 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 switch (mStatus) {
1230 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
1233 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001234 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 case STATUS_UNCONFIGURED:
1237 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 case STATUS_ACTIVE:
1239 // OK
1240 break;
1241 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001242 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return INVALID_OPERATION;
1244 }
1245
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001246 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1247 if (stream == nullptr) {
1248 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 return BAD_VALUE;
1250 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001251 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252}
1253
1254status_t Camera3Device::deleteStream(int id) {
1255 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001256 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 Mutex::Autolock l(mLock);
1258 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001260 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001261
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 // CameraDevice semantics require device to already be idle before
1263 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001265 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001266 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 }
1268
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001269 if (mStatus == STATUS_ERROR) {
1270 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1271 __FUNCTION__, mId.string());
1272 return -EBUSY;
1273 }
1274
Igor Murashkin2fba5842013-04-22 14:03:54 -07001275 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001276 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 if (mInputStream != NULL && id == mInputStream->getId()) {
1278 deletedStream = mInputStream;
1279 mInputStream.clear();
1280 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001281 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001282 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 return BAD_VALUE;
1284 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001285 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001286 }
1287
1288 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001289 if (stream != nullptr) {
1290 deletedStream = stream;
1291 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 }
1293
1294 // Free up the stream endpoint so that it can be used by some other stream
1295 res = deletedStream->disconnect();
1296 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 // fall through since we want to still list the stream as deleted.
1299 }
1300 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001301 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302
1303 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001304}
1305
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001306status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001307 ATRACE_CALL();
1308 ALOGV("%s: E", __FUNCTION__);
1309
1310 Mutex::Autolock il(mInterfaceLock);
1311 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001312
Emilian Peev811d2952018-05-25 11:08:40 +01001313 // In case the client doesn't include any session parameter, try a
1314 // speculative configuration using the values from the last cached
1315 // default request.
1316 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001317 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001318 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1319 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1320 mLastTemplateId);
1321 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1322 operatingMode);
1323 }
1324
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001325 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1326}
1327
1328status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1329 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001330 //Filter out any incoming session parameters
1331 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001332 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1333 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001334 CameraMetadata filteredParams(availableSessionKeys.count);
1335 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1336 filteredParams.getAndLock());
1337 set_camera_metadata_vendor_id(meta, mVendorTagId);
1338 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001339 if (availableSessionKeys.count > 0) {
1340 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1341 camera_metadata_ro_entry entry = params.find(
1342 availableSessionKeys.data.i32[i]);
1343 if (entry.count > 0) {
1344 filteredParams.update(entry);
1345 }
1346 }
1347 }
1348
1349 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001350}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001351
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001352status_t Camera3Device::getInputBufferProducer(
1353 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001354 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001355 Mutex::Autolock il(mInterfaceLock);
1356 Mutex::Autolock l(mLock);
1357
1358 if (producer == NULL) {
1359 return BAD_VALUE;
1360 } else if (mInputStream == NULL) {
1361 return INVALID_OPERATION;
1362 }
1363
1364 return mInputStream->getInputBufferProducer(producer);
1365}
1366
Emilian Peevf4816702020-04-03 15:44:51 -07001367status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001368 CameraMetadata *request) {
1369 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001370 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001371
Emilian Peevf4816702020-04-03 15:44:51 -07001372 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001373 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001374 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001375 return BAD_VALUE;
1376 }
1377
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001380 {
1381 Mutex::Autolock l(mLock);
1382 switch (mStatus) {
1383 case STATUS_ERROR:
1384 CLOGE("Device has encountered a serious error");
1385 return INVALID_OPERATION;
1386 case STATUS_UNINITIALIZED:
1387 CLOGE("Device is not initialized!");
1388 return INVALID_OPERATION;
1389 case STATUS_UNCONFIGURED:
1390 case STATUS_CONFIGURED:
1391 case STATUS_ACTIVE:
1392 // OK
1393 break;
1394 default:
1395 SET_ERR_L("Unexpected status: %d", mStatus);
1396 return INVALID_OPERATION;
1397 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001398
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399 if (!mRequestTemplateCache[templateId].isEmpty()) {
1400 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001401 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001402 return OK;
1403 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001404 }
1405
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001406 camera_metadata_t *rawRequest;
1407 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001408 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001409
1410 {
1411 Mutex::Autolock l(mLock);
1412 if (res == BAD_VALUE) {
1413 ALOGI("%s: template %d is not supported on this camera device",
1414 __FUNCTION__, templateId);
1415 return res;
1416 } else if (res != OK) {
1417 CLOGE("Unable to construct request template %d: %s (%d)",
1418 templateId, strerror(-res), res);
1419 return res;
1420 }
1421
1422 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1423 mRequestTemplateCache[templateId].acquire(rawRequest);
1424
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001425 // Override the template request with zoomRatioMapper
1426 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1427 &mRequestTemplateCache[templateId]);
1428 if (res != OK) {
1429 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1430 templateId, strerror(-res), res);
1431 return res;
1432 }
1433
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001434 // Fill in JPEG_QUALITY if not available
1435 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1436 static const uint8_t kDefaultJpegQuality = 95;
1437 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1438 &kDefaultJpegQuality, 1);
1439 }
1440
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001441 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001442 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001444 return OK;
1445}
1446
1447status_t Camera3Device::waitUntilDrained() {
1448 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001450 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001452
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001453 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001454}
1455
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001456status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 switch (mStatus) {
1458 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001459 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 ALOGV("%s: Already idle", __FUNCTION__);
1461 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001462 case STATUS_CONFIGURED:
1463 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 case STATUS_ERROR:
1465 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001466 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 break;
1468 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001469 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 return INVALID_OPERATION;
1471 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001472 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1473 maxExpectedDuration);
1474 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001475 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001476 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001477 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1478 res);
1479 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001480 return res;
1481}
1482
Ruben Brunk183f0562015-08-12 12:55:02 -07001483void Camera3Device::internalUpdateStatusLocked(Status status) {
1484 mStatus = status;
1485 mRecentStatusUpdates.add(mStatus);
1486 mStatusChanged.broadcast();
1487}
1488
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001489// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001490status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001491 if (mRequestThread.get() != nullptr) {
1492 mRequestThread->setPaused(true);
1493 } else {
1494 return NO_INIT;
1495 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001497 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1498 maxExpectedDuration);
1499 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 if (res != OK) {
1501 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001502 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 }
1504
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 return res;
1506}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001508// Resume after internalPauseAndWaitLocked
1509status_t Camera3Device::internalResumeLocked() {
1510 status_t res;
1511
1512 mRequestThread->setPaused(false);
1513
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001514 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1515 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1517 if (res != OK) {
1518 SET_ERR_L("Can't transition to active in %f seconds!",
1519 kActiveTimeout/1e9);
1520 }
1521 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523}
1524
Ruben Brunk183f0562015-08-12 12:55:02 -07001525status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001527
1528 size_t startIndex = 0;
1529 if (mStatusWaiters == 0) {
1530 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1531 // this status list
1532 mRecentStatusUpdates.clear();
1533 } else {
1534 // If other threads are waiting on updates to this status list, set the position of the
1535 // first element that this list will check rather than clearing the list.
1536 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 }
1538
Ruben Brunk183f0562015-08-12 12:55:02 -07001539 mStatusWaiters++;
1540
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001541 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001542 if (!active && mUseHalBufManager) {
1543 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001544 if (mStatus == STATUS_ACTIVE) {
1545 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001546 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001547 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001548 mRequestBufferSM.onWaitUntilIdle();
1549 }
1550
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 bool stateSeen = false;
1552 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001553 if (active == (mStatus == STATUS_ACTIVE)) {
1554 // Desired state is current
1555 break;
1556 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001557
1558 res = mStatusChanged.waitRelative(mLock, timeout);
1559 if (res != OK) break;
1560
Ruben Brunk183f0562015-08-12 12:55:02 -07001561 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1562 // transitions.
1563 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1564 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1565 __FUNCTION__);
1566
1567 // Encountered desired state since we began waiting
1568 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1570 stateSeen = true;
1571 break;
1572 }
1573 }
1574 } while (!stateSeen);
1575
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001576 if (signalPipelineDrain) {
1577 mRequestThread->resetPipelineDrain();
1578 }
1579
Ruben Brunk183f0562015-08-12 12:55:02 -07001580 mStatusWaiters--;
1581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 return res;
1583}
1584
1585
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001586status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001588 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001589
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001590 if (listener != NULL && mListener != NULL) {
1591 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1592 }
1593 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001594 mRequestThread->setNotificationListener(listener);
1595 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001596
1597 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001598}
1599
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001600bool Camera3Device::willNotify3A() {
1601 return false;
1602}
1603
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001604status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001605 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001606 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001608 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001609 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1610 if (st == std::cv_status::timeout) {
1611 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001612 }
1613 }
1614 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615}
1616
Jianing Weicb0652e2014-03-12 18:29:36 -07001617status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001619 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001620
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001621 if (mResultQueue.empty()) {
1622 return NOT_ENOUGH_DATA;
1623 }
1624
Jianing Weicb0652e2014-03-12 18:29:36 -07001625 if (frame == NULL) {
1626 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1627 return BAD_VALUE;
1628 }
1629
1630 CaptureResult &result = *(mResultQueue.begin());
1631 frame->mResultExtras = result.mResultExtras;
1632 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001633 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001634 mResultQueue.erase(mResultQueue.begin());
1635
1636 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001637}
1638
1639status_t Camera3Device::triggerAutofocus(uint32_t id) {
1640 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001643 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1644 // Mix-in this trigger into the next request and only the next request.
1645 RequestTrigger trigger[] = {
1646 {
1647 ANDROID_CONTROL_AF_TRIGGER,
1648 ANDROID_CONTROL_AF_TRIGGER_START
1649 },
1650 {
1651 ANDROID_CONTROL_AF_TRIGGER_ID,
1652 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001653 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001654 };
1655
1656 return mRequestThread->queueTrigger(trigger,
1657 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658}
1659
1660status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1661 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001662 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001664 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1665 // Mix-in this trigger into the next request and only the next request.
1666 RequestTrigger trigger[] = {
1667 {
1668 ANDROID_CONTROL_AF_TRIGGER,
1669 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1670 },
1671 {
1672 ANDROID_CONTROL_AF_TRIGGER_ID,
1673 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001674 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001675 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001677 return mRequestThread->queueTrigger(trigger,
1678 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001679}
1680
1681status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1682 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001684
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001685 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1686 // Mix-in this trigger into the next request and only the next request.
1687 RequestTrigger trigger[] = {
1688 {
1689 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1690 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1691 },
1692 {
1693 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1694 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001695 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001696 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001698 return mRequestThread->queueTrigger(trigger,
1699 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700}
1701
Jianing Weicb0652e2014-03-12 18:29:36 -07001702status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001703 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001704 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001706
Zhijun He7ef20392014-04-21 16:04:17 -07001707 {
1708 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001709
1710 // b/116514106 "disconnect()" can get called twice for the same device. The
1711 // camera device will not be initialized during the second run.
1712 if (mStatus == STATUS_UNINITIALIZED) {
1713 return OK;
1714 }
1715
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001716 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001717
1718 // Stop session and stream counter
1719 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001720 }
1721
Emilian Peev08dd2452017-04-06 16:55:14 +01001722 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001723}
1724
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001725status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001726 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1727}
1728
1729status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001730 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001731 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001732 Mutex::Autolock il(mInterfaceLock);
1733 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001734
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001735 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1736 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001737 CLOGE("Stream %d does not exist", streamId);
1738 return BAD_VALUE;
1739 }
1740
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001741 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001742 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001743 return BAD_VALUE;
1744 }
1745
1746 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001747 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001748 return BAD_VALUE;
1749 }
1750
Ruben Brunkc78ac262015-08-13 17:58:46 -07001751 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752}
1753
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001754status_t Camera3Device::tearDown(int streamId) {
1755 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001756 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001757 Mutex::Autolock il(mInterfaceLock);
1758 Mutex::Autolock l(mLock);
1759
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001760 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1761 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001762 CLOGE("Stream %d does not exist", streamId);
1763 return BAD_VALUE;
1764 }
1765
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001766 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1767 CLOGE("Stream %d is a target of a in-progress request", streamId);
1768 return BAD_VALUE;
1769 }
1770
1771 return stream->tearDown();
1772}
1773
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001774status_t Camera3Device::addBufferListenerForStream(int streamId,
1775 wp<Camera3StreamBufferListener> listener) {
1776 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001777 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001778 Mutex::Autolock il(mInterfaceLock);
1779 Mutex::Autolock l(mLock);
1780
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001781 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1782 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001783 CLOGE("Stream %d does not exist", streamId);
1784 return BAD_VALUE;
1785 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001786 stream->addBufferListener(listener);
1787
1788 return OK;
1789}
1790
Austin Borger4a870a32022-02-25 01:48:41 +00001791float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1792 camera_metadata_entry minDurations =
1793 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1794 for (size_t i = 0; i < minDurations.count; i += 4) {
1795 if (minDurations.data.i64[i] == stream->getFormat()
1796 && minDurations.data.i64[i+1] == stream->getWidth()
1797 && minDurations.data.i64[i+2] == stream->getHeight()) {
1798 int64_t minFrameDuration = minDurations.data.i64[i+3];
1799 return 1e9f / minFrameDuration;
1800 }
1801 }
1802 return 0.0f;
1803}
1804
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806 * Methods called by subclasses
1807 */
1808
1809void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001810 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001811 std::vector<int> streamIds;
1812 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001813 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001815 {
1816 // Need mLock to safely update state and synchronize to current
1817 // state of methods in flight.
1818 Mutex::Autolock l(mLock);
1819 // We can get various system-idle notices from the status tracker
1820 // while starting up. Only care about them if we've actually sent
1821 // in some requests recently.
1822 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1823 return;
1824 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001825 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1826 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001827 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828
1829 // Skip notifying listener if we're doing some user-transparent
1830 // state changes
1831 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001832
Austin Borger4a870a32022-02-25 01:48:41 +00001833 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1834 auto stream = mOutputStreams[i];
1835 if (stream.get() == nullptr) continue;
1836
1837 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1838 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1839
1840 // Populate stream statistics in case of Idle
1841 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001842 streamIds.push_back(stream->getId());
1843 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1844 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001845 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001846 if (camera3Stream != nullptr) {
1847 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001848 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001849 }
1850 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001851 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001852 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001853 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001854 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001855 }
1856 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001857 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001858
1859 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001861 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001862 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001864 status_t res = OK;
1865 if (listener != nullptr) {
1866 if (idle) {
1867 // Get session stats from the builder, and notify the listener.
1868 int64_t requestCount, resultErrorCount;
1869 bool deviceError;
1870 std::map<int, StreamStats> streamStatsMap;
1871 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1872 &deviceError, &streamStatsMap);
1873 for (size_t i = 0; i < streamIds.size(); i++) {
1874 int streamId = streamIds[i];
1875 auto stats = streamStatsMap.find(streamId);
1876 if (stats != streamStatsMap.end()) {
1877 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1878 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1879 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1880 streamStats[i].mHistogramType =
1881 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1882 streamStats[i].mHistogramBins.assign(
1883 stats->second.mCaptureLatencyBins.begin(),
1884 stats->second.mCaptureLatencyBins.end());
1885 streamStats[i].mHistogramCounts.assign(
1886 stats->second.mCaptureLatencyHistogram.begin(),
1887 stats->second.mCaptureLatencyHistogram.end());
1888 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001889 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001890 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1891 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001892 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001893 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001894 }
1895 if (res != OK) {
1896 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1897 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898 }
1899}
1900
Shuzhen Wang758c2152017-01-10 18:26:18 -08001901status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001902 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001903 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001904 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1905 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001906
1907 if (surfaceIds == nullptr) {
1908 return BAD_VALUE;
1909 }
1910
Zhijun He5d677d12016-05-29 16:52:39 -07001911 Mutex::Autolock il(mInterfaceLock);
1912 Mutex::Autolock l(mLock);
1913
Shuzhen Wang758c2152017-01-10 18:26:18 -08001914 if (consumers.size() == 0) {
1915 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001916 return BAD_VALUE;
1917 }
1918
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001919 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1920 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001921 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001922 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001923 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001924
1925 // isConsumerConfigurationDeferred will be off after setConsumers
1926 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001927 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001928 if (res != OK) {
1929 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1930 return res;
1931 }
1932
Emilian Peev40ead602017-09-26 15:46:36 +01001933 for (auto &consumer : consumers) {
1934 int id = stream->getSurfaceId(consumer);
1935 if (id < 0) {
1936 CLOGE("Invalid surface id!");
1937 return BAD_VALUE;
1938 }
1939 surfaceIds->push_back(id);
1940 }
1941
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001942 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001943 if (!stream->isConfiguring()) {
1944 CLOGE("Stream %d was already fully configured.", streamId);
1945 return INVALID_OPERATION;
1946 }
Zhijun He5d677d12016-05-29 16:52:39 -07001947
Shuzhen Wang0129d522016-10-30 22:43:41 -07001948 res = stream->finishConfiguration();
1949 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001950 // If finishConfiguration fails due to abandoned surface, do not set
1951 // device to error state.
1952 bool isSurfaceAbandoned =
1953 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1954 if (!isSurfaceAbandoned) {
1955 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1956 stream->getId(), strerror(-res), res);
1957 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001958 return res;
1959 }
Zhijun He5d677d12016-05-29 16:52:39 -07001960 }
1961
1962 return OK;
1963}
1964
Emilian Peev40ead602017-09-26 15:46:36 +01001965status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1966 const std::vector<OutputStreamInfo> &outputInfo,
1967 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1968 Mutex::Autolock il(mInterfaceLock);
1969 Mutex::Autolock l(mLock);
1970
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1972 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001973 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001974 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001975 }
1976
1977 for (const auto &it : removedSurfaceIds) {
1978 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1979 CLOGE("Shared surface still part of a pending request!");
1980 return -EBUSY;
1981 }
1982 }
1983
Emilian Peev40ead602017-09-26 15:46:36 +01001984 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1985 if (res != OK) {
1986 CLOGE("Stream %d failed to update stream (error %d %s) ",
1987 streamId, res, strerror(-res));
1988 if (res == UNKNOWN_ERROR) {
1989 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1990 __FUNCTION__);
1991 }
1992 return res;
1993 }
1994
1995 return res;
1996}
1997
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001998status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1999 Mutex::Autolock il(mInterfaceLock);
2000 Mutex::Autolock l(mLock);
2001
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002002 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2003 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002004 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2005 return BAD_VALUE;
2006 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002007
2008 if (dropping) {
2009 mSessionStatsBuilder.stopCounter(streamId);
2010 } else {
2011 mSessionStatsBuilder.startCounter(streamId);
2012 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002013 return stream->dropBuffers(dropping);
2014}
2015
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002016/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002017 * Camera3Device private methods
2018 */
2019
2020sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002021 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002023
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002024 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002025 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002026
2027 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002028 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002029 if (inputStreams.count > 0) {
2030 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002031 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002032 CLOGE("Request references unknown input stream %d",
2033 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002034 return NULL;
2035 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002036
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002038 SET_ERR_L("%s: input stream %d is not configured!",
2039 __FUNCTION__, mInputStream->getId());
2040 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002042 // Check if stream prepare is blocking requests.
2043 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044 CLOGE("Request references an input stream that's being prepared!");
2045 return NULL;
2046 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002047
2048 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002049 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002050 }
2051
2052 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002053 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002054 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002055 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 return NULL;
2057 }
2058
2059 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002060 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2061 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002062 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002063 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 return NULL;
2065 }
Zhijun He5d677d12016-05-29 16:52:39 -07002066 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002067 auto iter = surfaceMap.find(streams.data.i32[i]);
2068 if (iter != surfaceMap.end()) {
2069 const std::vector<size_t>& surfaces = iter->second;
2070 for (const auto& surface : surfaces) {
2071 if (stream->isConsumerConfigurationDeferred(surface)) {
2072 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2073 "due to deferred consumer", stream->getId(), surface);
2074 return NULL;
2075 }
2076 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002077 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002078 }
2079
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002081 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2082 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002084 // Check if stream prepare is blocking requests.
2085 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002086 CLOGE("Request references an output stream that's being prepared!");
2087 return NULL;
2088 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002089
2090 newRequest->mOutputStreams.push(stream);
2091 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002092 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002093 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002095 auto rotateAndCropEntry =
2096 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2097 if (rotateAndCropEntry.count > 0 &&
2098 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2099 newRequest->mRotateAndCropAuto = true;
2100 } else {
2101 newRequest->mRotateAndCropAuto = false;
2102 }
2103
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002104 auto zoomRatioEntry =
2105 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2106 if (zoomRatioEntry.count > 0 &&
2107 zoomRatioEntry.data.f[0] == 1.0f) {
2108 newRequest->mZoomRatioIs1x = true;
2109 } else {
2110 newRequest->mZoomRatioIs1x = false;
2111 }
2112
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002113 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002114 for (auto& settings : newRequest->mSettingsList) {
2115 auto testPatternModeEntry =
2116 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2117 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2118 testPatternModeEntry.data.i32[0] :
2119 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002120
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002121 auto testPatternDataEntry =
2122 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2123 if (testPatternDataEntry.count >= 4) {
2124 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2125 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2126 } else {
2127 settings.mOriginalTestPatternData[0] = 0;
2128 settings.mOriginalTestPatternData[1] = 0;
2129 settings.mOriginalTestPatternData[2] = 0;
2130 settings.mOriginalTestPatternData[3] = 0;
2131 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002132 }
2133 }
2134
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002136}
2137
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002138void Camera3Device::cancelStreamsConfigurationLocked() {
2139 int res = OK;
2140 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2141 res = mInputStream->cancelConfiguration();
2142 if (res != OK) {
2143 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2144 mInputStream->getId(), strerror(-res), res);
2145 }
2146 }
2147
2148 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002149 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002150 if (outputStream->isConfiguring()) {
2151 res = outputStream->cancelConfiguration();
2152 if (res != OK) {
2153 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2154 outputStream->getId(), strerror(-res), res);
2155 }
2156 }
2157 }
2158
2159 // Return state to that at start of call, so that future configures
2160 // properly clean things up
2161 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2162 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002163
2164 res = mPreparerThread->resume();
2165 if (res != OK) {
2166 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2167 }
2168}
2169
Emilian Peev0d0191e2020-04-21 17:01:18 -07002170bool Camera3Device::checkAbandonedStreamsLocked() {
2171 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2172 return true;
2173 }
2174
2175 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2176 auto stream = mOutputStreams[i];
2177 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2178 return true;
2179 }
2180 }
2181
2182 return false;
2183}
2184
Emilian Peev3bead5f2020-05-28 17:29:08 -07002185bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002186 ATRACE_CALL();
2187 bool ret = false;
2188
Shuzhen Wang316781a2020-08-18 18:11:01 -07002189 nsecs_t startTime = systemTime();
2190
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002191 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002192 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2193
2194 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002195 if (checkAbandonedStreamsLocked()) {
2196 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2197 __FUNCTION__);
2198 return true;
2199 }
2200
Emilian Peev3bead5f2020-05-28 17:29:08 -07002201 status_t rc = NO_ERROR;
2202 bool markClientActive = false;
2203 if (mStatus == STATUS_ACTIVE) {
2204 markClientActive = true;
2205 mPauseStateNotify = true;
2206 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2207
2208 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2209 }
2210
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002211 if (rc == NO_ERROR) {
2212 mNeedConfig = true;
2213 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2214 if (rc == NO_ERROR) {
2215 ret = true;
2216 mPauseStateNotify = false;
2217 //Moving to active state while holding 'mLock' is important.
2218 //There could be pending calls to 'create-/deleteStream' which
2219 //will trigger another stream configuration while the already
2220 //present streams end up with outstanding buffers that will
2221 //not get drained.
2222 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002223 } else if (rc == DEAD_OBJECT) {
2224 // DEAD_OBJECT can be returned if either the consumer surface is
2225 // abandoned, or the HAL has died.
2226 // - If the HAL has died, configureStreamsLocked call will set
2227 // device to error state,
2228 // - If surface is abandoned, we should not set device to error
2229 // state.
2230 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002231 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002232 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002233 }
2234 } else {
2235 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2236 }
2237
Shuzhen Wang316781a2020-08-18 18:11:01 -07002238 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2239 ns2ms(systemTime() - startTime));
2240
Emilian Peev3bead5f2020-05-28 17:29:08 -07002241 if (markClientActive) {
2242 mStatusTracker->markComponentActive(clientStatusId);
2243 }
2244
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002245 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002246}
2247
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002248status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002249 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002250 ATRACE_CALL();
2251 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002252
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002253 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002254 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255 return INVALID_OPERATION;
2256 }
2257
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002258 if (operatingMode < 0) {
2259 CLOGE("Invalid operating mode: %d", operatingMode);
2260 return BAD_VALUE;
2261 }
2262
2263 bool isConstrainedHighSpeed =
2264 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2265 operatingMode;
2266
2267 if (mOperatingMode != operatingMode) {
2268 mNeedConfig = true;
2269 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2270 mOperatingMode = operatingMode;
2271 }
2272
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002273 // In case called from configureStreams, abort queued input buffers not belonging to
2274 // any pending requests.
2275 if (mInputStream != NULL && notifyRequestThread) {
2276 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002277 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002278 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002279 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002280 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002281 if (res != OK) {
2282 // Exhausted acquiring all input buffers.
2283 break;
2284 }
2285
Emilian Peevf4816702020-04-03 15:44:51 -07002286 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002287 res = mInputStream->returnInputBuffer(inputBuffer);
2288 if (res != OK) {
2289 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2290 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2291 }
2292 }
2293 }
2294
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002295 if (!mNeedConfig) {
2296 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2297 return OK;
2298 }
2299
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002300 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002301 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002302 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2303 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002304 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002305 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002306 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002307 }
2308
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002309 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002310 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002312 mPreparerThread->pause();
2313
Emilian Peevf4816702020-04-03 15:44:51 -07002314 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002315 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002317 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318
Emilian Peevf4816702020-04-03 15:44:51 -07002319 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002321 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002322
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323
2324 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002325 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326 inputStream = mInputStream->startConfiguration();
2327 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002328 CLOGE("Can't start input stream configuration");
2329 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002330 return INVALID_OPERATION;
2331 }
2332 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002333
2334 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002335 }
2336
Shuzhen Wang99080502021-03-07 21:08:20 -08002337 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002338 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002339 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002340
2341 // Don't configure bidi streams twice, nor add them twice to the list
2342 if (mOutputStreams[i].get() ==
2343 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2344
2345 config.num_streams--;
2346 continue;
2347 }
2348
Emilian Peevf4816702020-04-03 15:44:51 -07002349 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002350 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002352 CLOGE("Can't start output stream configuration");
2353 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 return INVALID_OPERATION;
2355 }
2356 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002357
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002358 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002359 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2360 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002361 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2362 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002363 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2364 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002365 } else if (outputStream->data_space ==
2366 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2367 bufferSizes[k] = outputStream->width * outputStream->height;
2368 } else {
2369 ALOGW("%s: Blob dataSpace %d not supported",
2370 __FUNCTION__, outputStream->data_space);
2371 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002372 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002373
2374 if (mOutputStreams[i]->isMultiResolution()) {
2375 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2376 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2377 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2378 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002379
2380 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2381 composerSurfacePresent = true;
2382 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002383 }
2384
2385 config.streams = streams.editArray();
2386
2387 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002388 // max_buffers, usage, and priv fields, as well as data_space and format
2389 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002390
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002391 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002392 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002393 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002394
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002395 if (res == BAD_VALUE) {
2396 // HAL rejected this set of streams as unsupported, clean up config
2397 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002398 CLOGE("Set of requested inputs/outputs not supported by HAL");
2399 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002400 return BAD_VALUE;
2401 } else if (res != OK) {
2402 // Some other kind of error from configure_streams - this is not
2403 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002404 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2405 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002406 return res;
2407 }
2408
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002409 // Finish all stream configuration immediately.
2410 // TODO: Try to relax this later back to lazy completion, which should be
2411 // faster
2412
Igor Murashkin073f8572013-05-02 14:59:28 -07002413 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002414 bool streamReConfigured = false;
2415 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002416 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002417 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002418 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002419 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002420 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2421 return DEAD_OBJECT;
2422 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002423 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002424 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002425 if (streamReConfigured) {
2426 mInterface->onStreamReConfigured(mInputStream->getId());
2427 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002428 }
2429
2430 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002431 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002432 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002433 bool streamReConfigured = false;
2434 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002435 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002436 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002437 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002438 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002439 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2440 return DEAD_OBJECT;
2441 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002442 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002443 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002444 if (streamReConfigured) {
2445 mInterface->onStreamReConfigured(outputStream->getId());
2446 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002447 }
2448 }
2449
Emilian Peeve23f1d92021-09-20 14:56:01 -07002450 mRequestThread->setComposerSurface(composerSurfacePresent);
2451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452 // Request thread needs to know to avoid using repeat-last-settings protocol
2453 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002454 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002455 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2456 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002458
Zhijun He90f7c372016-08-16 16:19:43 -07002459 char value[PROPERTY_VALUE_MAX];
2460 property_get("camera.fifo.disable", value, "0");
2461 int32_t disableFifo = atoi(value);
2462 if (disableFifo != 1) {
2463 // Boost priority of request thread to SCHED_FIFO.
2464 pid_t requestThreadTid = mRequestThread->getTid();
2465 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002466 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002467 if (res != OK) {
2468 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2469 strerror(-res), res);
2470 } else {
2471 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2472 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002473 }
2474
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002475 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002476 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2477 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2478 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2479 sessionParams.unlock(newSessionParams);
2480 mSessionParams.unlock(currentSessionParams);
2481 if (updateSessionParams) {
2482 mSessionParams = sessionParams;
2483 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002484
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002485 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002486
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002487 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002488 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002489
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002490 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002491
Zhijun He0a210512014-07-24 13:45:15 -07002492 // tear down the deleted streams after configure streams.
2493 mDeletedStreams.clear();
2494
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002495 auto rc = mPreparerThread->resume();
2496 if (rc != OK) {
2497 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2498 return rc;
2499 }
2500
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002501 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002502 mRequestBufferSM.onStreamsConfigured();
2503 }
2504
Cliff Wu3b268182021-07-06 15:44:43 +08002505 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002506 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002507 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002508 // configure the injection streams.
2509 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002510 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002511 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2512 res = mInjectionMethods->injectCamera(config, bufferSizes);
2513 if (res != OK) {
2514 ALOGE("Can't finish inject camera process!");
2515 return res;
2516 }
Cliff Wu3b268182021-07-06 15:44:43 +08002517 } else {
2518 // First run configureStreamsLocked() and then call injectCamera() case:
2519 // If the stream configuration has been completed and camera deive is active, but the
2520 // injection camera has not been injected yet, we need to store the stream configuration of
2521 // the internal camera (because the stream configuration of the injection camera is based
2522 // on the internal camera). When injecting occurs later, this configuration can be used by
2523 // the injection camera.
2524 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2525 " injection camera has not been injected yet.", __FUNCTION__);
2526 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002527 }
2528
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002530}
2531
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002532status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002533 ATRACE_CALL();
2534 status_t res;
2535
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002536 if (mFakeStreamId != NO_STREAM) {
2537 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002538 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002539 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002540 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002541 return INVALID_OPERATION;
2542 }
2543
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002544 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002545
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002546 sp<Camera3OutputStreamInterface> fakeStream =
2547 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002549 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002550 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002552 return res;
2553 }
2554
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 mNextStreamId++;
2557
2558 return OK;
2559}
2560
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002561status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002562 ATRACE_CALL();
2563 status_t res;
2564
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002565 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002566 if (mOutputStreams.size() == 1) return OK;
2567
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002568 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002569
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002570 // Ok, have a fake stream and there's at least one other output stream,
2571 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002572
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002573 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002574 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002575 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002576 return INVALID_OPERATION;
2577 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002578 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002579
2580 // Free up the stream endpoint so that it can be used by some other stream
2581 res = deletedStream->disconnect();
2582 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002583 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584 // fall through since we want to still list the stream as deleted.
2585 }
2586 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002587 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002588
2589 return res;
2590}
2591
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002592void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002593 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002594 Mutex::Autolock l(mLock);
2595 va_list args;
2596 va_start(args, fmt);
2597
2598 setErrorStateLockedV(fmt, args);
2599
2600 va_end(args);
2601}
2602
2603void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002604 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002605 Mutex::Autolock l(mLock);
2606 setErrorStateLockedV(fmt, args);
2607}
2608
2609void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2610 va_list args;
2611 va_start(args, fmt);
2612
2613 setErrorStateLockedV(fmt, args);
2614
2615 va_end(args);
2616}
2617
2618void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002619 // Print out all error messages to log
2620 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002621 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002622
2623 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002624 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002625
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002626 mErrorCause = errorCause;
2627
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002628 if (mRequestThread != nullptr) {
2629 mRequestThread->setPaused(true);
2630 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002631 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002632
2633 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002634 sp<NotificationListener> listener = mListener.promote();
2635 if (listener != NULL) {
2636 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002637 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002638 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002639 }
2640
2641 // Save stack trace. View by dumping it later.
2642 CameraTraces::saveTrace();
2643 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002644}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645
2646/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002647 * In-flight request management
2648 */
2649
Jianing Weicb0652e2014-03-12 18:29:36 -07002650status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002651 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002652 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002653 const std::set<std::set<String8>>& physicalCameraIds,
2654 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2655 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002656 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002657 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002658 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002659
2660 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002661 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002662 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002663 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002664 if (res < 0) return res;
2665
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002666 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002667 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2668 // avoid a deadlock during reprocess requests.
2669 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002670 if (mStatusTracker != nullptr) {
2671 mStatusTracker->markComponentActive(mInFlightStatusId);
2672 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002673 }
2674
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002675 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002676 return OK;
2677}
2678
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002679void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002680 // Indicate idle inFlightMap to the status tracker
2681 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002682 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002683 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2684 // avoid a deadlock during reprocess requests.
2685 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002686 if (mStatusTracker != nullptr) {
2687 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2688 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002689 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002690 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002691}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002692
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002693void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002694 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002695 // something has likely gone wrong. This might still be legit only if application send in
2696 // a long burst of long exposure requests.
2697 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2698 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2699 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2700 mInFlightMap.size(), mExpectedInflightDuration);
2701 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2702 kInFlightWarnLimitHighSpeed) {
2703 CLOGW("In-flight list too large for high speed configuration: %zu,"
2704 "total inflight duration %" PRIu64,
2705 mInFlightMap.size(), mExpectedInflightDuration);
2706 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002707 }
2708}
2709
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002710void Camera3Device::onInflightMapFlushedLocked() {
2711 mExpectedInflightDuration = 0;
2712}
2713
2714void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002715 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002716 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2717 mInFlightMap.removeItemsAt(idx, 1);
2718
2719 onInflightEntryRemovedLocked(duration);
2720}
2721
2722
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002723void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002724 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002725 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002726 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002727 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002728 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002729 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002730
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002731 FlushInflightReqStates states {
2732 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002733 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002734
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002735 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002736}
2737
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002738CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002739 ALOGV("%s", __FUNCTION__);
2740
Igor Murashkin1e479c02013-09-06 16:55:14 -07002741 CameraMetadata retVal;
2742
2743 if (mRequestThread != NULL) {
2744 retVal = mRequestThread->getLatestRequest();
2745 }
2746
Igor Murashkin1e479c02013-09-06 16:55:14 -07002747 return retVal;
2748}
2749
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002750void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002751 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002752 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002753 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2754 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002755
2756 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002757 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002758}
2759
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002760void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002761 std::vector<native_handle_t*> *handles, bool closeFd) {
2762 if (handles == nullptr) {
2763 return;
2764 }
2765 if (closeFd) {
2766 for (auto& handle : *handles) {
2767 native_handle_close(handle);
2768 }
2769 }
2770 for (auto& handle : *handles) {
2771 native_handle_delete(handle);
2772 }
2773 handles->clear();
2774 return;
2775}
2776
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002777/**
2778 * HalInterface inner class methods
2779 */
2780
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002781void Camera3Device::HalInterface::getInflightBufferKeys(
2782 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002783 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002784 return;
2785}
2786
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002787void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2788 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002789 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002790 return;
2791}
2792
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002793bool Camera3Device::HalInterface::verifyBufferIds(
2794 int32_t streamId, std::vector<uint64_t>& bufIds) {
2795 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002796}
2797
2798status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002799 int32_t frameNumber, int32_t streamId,
2800 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002801 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002802}
2803
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002804status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002805 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002806 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002807}
2808
2809// Find and pop a buffer_handle_t based on bufferId
2810status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002811 uint64_t bufferId,
2812 /*out*/ buffer_handle_t** buffer,
2813 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002814 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002815}
2816
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002817std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2818 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002819 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002820}
2821
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002822uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2823 const native_handle_t* handle) {
2824 return mBufferRecords.removeOneBufferCache(streamId, handle);
2825}
2826
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002827void Camera3Device::HalInterface::onBufferFreed(
2828 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002829 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2830 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2831 if (bufferId != BUFFER_ID_NO_BUFFER) {
2832 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002833 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002834}
2835
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002836void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002837 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2838 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2839 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002840 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2841 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002842}
2843
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002844/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002845 * RequestThread inner class methods
2846 */
2847
2848Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002849 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002850 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002851 bool useHalBufManager,
2852 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002853 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002854 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002855 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002856 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002857 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002858 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002859 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002860 mReconfigured(false),
2861 mDoPause(false),
2862 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002863 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002864 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002865 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002866 mCurrentAfTriggerId(0),
2867 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002868 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002869 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002870 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002871 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002872 mRepeatingLastFrameNumber(
2873 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002874 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002875 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002876 mRequestLatency(kRequestLatencyBinSize),
2877 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002878 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002879 mUseHalBufManager(useHalBufManager),
2880 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002881 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002882}
2883
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002884Camera3Device::RequestThread::~RequestThread() {}
2885
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002886void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002887 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002888 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002889 Mutex::Autolock l(mRequestLock);
2890 mListener = listener;
2891}
2892
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002893void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002894 const CameraMetadata& sessionParams,
2895 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002896 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002897 Mutex::Autolock l(mRequestLock);
2898 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002899 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002900 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002901 // Prepare video stream for high speed recording.
2902 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002903 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002904}
2905
Jianing Wei90e59c92014-03-12 18:29:36 -07002906status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002907 List<sp<CaptureRequest> > &requests,
2908 /*out*/
2909 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002910 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002911 Mutex::Autolock l(mRequestLock);
2912 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2913 ++it) {
2914 mRequestQueue.push_back(*it);
2915 }
2916
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002917 if (lastFrameNumber != NULL) {
2918 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2919 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2920 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2921 *lastFrameNumber);
2922 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002923
Jianing Wei90e59c92014-03-12 18:29:36 -07002924 unpauseForNewRequests();
2925
2926 return OK;
2927}
2928
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002929
2930status_t Camera3Device::RequestThread::queueTrigger(
2931 RequestTrigger trigger[],
2932 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002933 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002934 Mutex::Autolock l(mTriggerMutex);
2935 status_t ret;
2936
2937 for (size_t i = 0; i < count; ++i) {
2938 ret = queueTriggerLocked(trigger[i]);
2939
2940 if (ret != OK) {
2941 return ret;
2942 }
2943 }
2944
2945 return OK;
2946}
2947
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2949 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002950 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002951 if (d != nullptr) return d->mId;
2952 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002953}
2954
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002955status_t Camera3Device::RequestThread::queueTriggerLocked(
2956 RequestTrigger trigger) {
2957
2958 uint32_t tag = trigger.metadataTag;
2959 ssize_t index = mTriggerMap.indexOfKey(tag);
2960
2961 switch (trigger.getTagType()) {
2962 case TYPE_BYTE:
2963 // fall-through
2964 case TYPE_INT32:
2965 break;
2966 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002967 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2968 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002969 return INVALID_OPERATION;
2970 }
2971
2972 /**
2973 * Collect only the latest trigger, since we only have 1 field
2974 * in the request settings per trigger tag, and can't send more than 1
2975 * trigger per request.
2976 */
2977 if (index != NAME_NOT_FOUND) {
2978 mTriggerMap.editValueAt(index) = trigger;
2979 } else {
2980 mTriggerMap.add(tag, trigger);
2981 }
2982
2983 return OK;
2984}
2985
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002986status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002987 const RequestList &requests,
2988 /*out*/
2989 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002990 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002991 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002992 if (lastFrameNumber != NULL) {
2993 *lastFrameNumber = mRepeatingLastFrameNumber;
2994 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002995 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002996 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002997 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2998 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002999
3000 unpauseForNewRequests();
3001
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003002 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003003 return OK;
3004}
3005
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003006bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003007 if (mRepeatingRequests.empty()) {
3008 return false;
3009 }
3010 int32_t requestId = requestIn->mResultExtras.requestId;
3011 const RequestList &repeatRequests = mRepeatingRequests;
3012 // All repeating requests are guaranteed to have same id so only check first quest
3013 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3014 return (firstRequest->mResultExtras.requestId == requestId);
3015}
3016
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003017status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003018 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003019 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003020 return clearRepeatingRequestsLocked(lastFrameNumber);
3021
3022}
3023
3024status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003025 std::vector<int32_t> streamIds;
3026 for (const auto& request : mRepeatingRequests) {
3027 for (const auto& stream : request->mOutputStreams) {
3028 streamIds.push_back(stream->getId());
3029 }
3030 }
3031
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003032 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003033 if (lastFrameNumber != NULL) {
3034 *lastFrameNumber = mRepeatingLastFrameNumber;
3035 }
Emilian Peev2295df72021-11-12 18:14:10 -08003036
3037 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3038
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003039 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003040 return OK;
3041}
3042
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003043status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003044 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003045 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003046 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003047 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003048
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003049 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003050
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003051 // Send errors for all requests pending in the request queue, including
3052 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003053 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003054 if (listener != NULL) {
3055 for (RequestList::iterator it = mRequestQueue.begin();
3056 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003057 // Abort the input buffers for reprocess requests.
3058 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003059 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003060 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003061 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003062 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003063 if (res != OK) {
3064 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3065 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3066 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003067 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003068 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3069 if (res != OK) {
3070 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3071 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3072 }
3073 }
3074 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003075 // Set the frame number this request would have had, if it
3076 // had been submitted; this frame number will not be reused.
3077 // The requestId and burstId fields were set when the request was
3078 // submitted originally (in convertMetadataListToRequestListLocked)
3079 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003081 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003082 }
3083 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003084 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003085
3086 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003087 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003088 if (lastFrameNumber != NULL) {
3089 *lastFrameNumber = mRepeatingLastFrameNumber;
3090 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003091 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003092 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003093 return OK;
3094}
3095
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003096status_t Camera3Device::RequestThread::flush() {
3097 ATRACE_CALL();
3098 Mutex::Autolock l(mFlushLock);
3099
Emilian Peev08dd2452017-04-06 16:55:14 +01003100 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003101}
3102
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003103void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003104 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003105 Mutex::Autolock l(mPauseLock);
3106 mDoPause = paused;
3107 mDoPauseSignal.signal();
3108}
3109
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003110status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3111 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003112 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003113 Mutex::Autolock l(mLatestRequestMutex);
3114 status_t res;
3115 while (mLatestRequestId != requestId) {
3116 nsecs_t startTime = systemTime();
3117
3118 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3119 if (res != OK) return res;
3120
3121 timeout -= (systemTime() - startTime);
3122 }
3123
3124 return OK;
3125}
3126
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003127void Camera3Device::RequestThread::requestExit() {
3128 // Call parent to set up shutdown
3129 Thread::requestExit();
3130 // The exit from any possible waits
3131 mDoPauseSignal.signal();
3132 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003133
3134 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3135 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003136}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003137
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003138void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003139 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003140 bool surfaceAbandoned = false;
3141 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003142 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003143 {
3144 Mutex::Autolock l(mRequestLock);
3145 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3146 // repeating requests.
3147 for (const auto& request : mRepeatingRequests) {
3148 for (const auto& s : request->mOutputStreams) {
3149 if (s->isAbandoned()) {
3150 surfaceAbandoned = true;
3151 clearRepeatingRequestsLocked(&lastFrameNumber);
3152 break;
3153 }
3154 }
3155 if (surfaceAbandoned) {
3156 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003157 }
3158 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003159 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003160 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003161
3162 if (listener != NULL && surfaceAbandoned) {
3163 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003164 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003165}
3166
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003167bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003168 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003169 status_t res;
3170 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003171 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003172 uint32_t numRequestProcessed = 0;
3173 for (size_t i = 0; i < batchSize; i++) {
3174 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003175 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003176 }
3177
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003178 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3179
3180 bool triggerRemoveFailed = false;
3181 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3182 for (size_t i = 0; i < numRequestProcessed; i++) {
3183 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3184 nextRequest.submitted = true;
3185
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003186 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003187
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003188 if (!triggerRemoveFailed) {
3189 // Remove any previously queued triggers (after unlock)
3190 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3191 if (removeTriggerRes != OK) {
3192 triggerRemoveFailed = true;
3193 triggerFailedRequest = nextRequest;
3194 }
3195 }
3196 }
3197
3198 if (triggerRemoveFailed) {
3199 SET_ERR("RequestThread: Unable to remove triggers "
3200 "(capture request %d, HAL device: %s (%d)",
3201 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3202 cleanUpFailedRequests(/*sendRequestError*/ false);
3203 return false;
3204 }
3205
3206 if (res != OK) {
3207 // Should only get a failure here for malformed requests or device-level
3208 // errors, so consider all errors fatal. Bad metadata failures should
3209 // come through notify.
3210 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3211 mNextRequests[numRequestProcessed].halRequest.frame_number,
3212 strerror(-res), res);
3213 cleanUpFailedRequests(/*sendRequestError*/ false);
3214 return false;
3215 }
3216 return true;
3217}
3218
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003219nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3220 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3221 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3222 find_camera_metadata_ro_entry(request,
3223 ANDROID_CONTROL_AE_MODE,
3224 &e);
3225 if (e.count == 0) return maxExpectedDuration;
3226
3227 switch (e.data.u8[0]) {
3228 case ANDROID_CONTROL_AE_MODE_OFF:
3229 find_camera_metadata_ro_entry(request,
3230 ANDROID_SENSOR_EXPOSURE_TIME,
3231 &e);
3232 if (e.count > 0) {
3233 maxExpectedDuration = e.data.i64[0];
3234 }
3235 find_camera_metadata_ro_entry(request,
3236 ANDROID_SENSOR_FRAME_DURATION,
3237 &e);
3238 if (e.count > 0) {
3239 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3240 }
3241 break;
3242 default:
3243 find_camera_metadata_ro_entry(request,
3244 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3245 &e);
3246 if (e.count > 1) {
3247 maxExpectedDuration = 1e9 / e.data.u8[0];
3248 }
3249 break;
3250 }
3251
3252 return maxExpectedDuration;
3253}
3254
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003255bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3256 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3257 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3258 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3259 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3260 return true;
3261 }
3262
3263 return false;
3264}
3265
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003266void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3267 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003268 camera_capture_request_t& halRequest = nextRequest.halRequest;
3269 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003270 Mutex::Autolock al(mLatestRequestMutex);
3271
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003273 mLatestRequest.acquire(cloned);
3274
3275 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003276 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3277 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3278 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003279 CameraMetadata(cloned));
3280 }
3281
3282 sp<Camera3Device> parent = mParent.promote();
3283 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003284 int32_t inputStreamId = -1;
3285 if (halRequest.input_buffer != nullptr) {
3286 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3287 }
3288
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003289 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003290 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003291 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3292 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003293 }
3294 }
3295
Shuzhen Wang83bff122020-11-20 15:51:39 -08003296 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003297 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003298 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003299 }
3300
Shuzhen Wang83bff122020-11-20 15:51:39 -08003301 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003302}
3303
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003304bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3305 ATRACE_CALL();
3306 bool updatesDetected = false;
3307
Emilian Peev4ec17882019-01-24 17:16:58 -08003308 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003309 for (auto tag : mSessionParamKeys) {
3310 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003311 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003312
3313 if (entry.count > 0) {
3314 bool isDifferent = false;
3315 if (lastEntry.count > 0) {
3316 // Have a last value, compare to see if changed
3317 if (lastEntry.type == entry.type &&
3318 lastEntry.count == entry.count) {
3319 // Same type and count, compare values
3320 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3321 size_t entryBytes = bytesPerValue * lastEntry.count;
3322 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3323 if (cmp != 0) {
3324 isDifferent = true;
3325 }
3326 } else {
3327 // Count or type has changed
3328 isDifferent = true;
3329 }
3330 } else {
3331 // No last entry, so always consider to be different
3332 isDifferent = true;
3333 }
3334
3335 if (isDifferent) {
3336 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003337 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3338 updatesDetected = true;
3339 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003340 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003341 }
3342 } else if (lastEntry.count > 0) {
3343 // Value has been removed
3344 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003345 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003346 updatesDetected = true;
3347 }
3348 }
3349
Emilian Peev4ec17882019-01-24 17:16:58 -08003350 bool reconfigureRequired;
3351 if (updatesDetected) {
3352 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3353 updatedParams);
3354 mLatestSessionParams = updatedParams;
3355 } else {
3356 reconfigureRequired = false;
3357 }
3358
3359 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003360}
3361
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003362bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003363 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003364 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003365 // Any function called from threadLoop() must not hold mInterfaceLock since
3366 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3367 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003368
3369 // Handle paused state.
3370 if (waitIfPaused()) {
3371 return true;
3372 }
3373
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003374 // Wait for the next batch of requests.
3375 waitForNextRequestBatch();
3376 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003377 return true;
3378 }
3379
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003380 // Get the latest request ID, if any
3381 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003382 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003383 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003384 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003385 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003386 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003387 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3388 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003389 }
3390
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003391 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3392 // or a single request from streaming or burst. In either case the first element
3393 // should contain the latest camera settings that we need to check for any session
3394 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003395 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003396 res = OK;
3397
3398 //Input stream buffers are already acquired at this point so an input stream
3399 //will not be able to move to idle state unless we force it.
3400 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3401 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3402 if (res != OK) {
3403 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3404 cleanUpFailedRequests(/*sendRequestError*/ false);
3405 return false;
3406 }
3407 }
3408
3409 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003410 sp<Camera3Device> parent = mParent.promote();
3411 if (parent != nullptr) {
3412 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003413 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003414 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003415
3416 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3417 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3418 if (res != OK) {
3419 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3420 cleanUpFailedRequests(/*sendRequestError*/ false);
3421 return false;
3422 }
3423 }
3424 }
3425 }
3426
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003427 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003428 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003429 if (res == TIMED_OUT) {
3430 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003431 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003432 // Check if any stream is abandoned.
3433 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003434 return true;
3435 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003436 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003437 return false;
3438 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003439
Zhijun Hecc27e112013-10-03 16:12:43 -07003440 // Inform waitUntilRequestProcessed thread of a new request ID
3441 {
3442 Mutex::Autolock al(mLatestRequestMutex);
3443
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003444 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003445 mLatestRequestSignal.signal();
3446 }
3447
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003448 // Submit a batch of requests to HAL.
3449 // Use flush lock only when submitting multilple requests in a batch.
3450 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3451 // which may take a long time to finish so synchronizing flush() and
3452 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3453 // For now, only synchronize for high speed recording and we should figure something out for
3454 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003455 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003456
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003457 if (useFlushLock) {
3458 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003459 }
3460
Zhijun Hef0645c12016-08-02 00:58:11 -07003461 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003462 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003463
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003464 sp<Camera3Device> parent = mParent.promote();
3465 if (parent != nullptr) {
3466 parent->mRequestBufferSM.onSubmittingRequest();
3467 }
3468
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003469 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003470 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003471 submitRequestSuccess = sendRequestsBatch();
3472
Shuzhen Wang686f6442017-06-20 16:16:04 -07003473 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3474 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003475
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003476 if (useFlushLock) {
3477 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003478 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003479
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003480 // Unset as current request
3481 {
3482 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003483 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003484 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003485 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003486
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003487 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003488}
3489
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003490status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3491 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3492 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3493 ANDROID_SCALER_CROP_REGION_SET};
3494 if (request == nullptr) {
3495 ALOGE("%s request metadata nullptr", __FUNCTION__);
3496 return BAD_VALUE;
3497 }
3498 status_t res = OK;
3499 for (const auto &key : kFwkOnlyRegionKeys) {
3500 if (request->exists(key)) {
3501 res = request->erase(key);
3502 if (res != OK) {
3503 return res;
3504 }
3505 }
3506 }
3507 return OK;
3508}
3509
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003510status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003511 ATRACE_CALL();
3512
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003513 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003514 for (size_t i = 0; i < mNextRequests.size(); i++) {
3515 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003516 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003517 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3518 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003519
3520 // Prepare a request to HAL
3521 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3522
3523 // Insert any queued triggers (before metadata is locked)
3524 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003525 if (res < 0) {
3526 SET_ERR("RequestThread: Unable to insert triggers "
3527 "(capture request %d, HAL device: %s (%d)",
3528 halRequest->frame_number, strerror(-res), res);
3529 return INVALID_OPERATION;
3530 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003531
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003532 int triggerCount = res;
3533 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3534 mPrevTriggers = triggerCount;
3535
Emilian Peeve23f1d92021-09-20 14:56:01 -07003536 // Do not override rotate&crop for stream configurations that include
3537 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3538 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3539 bool rotateAndCropChanged = mComposerOutput ? false :
3540 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003541 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003542
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003543 // If the request is the same as last, or we had triggers now or last time or
3544 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003545 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003546 (mPrevRequest != captureRequest || triggersMixedIn ||
3547 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003548 // Request settings are all the same within one batch, so only treat the first
3549 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003550 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003551 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003552 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003553 /**
3554 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003555 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003556 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003557 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003558 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003559 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003560 "(capture request %d, HAL device: %s (%d)",
3561 halRequest->frame_number, strerror(-res), res);
3562 return INVALID_OPERATION;
3563 }
3564
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003565 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003566 sp<Camera3Device> parent = mParent.promote();
3567 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003568 List<PhysicalCameraSettings>::iterator it;
3569 for (it = captureRequest->mSettingsList.begin();
3570 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003571 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3572 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003573 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3574 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3575 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3576 res);
3577 return INVALID_OPERATION;
3578 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003579 continue;
3580 }
3581
3582 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3583 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3584 updateCaptureRequest(&(it->metadata));
3585 if (res != OK) {
3586 SET_ERR("RequestThread: Unable to correct capture requests "
3587 "for scaler crop region and metering regions for request "
3588 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3589 res);
3590 return INVALID_OPERATION;
3591 }
3592 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003593 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3594 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3595 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3596 res);
3597 return INVALID_OPERATION;
3598 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003599 }
3600 }
3601
3602 // Correct metadata regions for distortion correction if enabled
3603 for (it = captureRequest->mSettingsList.begin();
3604 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003605 if (parent->mDistortionMappers.find(it->cameraId) ==
3606 parent->mDistortionMappers.end()) {
3607 continue;
3608 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003609
3610 if (!captureRequest->mDistortionCorrectionUpdated) {
3611 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3612 &(it->metadata));
3613 if (res != OK) {
3614 SET_ERR("RequestThread: Unable to correct capture requests "
3615 "for lens distortion for request %d: %s (%d)",
3616 halRequest->frame_number, strerror(-res), res);
3617 return INVALID_OPERATION;
3618 }
3619 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003620 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003621 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003622
3623 for (it = captureRequest->mSettingsList.begin();
3624 it != captureRequest->mSettingsList.end(); it++) {
3625 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3626 parent->mZoomRatioMappers.end()) {
3627 continue;
3628 }
3629
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003630 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003631 cameraIdsWithZoom.insert(it->cameraId);
3632 }
3633
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003634 if (!captureRequest->mZoomRatioUpdated) {
3635 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3636 &(it->metadata));
3637 if (res != OK) {
3638 SET_ERR("RequestThread: Unable to correct capture requests "
3639 "for zoom ratio for request %d: %s (%d)",
3640 halRequest->frame_number, strerror(-res), res);
3641 return INVALID_OPERATION;
3642 }
3643 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003644 }
3645 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003646 if (captureRequest->mRotateAndCropAuto &&
3647 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003648 for (it = captureRequest->mSettingsList.begin();
3649 it != captureRequest->mSettingsList.end(); it++) {
3650 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3651 if (mapper != parent->mRotateAndCropMappers.end()) {
3652 res = mapper->second.updateCaptureRequest(&(it->metadata));
3653 if (res != OK) {
3654 SET_ERR("RequestThread: Unable to correct capture requests "
3655 "for rotate-and-crop for request %d: %s (%d)",
3656 halRequest->frame_number, strerror(-res), res);
3657 return INVALID_OPERATION;
3658 }
3659 }
3660 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003661 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003662 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003663 }
3664 }
3665
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003666 /**
3667 * The request should be presorted so accesses in HAL
3668 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3669 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003670 captureRequest->mSettingsList.begin()->metadata.sort();
3671 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003672 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003673 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003674 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3675
3676 IF_ALOGV() {
3677 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3678 find_camera_metadata_ro_entry(
3679 halRequest->settings,
3680 ANDROID_CONTROL_AF_TRIGGER,
3681 &e
3682 );
3683 if (e.count > 0) {
3684 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3685 __FUNCTION__,
3686 halRequest->frame_number,
3687 e.data.u8[0]);
3688 }
3689 }
3690 } else {
3691 // leave request.settings NULL to indicate 'reuse latest given'
3692 ALOGVV("%s: Request settings are REUSED",
3693 __FUNCTION__);
3694 }
3695
Emilian Peevaebbe412018-01-15 13:53:24 +00003696 if (captureRequest->mSettingsList.size() > 1) {
3697 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3698 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003699 if (newRequest) {
3700 halRequest->physcam_settings =
3701 new const camera_metadata* [halRequest->num_physcam_settings];
3702 } else {
3703 halRequest->physcam_settings = nullptr;
3704 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003705 auto it = ++captureRequest->mSettingsList.begin();
3706 size_t i = 0;
3707 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3708 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003709 if (newRequest) {
3710 it->metadata.sort();
3711 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3712 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003713 }
3714 }
3715
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003716 uint32_t totalNumBuffers = 0;
3717
3718 // Fill in buffers
3719 if (captureRequest->mInputStream != NULL) {
3720 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003721
3722 halRequest->input_width = captureRequest->mInputBufferSize.width;
3723 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003724 totalNumBuffers += 1;
3725 } else {
3726 halRequest->input_buffer = NULL;
3727 }
3728
Emilian Peevf4816702020-04-03 15:44:51 -07003729 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003730 captureRequest->mOutputStreams.size());
3731 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003732 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003733
3734 sp<Camera3Device> parent = mParent.promote();
3735 if (parent == NULL) {
3736 // Should not happen, and nowhere to send errors to, so just log it
3737 CLOGE("RequestThread: Parent is gone");
3738 return INVALID_OPERATION;
3739 }
3740 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3741
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003742 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003743 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003744 sp<Camera3OutputStreamInterface> outputStream =
3745 captureRequest->mOutputStreams.editItemAt(j);
3746 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003747
3748 // Prepare video buffers for high speed recording on the first video request.
3749 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3750 // Only try to prepare video stream on the first video request.
3751 mPrepareVideoStream = false;
3752
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003753 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3754 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003755 while (res == NOT_ENOUGH_DATA) {
3756 res = outputStream->prepareNextBuffer();
3757 }
3758 if (res != OK) {
3759 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3760 __FUNCTION__, strerror(-res), res);
3761 outputStream->cancelPrepare();
3762 }
3763 }
3764
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003765 std::vector<size_t> uniqueSurfaceIds;
3766 res = outputStream->getUniqueSurfaceIds(
3767 captureRequest->mOutputSurfaces[streamId],
3768 &uniqueSurfaceIds);
3769 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3770 if (res != OK && res != INVALID_OPERATION) {
3771 ALOGE("%s: failed to query stream %d unique surface IDs",
3772 __FUNCTION__, streamId);
3773 return res;
3774 }
3775 if (res == OK) {
3776 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3777 }
3778
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003779 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003780 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003781 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003782 return TIMED_OUT;
3783 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003784 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003785 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003786 buffer.stream = outputStream->asHalStream();
3787 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003788 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003789 buffer.acquire_fence = -1;
3790 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003791 // Mark the output stream as unpreparable to block clients from calling
3792 // 'prepare' after this request reaches CameraHal and before the respective
3793 // buffers are requested.
3794 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003795 } else {
3796 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3797 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003798 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003799 if (res != OK) {
3800 // Can't get output buffer from gralloc queue - this could be due to
3801 // abandoned queue or other consumer misbehavior, so not a fatal
3802 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003803 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003804 " %s (%d)", strerror(-res), res);
3805
3806 return TIMED_OUT;
3807 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003808 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003809
3810 {
3811 sp<Camera3Device> parent = mParent.promote();
3812 if (parent != nullptr) {
3813 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3814 for (const auto& settings : captureRequest->mSettingsList) {
3815 if ((streamCameraId.isEmpty() &&
3816 parent->getId() == settings.cameraId.c_str()) ||
3817 streamCameraId == settings.cameraId.c_str()) {
3818 outputStream->fireBufferRequestForFrameNumber(
3819 captureRequest->mResultExtras.frameNumber,
3820 settings.metadata);
3821 }
3822 }
3823 }
3824 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003825
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003826 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003827 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3828 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3829 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3830 } else if (!physicalCameraId.isEmpty()) {
3831 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003832 }
3833 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003834 }
3835 totalNumBuffers += halRequest->num_output_buffers;
3836
3837 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003838 // If this request list is for constrained high speed recording (not
3839 // preview), and the current request is not the last one in the batch,
3840 // do not send callback to the app.
3841 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003842 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003843 hasCallback = false;
3844 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003845 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003846 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003847 const camera_metadata_t* settings = halRequest->settings;
3848 bool shouldUnlockSettings = false;
3849 if (settings == nullptr) {
3850 shouldUnlockSettings = true;
3851 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3852 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003853 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3854 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003855 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003856 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3857 isStillCapture = true;
3858 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3859 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003860
Emilian Peevaf8416e2021-02-04 17:52:43 -08003861 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003862 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003863 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3864 isZslCapture = true;
3865 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003866 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003867 res = parent->registerInFlight(halRequest->frame_number,
3868 totalNumBuffers, captureRequest->mResultExtras,
3869 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003870 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003871 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003872 requestedPhysicalCameras, isStillCapture, isZslCapture,
3873 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003874 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003875 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003876 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3877 ", burstId = %" PRId32 ".",
3878 __FUNCTION__,
3879 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3880 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003881
3882 if (shouldUnlockSettings) {
3883 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3884 }
3885
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003886 if (res != OK) {
3887 SET_ERR("RequestThread: Unable to register new in-flight request:"
3888 " %s (%d)", strerror(-res), res);
3889 return INVALID_OPERATION;
3890 }
3891 }
3892
3893 return OK;
3894}
3895
Igor Murashkin1e479c02013-09-06 16:55:14 -07003896CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003897 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003898 Mutex::Autolock al(mLatestRequestMutex);
3899
3900 ALOGV("RequestThread::%s", __FUNCTION__);
3901
3902 return mLatestRequest;
3903}
3904
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003905bool Camera3Device::RequestThread::isStreamPending(
3906 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003907 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003908 Mutex::Autolock l(mRequestLock);
3909
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003910 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003911 if (!nextRequest.submitted) {
3912 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3913 if (stream == s) return true;
3914 }
3915 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003916 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003917 }
3918
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003919 for (const auto& request : mRequestQueue) {
3920 for (const auto& s : request->mOutputStreams) {
3921 if (stream == s) return true;
3922 }
3923 if (stream == request->mInputStream) return true;
3924 }
3925
3926 for (const auto& request : mRepeatingRequests) {
3927 for (const auto& s : request->mOutputStreams) {
3928 if (stream == s) return true;
3929 }
3930 if (stream == request->mInputStream) return true;
3931 }
3932
3933 return false;
3934}
Jianing Weicb0652e2014-03-12 18:29:36 -07003935
Emilian Peev40ead602017-09-26 15:46:36 +01003936bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3937 ATRACE_CALL();
3938 Mutex::Autolock l(mRequestLock);
3939
3940 for (const auto& nextRequest : mNextRequests) {
3941 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3942 if (s.first == streamId) {
3943 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3944 if (it != s.second.end()) {
3945 return true;
3946 }
3947 }
3948 }
3949 }
3950
3951 for (const auto& request : mRequestQueue) {
3952 for (const auto& s : request->mOutputSurfaces) {
3953 if (s.first == streamId) {
3954 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3955 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003956 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003957 }
3958 }
3959 }
3960 }
3961
3962 for (const auto& request : mRepeatingRequests) {
3963 for (const auto& s : request->mOutputSurfaces) {
3964 if (s.first == streamId) {
3965 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3966 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003967 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003968 }
3969 }
3970 }
3971 }
3972
3973 return false;
3974}
3975
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003976void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3977 if (!mUseHalBufManager) {
3978 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3979 return;
3980 }
3981
3982 Mutex::Autolock pl(mPauseLock);
3983 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003984 mInterface->signalPipelineDrain(streamIds);
3985 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003986 }
3987 // If request thread is still busy, wait until paused then notify HAL
3988 mNotifyPipelineDrain = true;
3989 mStreamIdsToBeDrained = streamIds;
3990}
3991
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003992void Camera3Device::RequestThread::resetPipelineDrain() {
3993 Mutex::Autolock pl(mPauseLock);
3994 mNotifyPipelineDrain = false;
3995 mStreamIdsToBeDrained.clear();
3996}
3997
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003998void Camera3Device::RequestThread::clearPreviousRequest() {
3999 Mutex::Autolock l(mRequestLock);
4000 mPrevRequest.clear();
4001}
4002
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004003status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4004 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4005 ATRACE_CALL();
4006 Mutex::Autolock l(mTriggerMutex);
4007 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4008 return BAD_VALUE;
4009 }
4010 mRotateAndCropOverride = rotateAndCropValue;
4011 return OK;
4012}
4013
Emilian Peeve23f1d92021-09-20 14:56:01 -07004014status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4015 ATRACE_CALL();
4016 Mutex::Autolock l(mTriggerMutex);
4017 mComposerOutput = composerSurfacePresent;
4018 return OK;
4019}
4020
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004021status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004022 ATRACE_CALL();
4023 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004024 if (muteMode != mCameraMute) {
4025 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004026 mCameraMuteChanged = true;
4027 }
4028 return OK;
4029}
4030
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004031nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004032 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004033 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004034 return mExpectedInflightDuration > kMinInflightDuration ?
4035 mExpectedInflightDuration : kMinInflightDuration;
4036}
4037
Emilian Peevaebbe412018-01-15 13:53:24 +00004038void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004039 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004040 if ((request == nullptr) || (halRequest == nullptr)) {
4041 ALOGE("%s: Invalid request!", __FUNCTION__);
4042 return;
4043 }
4044
4045 if (halRequest->num_physcam_settings > 0) {
4046 if (halRequest->physcam_id != nullptr) {
4047 delete [] halRequest->physcam_id;
4048 halRequest->physcam_id = nullptr;
4049 }
4050 if (halRequest->physcam_settings != nullptr) {
4051 auto it = ++(request->mSettingsList.begin());
4052 size_t i = 0;
4053 for (; it != request->mSettingsList.end(); it++, i++) {
4054 it->metadata.unlock(halRequest->physcam_settings[i]);
4055 }
4056 delete [] halRequest->physcam_settings;
4057 halRequest->physcam_settings = nullptr;
4058 }
4059 }
4060}
4061
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004062void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4063 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004064 return;
4065 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004066
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004067 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004068 // Skip the ones that have been submitted successfully.
4069 if (nextRequest.submitted) {
4070 continue;
4071 }
4072
4073 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004074 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4075 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004076
4077 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004078 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004079 }
4080
Emilian Peevaebbe412018-01-15 13:53:24 +00004081 cleanupPhysicalSettings(captureRequest, halRequest);
4082
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004084 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004085 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4086 }
4087
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004088 // No output buffer can be returned when using HAL buffer manager
4089 if (!mUseHalBufManager) {
4090 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4091 //Buffers that failed processing could still have
4092 //valid acquire fence.
4093 int acquireFence = (*outputBuffers)[i].acquire_fence;
4094 if (0 <= acquireFence) {
4095 close(acquireFence);
4096 outputBuffers->editItemAt(i).acquire_fence = -1;
4097 }
Emilian Peevf4816702020-04-03 15:44:51 -07004098 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004099 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4100 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004101 /*timestampIncreasing*/true, std::vector<size_t> (),
4102 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004103 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004104 }
4105
4106 if (sendRequestError) {
4107 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004108 sp<NotificationListener> listener = mListener.promote();
4109 if (listener != NULL) {
4110 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004111 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004112 captureRequest->mResultExtras);
4113 }
4114 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004115
4116 // Remove yet-to-be submitted inflight request from inflightMap
4117 {
4118 sp<Camera3Device> parent = mParent.promote();
4119 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004120 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004121 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4122 if (idx >= 0) {
4123 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4124 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4125 parent->removeInFlightMapEntryLocked(idx);
4126 }
4127 }
4128 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004129 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004130
4131 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004133}
4134
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004135void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004136 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004137 // Optimized a bit for the simple steady-state case (single repeating
4138 // request), to avoid putting that request in the queue temporarily.
4139 Mutex::Autolock l(mRequestLock);
4140
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004141 assert(mNextRequests.empty());
4142
4143 NextRequest nextRequest;
4144 nextRequest.captureRequest = waitForNextRequestLocked();
4145 if (nextRequest.captureRequest == nullptr) {
4146 return;
4147 }
4148
Emilian Peevf4816702020-04-03 15:44:51 -07004149 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004150 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004151 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004152
4153 // Wait for additional requests
4154 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4155
4156 for (size_t i = 1; i < batchSize; i++) {
4157 NextRequest additionalRequest;
4158 additionalRequest.captureRequest = waitForNextRequestLocked();
4159 if (additionalRequest.captureRequest == nullptr) {
4160 break;
4161 }
4162
Emilian Peevf4816702020-04-03 15:44:51 -07004163 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004164 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004165 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004166 }
4167
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004168 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004169 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004170 mNextRequests.size(), batchSize);
4171 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004172 }
4173
4174 return;
4175}
4176
4177sp<Camera3Device::CaptureRequest>
4178 Camera3Device::RequestThread::waitForNextRequestLocked() {
4179 status_t res;
4180 sp<CaptureRequest> nextRequest;
4181
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004182 while (mRequestQueue.empty()) {
4183 if (!mRepeatingRequests.empty()) {
4184 // Always atomically enqueue all requests in a repeating request
4185 // list. Guarantees a complete in-sequence set of captures to
4186 // application.
4187 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004188 if (mFirstRepeating) {
4189 mFirstRepeating = false;
4190 } else {
4191 for (auto& request : requests) {
4192 // For repeating requests, override timestamp request using
4193 // the time a request is inserted into the request queue,
4194 // because the original repeating request will have an old
4195 // fixed timestamp.
4196 request->mRequestTimeNs = systemTime();
4197 }
4198 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199 RequestList::const_iterator firstRequest =
4200 requests.begin();
4201 nextRequest = *firstRequest;
4202 mRequestQueue.insert(mRequestQueue.end(),
4203 ++firstRequest,
4204 requests.end());
4205 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004206
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004207 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004208
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004209 break;
4210 }
4211
4212 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4213
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004214 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4215 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004216 Mutex::Autolock pl(mPauseLock);
4217 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004218 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004219 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004220 if (mNotifyPipelineDrain) {
4221 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4222 mNotifyPipelineDrain = false;
4223 mStreamIdsToBeDrained.clear();
4224 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004225 // Let the tracker know
4226 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4227 if (statusTracker != 0) {
4228 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4229 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004230 sp<Camera3Device> parent = mParent.promote();
4231 if (parent != nullptr) {
4232 parent->mRequestBufferSM.onRequestThreadPaused();
4233 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234 }
4235 // Stop waiting for now and let thread management happen
4236 return NULL;
4237 }
4238 }
4239
4240 if (nextRequest == NULL) {
4241 // Don't have a repeating request already in hand, so queue
4242 // must have an entry now.
4243 RequestList::iterator firstRequest =
4244 mRequestQueue.begin();
4245 nextRequest = *firstRequest;
4246 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004247 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4248 sp<NotificationListener> listener = mListener.promote();
4249 if (listener != NULL) {
4250 listener->notifyRequestQueueEmpty();
4251 }
4252 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004253 }
4254
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004255 // In case we've been unpaused by setPaused clearing mDoPause, need to
4256 // update internal pause state (capture/setRepeatingRequest unpause
4257 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004259 if (mPaused) {
4260 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4261 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4262 if (statusTracker != 0) {
4263 statusTracker->markComponentActive(mStatusId);
4264 }
4265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004266 mPaused = false;
4267
4268 // Check if we've reconfigured since last time, and reset the preview
4269 // request if so. Can't use 'NULL request == repeat' across configure calls.
4270 if (mReconfigured) {
4271 mPrevRequest.clear();
4272 mReconfigured = false;
4273 }
4274
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004275 if (nextRequest != NULL) {
4276 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004277 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4278 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004279
4280 // Since RequestThread::clear() removes buffers from the input stream,
4281 // get the right buffer here before unlocking mRequestLock
4282 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004283 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4284 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004285 if (res != OK) {
4286 // Can't get input buffer from gralloc queue - this could be due to
4287 // disconnected queue or other producer misbehavior, so not a fatal
4288 // error
4289 ALOGE("%s: Can't get input buffer, skipping request:"
4290 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004291
4292 sp<NotificationListener> listener = mListener.promote();
4293 if (listener != NULL) {
4294 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004295 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004296 nextRequest->mResultExtras);
4297 }
4298 return NULL;
4299 }
4300 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004301 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004302
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004303 return nextRequest;
4304}
4305
4306bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004307 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004308 status_t res;
4309 Mutex::Autolock l(mPauseLock);
4310 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 if (mPaused == false) {
4312 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004313 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004314 if (mNotifyPipelineDrain) {
4315 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4316 mNotifyPipelineDrain = false;
4317 mStreamIdsToBeDrained.clear();
4318 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004319 // Let the tracker know
4320 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4321 if (statusTracker != 0) {
4322 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4323 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004324 sp<Camera3Device> parent = mParent.promote();
4325 if (parent != nullptr) {
4326 parent->mRequestBufferSM.onRequestThreadPaused();
4327 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004328 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004329
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004330 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004331 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004332 return true;
4333 }
4334 }
4335 // We don't set mPaused to false here, because waitForNextRequest needs
4336 // to further manage the paused state in case of starvation.
4337 return false;
4338}
4339
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004340void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004341 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004342 // With work to do, mark thread as unpaused.
4343 // If paused by request (setPaused), don't resume, to avoid
4344 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004345 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004346 Mutex::Autolock p(mPauseLock);
4347 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004348 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4349 if (mPaused) {
4350 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4351 if (statusTracker != 0) {
4352 statusTracker->markComponentActive(mStatusId);
4353 }
4354 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004355 mPaused = false;
4356 }
4357}
4358
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004359void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4360 sp<Camera3Device> parent = mParent.promote();
4361 if (parent != NULL) {
4362 va_list args;
4363 va_start(args, fmt);
4364
4365 parent->setErrorStateV(fmt, args);
4366
4367 va_end(args);
4368 }
4369}
4370
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004371status_t Camera3Device::RequestThread::insertTriggers(
4372 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004373 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004374 Mutex::Autolock al(mTriggerMutex);
4375
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004376 sp<Camera3Device> parent = mParent.promote();
4377 if (parent == NULL) {
4378 CLOGE("RequestThread: Parent is gone");
4379 return DEAD_OBJECT;
4380 }
4381
Emilian Peevaebbe412018-01-15 13:53:24 +00004382 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004383 size_t count = mTriggerMap.size();
4384
4385 for (size_t i = 0; i < count; ++i) {
4386 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004387 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004388
4389 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4390 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4391 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004392 if (isAeTrigger) {
4393 request->mResultExtras.precaptureTriggerId = triggerId;
4394 mCurrentPreCaptureTriggerId = triggerId;
4395 } else {
4396 request->mResultExtras.afTriggerId = triggerId;
4397 mCurrentAfTriggerId = triggerId;
4398 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004399 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004400 }
4401
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004402 camera_metadata_entry entry = metadata.find(tag);
4403
4404 if (entry.count > 0) {
4405 /**
4406 * Already has an entry for this trigger in the request.
4407 * Rewrite it with our requested trigger value.
4408 */
4409 RequestTrigger oldTrigger = trigger;
4410
4411 oldTrigger.entryValue = entry.data.u8[0];
4412
4413 mTriggerReplacedMap.add(tag, oldTrigger);
4414 } else {
4415 /**
4416 * More typical, no trigger entry, so we just add it
4417 */
4418 mTriggerRemovedMap.add(tag, trigger);
4419 }
4420
4421 status_t res;
4422
4423 switch (trigger.getTagType()) {
4424 case TYPE_BYTE: {
4425 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4426 res = metadata.update(tag,
4427 &entryValue,
4428 /*count*/1);
4429 break;
4430 }
4431 case TYPE_INT32:
4432 res = metadata.update(tag,
4433 &trigger.entryValue,
4434 /*count*/1);
4435 break;
4436 default:
4437 ALOGE("%s: Type not supported: 0x%x",
4438 __FUNCTION__,
4439 trigger.getTagType());
4440 return INVALID_OPERATION;
4441 }
4442
4443 if (res != OK) {
4444 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4445 ", value %d", __FUNCTION__, trigger.getTagName(),
4446 trigger.entryValue);
4447 return res;
4448 }
4449
4450 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4451 trigger.getTagName(),
4452 trigger.entryValue);
4453 }
4454
4455 mTriggerMap.clear();
4456
4457 return count;
4458}
4459
4460status_t Camera3Device::RequestThread::removeTriggers(
4461 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004462 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004463 Mutex::Autolock al(mTriggerMutex);
4464
Emilian Peevaebbe412018-01-15 13:53:24 +00004465 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004466
4467 /**
4468 * Replace all old entries with their old values.
4469 */
4470 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4471 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4472
4473 status_t res;
4474
4475 uint32_t tag = trigger.metadataTag;
4476 switch (trigger.getTagType()) {
4477 case TYPE_BYTE: {
4478 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4479 res = metadata.update(tag,
4480 &entryValue,
4481 /*count*/1);
4482 break;
4483 }
4484 case TYPE_INT32:
4485 res = metadata.update(tag,
4486 &trigger.entryValue,
4487 /*count*/1);
4488 break;
4489 default:
4490 ALOGE("%s: Type not supported: 0x%x",
4491 __FUNCTION__,
4492 trigger.getTagType());
4493 return INVALID_OPERATION;
4494 }
4495
4496 if (res != OK) {
4497 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4498 ", trigger value %d", __FUNCTION__,
4499 trigger.getTagName(), trigger.entryValue);
4500 return res;
4501 }
4502 }
4503 mTriggerReplacedMap.clear();
4504
4505 /**
4506 * Remove all new entries.
4507 */
4508 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4509 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4510 status_t res = metadata.erase(trigger.metadataTag);
4511
4512 if (res != OK) {
4513 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4514 ", trigger value %d", __FUNCTION__,
4515 trigger.getTagName(), trigger.entryValue);
4516 return res;
4517 }
4518 }
4519 mTriggerRemovedMap.clear();
4520
4521 return OK;
4522}
4523
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004524status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004525 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004526 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004527 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004528 status_t res;
4529
Emilian Peevaebbe412018-01-15 13:53:24 +00004530 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004531
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004532 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004533 // exists
4534 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4535 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4536 if (afTrigger.count > 0 &&
4537 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4538 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004539 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004540 if (res != OK) return res;
4541 }
4542
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004543 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004544 // if none already exists
4545 camera_metadata_entry pcTrigger =
4546 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4547 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4548 if (pcTrigger.count > 0 &&
4549 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4550 pcId.count == 0) {
4551 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004552 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004553 if (res != OK) return res;
4554 }
4555
4556 return OK;
4557}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004558
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004559bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4560 const sp<CaptureRequest> &request) {
4561 ATRACE_CALL();
4562
4563 if (request->mRotateAndCropAuto) {
4564 Mutex::Autolock l(mTriggerMutex);
4565 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4566
4567 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4568 if (rotateAndCropEntry.count > 0) {
4569 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4570 return false;
4571 } else {
4572 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4573 return true;
4574 }
4575 } else {
4576 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4577 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4578 &rotateAndCrop_u8, 1);
4579 return true;
4580 }
4581 }
4582 return false;
4583}
4584
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004585bool Camera3Device::RequestThread::overrideTestPattern(
4586 const sp<CaptureRequest> &request) {
4587 ATRACE_CALL();
4588
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004589 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004590
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004591 Mutex::Autolock l(mTriggerMutex);
4592
4593 bool changed = false;
4594
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004595 // For a multi-camera, the physical cameras support the same set of
4596 // test pattern modes as the logical camera.
4597 for (auto& settings : request->mSettingsList) {
4598 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004599
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004600 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4601 int32_t testPatternData[4] = {
4602 settings.mOriginalTestPatternData[0],
4603 settings.mOriginalTestPatternData[1],
4604 settings.mOriginalTestPatternData[2],
4605 settings.mOriginalTestPatternData[3]
4606 };
4607 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4608 testPatternMode = mCameraMute;
4609 testPatternData[0] = 0;
4610 testPatternData[1] = 0;
4611 testPatternData[2] = 0;
4612 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004613 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004614
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004615 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4616 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4617 if (testPatternEntry.count > 0) {
4618 if (testPatternEntry.data.i32[0] != testPatternMode) {
4619 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004620 changed = true;
4621 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004622 } else if (supportTestPatternModeKey) {
4623 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4624 &testPatternMode, 1);
4625 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004626 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004627
4628 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4629 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4630 if (testPatternColor.count >= 4) {
4631 for (size_t i = 0; i < 4; i++) {
4632 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4633 testPatternColor.data.i32[i] = testPatternData[i];
4634 changed = true;
4635 }
4636 }
4637 } else if (supportTestPatternDataKey) {
4638 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4639 testPatternData, 4);
4640 changed = true;
4641 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004642 }
4643
4644 return changed;
4645}
4646
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004647status_t Camera3Device::RequestThread::setHalInterface(
4648 sp<HalInterface> newHalInterface) {
4649 if (newHalInterface.get() == nullptr) {
4650 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4651 return DEAD_OBJECT;
4652 }
4653
4654 mInterface = newHalInterface;
4655
4656 return OK;
4657}
4658
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004659/**
4660 * PreparerThread inner class methods
4661 */
4662
4663Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004664 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004665 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004666}
4667
4668Camera3Device::PreparerThread::~PreparerThread() {
4669 Thread::requestExitAndWait();
4670 if (mCurrentStream != nullptr) {
4671 mCurrentStream->cancelPrepare();
4672 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4673 mCurrentStream.clear();
4674 }
4675 clear();
4676}
4677
Ruben Brunkc78ac262015-08-13 17:58:46 -07004678status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004679 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004680 status_t res;
4681
4682 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004683 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004684
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004685 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004686 if (res == OK) {
4687 // No preparation needed, fire listener right off
4688 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004689 if (listener != NULL) {
4690 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004691 }
4692 return OK;
4693 } else if (res != NOT_ENOUGH_DATA) {
4694 return res;
4695 }
4696
4697 // Need to prepare, start up thread if necessary
4698 if (!mActive) {
4699 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4700 // isn't running
4701 Thread::requestExitAndWait();
4702 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4703 if (res != OK) {
4704 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004705 if (listener != NULL) {
4706 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004707 }
4708 return res;
4709 }
4710 mCancelNow = false;
4711 mActive = true;
4712 ALOGV("%s: Preparer stream started", __FUNCTION__);
4713 }
4714
4715 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004716 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004717 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4718
4719 return OK;
4720}
4721
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004722void Camera3Device::PreparerThread::pause() {
4723 ATRACE_CALL();
4724
4725 Mutex::Autolock l(mLock);
4726
4727 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4728 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4729 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4730 int currentMaxCount = mCurrentMaxCount;
4731 mPendingStreams.clear();
4732 mCancelNow = true;
4733 while (mActive) {
4734 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4735 if (res == TIMED_OUT) {
4736 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4737 return;
4738 } else if (res != OK) {
4739 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4740 return;
4741 }
4742 }
4743
4744 //Check whether the prepare thread was able to complete the current
4745 //stream. In case work is still pending emplace it along with the rest
4746 //of the streams in the pending list.
4747 if (currentStream != nullptr) {
4748 if (!mCurrentPrepareComplete) {
4749 pendingStreams.emplace(currentMaxCount, currentStream);
4750 }
4751 }
4752
4753 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4754 for (const auto& it : mPendingStreams) {
4755 it.second->cancelPrepare();
4756 }
4757}
4758
4759status_t Camera3Device::PreparerThread::resume() {
4760 ATRACE_CALL();
4761 status_t res;
4762
4763 Mutex::Autolock l(mLock);
4764 sp<NotificationListener> listener = mListener.promote();
4765
4766 if (mActive) {
4767 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4768 return NO_INIT;
4769 }
4770
4771 auto it = mPendingStreams.begin();
4772 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004773 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004774 if (res == OK) {
4775 if (listener != NULL) {
4776 listener->notifyPrepared(it->second->getId());
4777 }
4778 it = mPendingStreams.erase(it);
4779 } else if (res != NOT_ENOUGH_DATA) {
4780 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4781 res, strerror(-res));
4782 it = mPendingStreams.erase(it);
4783 } else {
4784 it++;
4785 }
4786 }
4787
4788 if (mPendingStreams.empty()) {
4789 return OK;
4790 }
4791
4792 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4793 if (res != OK) {
4794 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4795 __FUNCTION__, res, strerror(-res));
4796 return res;
4797 }
4798 mCancelNow = false;
4799 mActive = true;
4800 ALOGV("%s: Preparer stream started", __FUNCTION__);
4801
4802 return OK;
4803}
4804
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004805status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004806 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004807 Mutex::Autolock l(mLock);
4808
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004809 for (const auto& it : mPendingStreams) {
4810 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004811 }
4812 mPendingStreams.clear();
4813 mCancelNow = true;
4814
4815 return OK;
4816}
4817
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004818void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004819 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004820 Mutex::Autolock l(mLock);
4821 mListener = listener;
4822}
4823
4824bool Camera3Device::PreparerThread::threadLoop() {
4825 status_t res;
4826 {
4827 Mutex::Autolock l(mLock);
4828 if (mCurrentStream == nullptr) {
4829 // End thread if done with work
4830 if (mPendingStreams.empty()) {
4831 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4832 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4833 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4834 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004835 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004836 return false;
4837 }
4838
4839 // Get next stream to prepare
4840 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004841 mCurrentStream = it->second;
4842 mCurrentMaxCount = it->first;
4843 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004844 mPendingStreams.erase(it);
4845 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4846 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4847 } else if (mCancelNow) {
4848 mCurrentStream->cancelPrepare();
4849 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4850 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4851 mCurrentStream.clear();
4852 mCancelNow = false;
4853 return true;
4854 }
4855 }
4856
4857 res = mCurrentStream->prepareNextBuffer();
4858 if (res == NOT_ENOUGH_DATA) return true;
4859 if (res != OK) {
4860 // Something bad happened; try to recover by cancelling prepare and
4861 // signalling listener anyway
4862 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4863 mCurrentStream->getId(), res, strerror(-res));
4864 mCurrentStream->cancelPrepare();
4865 }
4866
4867 // This stream has finished, notify listener
4868 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004869 sp<NotificationListener> listener = mListener.promote();
4870 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4872 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004873 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004874 }
4875
4876 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4877 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004878 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004879
4880 return true;
4881}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004882
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004883status_t Camera3Device::RequestBufferStateMachine::initialize(
4884 sp<camera3::StatusTracker> statusTracker) {
4885 if (statusTracker == nullptr) {
4886 ALOGE("%s: statusTracker is null", __FUNCTION__);
4887 return BAD_VALUE;
4888 }
4889
4890 std::lock_guard<std::mutex> lock(mLock);
4891 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004892 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004893 return OK;
4894}
4895
4896bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4897 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004898 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004899 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004900 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004901 return true;
4902 }
4903 return false;
4904}
4905
4906void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4907 std::lock_guard<std::mutex> lock(mLock);
4908 if (!mRequestBufferOngoing) {
4909 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4910 return;
4911 }
4912 mRequestBufferOngoing = false;
4913 if (mStatus == RB_STATUS_PENDING_STOP) {
4914 checkSwitchToStopLocked();
4915 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004916 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004917}
4918
4919void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4920 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004921 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004922 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004923 return;
4924}
4925
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004926void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004927 std::lock_guard<std::mutex> lock(mLock);
4928 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004929 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4930 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004931 mInflightMapEmpty = false;
4932 if (mStatus == RB_STATUS_STOPPED) {
4933 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004934 }
4935 return;
4936}
4937
4938void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4939 std::lock_guard<std::mutex> lock(mLock);
4940 mRequestThreadPaused = true;
4941 if (mStatus == RB_STATUS_PENDING_STOP) {
4942 checkSwitchToStopLocked();
4943 }
4944 return;
4945}
4946
4947void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4948 std::lock_guard<std::mutex> lock(mLock);
4949 mInflightMapEmpty = true;
4950 if (mStatus == RB_STATUS_PENDING_STOP) {
4951 checkSwitchToStopLocked();
4952 }
4953 return;
4954}
4955
4956void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4957 std::lock_guard<std::mutex> lock(mLock);
4958 if (!checkSwitchToStopLocked()) {
4959 mStatus = RB_STATUS_PENDING_STOP;
4960 }
4961 return;
4962}
4963
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004964bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4965 std::lock_guard<std::mutex> lock(mLock);
4966 if (mRequestBufferOngoing) {
4967 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4968 __FUNCTION__);
4969 return false;
4970 }
4971 mSwitchedToOffline = true;
4972 mInflightMapEmpty = true;
4973 mRequestThreadPaused = true;
4974 mStatus = RB_STATUS_STOPPED;
4975 return true;
4976}
4977
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004978void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4979 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4980 if (statusTracker != nullptr) {
4981 if (active) {
4982 statusTracker->markComponentActive(mRequestBufferStatusId);
4983 } else {
4984 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4985 }
4986 }
4987}
4988
4989bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4990 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4991 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004992 return true;
4993 }
4994 return false;
4995}
4996
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004997bool Camera3Device::startRequestBuffer() {
4998 return mRequestBufferSM.startRequestBuffer();
4999}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005000
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005001void Camera3Device::endRequestBuffer() {
5002 mRequestBufferSM.endRequestBuffer();
5003}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005004
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005005nsecs_t Camera3Device::getWaitDuration() {
5006 return kBaseGetBufferWait + getExpectedInFlightDuration();
5007}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005008
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005009void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5010 mInterface->getInflightBufferKeys(out);
5011}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005012
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005013void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5014 mInterface->getInflightRequestBufferKeys(out);
5015}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005016
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005017std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5018 std::vector<sp<Camera3StreamInterface>> ret;
5019 bool hasInputStream = mInputStream != nullptr;
5020 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5021 if (hasInputStream) {
5022 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005023 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005024 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5025 ret.push_back(mOutputStreams[i]);
5026 }
5027 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5028 ret.push_back(mDeletedStreams[i]);
5029 }
5030 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005031}
5032
Emilian Peevcc0b7952020-01-07 13:54:47 -08005033void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5034 ATRACE_CALL();
5035
5036 if (offlineStreamIds == nullptr) {
5037 return;
5038 }
5039
5040 Mutex::Autolock il(mInterfaceLock);
5041
5042 auto streamIds = mOutputStreams.getStreamIds();
5043 bool hasInputStream = mInputStream != nullptr;
5044 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5045 offlineStreamIds->push_back(mInputStream->getId());
5046 }
5047
5048 for (const auto & streamId : streamIds) {
5049 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5050 // Streams that use the camera buffer manager are currently not supported in
5051 // offline mode
5052 if (stream->getOfflineProcessingSupport() &&
5053 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5054 offlineStreamIds->push_back(streamId);
5055 }
5056 }
5057}
5058
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005059status_t Camera3Device::setRotateAndCropAutoBehavior(
5060 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5061 ATRACE_CALL();
5062 Mutex::Autolock il(mInterfaceLock);
5063 Mutex::Autolock l(mLock);
5064 if (mRequestThread == nullptr) {
5065 return INVALID_OPERATION;
5066 }
5067 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5068}
5069
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005070bool Camera3Device::supportsCameraMute() {
5071 Mutex::Autolock il(mInterfaceLock);
5072 Mutex::Autolock l(mLock);
5073
5074 return mSupportCameraMute;
5075}
5076
5077status_t Camera3Device::setCameraMute(bool enabled) {
5078 ATRACE_CALL();
5079 Mutex::Autolock il(mInterfaceLock);
5080 Mutex::Autolock l(mLock);
5081
5082 if (mRequestThread == nullptr || !mSupportCameraMute) {
5083 return INVALID_OPERATION;
5084 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005085 int32_t muteMode =
5086 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5087 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5088 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5089 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005090}
5091
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005092status_t Camera3Device::injectCamera(const String8& injectedCamId,
5093 sp<CameraProviderManager> manager) {
5094 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5095 ATRACE_CALL();
5096 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005097 // When the camera device is active, injectCamera() and stopInjection() will call
5098 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5099 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5100 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5101 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5102 // waitUntilStateThenRelock().
5103 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005104
5105 status_t res = NO_ERROR;
5106 if (mInjectionMethods->isInjecting()) {
5107 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5108 return OK;
5109 } else {
5110 res = mInjectionMethods->stopInjection();
5111 if (res != OK) {
5112 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5113 __FUNCTION__, res);
5114 return res;
5115 }
5116 }
5117 }
5118
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005119 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005120 if (res != OK) {
5121 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5122 __FUNCTION__, res);
5123 return res;
5124 }
5125
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005126 // When the second display of android is cast to the remote device, and the opened camera is
5127 // also cast to the second display, in this case, because the camera has configured the streams
5128 // at this time, we can directly call injectCamera() to replace the internal camera with
5129 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005130 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5131 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5132
5133 camera3::camera_stream_configuration injectionConfig;
5134 std::vector<uint32_t> injectionBufferSizes;
5135 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5136 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5137 || injectionBufferSizes.size() <= 0) {
5138 ALOGE("Failed to inject camera due to abandoned configuration! "
5139 "mOperatingMode: %d injectionConfig.num_streams: %d "
5140 "injectionBufferSizes.size(): %zu", mOperatingMode,
5141 injectionConfig.num_streams, injectionBufferSizes.size());
5142 return DEAD_OBJECT;
5143 }
5144
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005145 res = mInjectionMethods->injectCamera(
5146 injectionConfig, injectionBufferSizes);
5147 if (res != OK) {
5148 ALOGE("Can't finish inject camera process!");
5149 return res;
5150 }
5151 }
5152
5153 return OK;
5154}
5155
5156status_t Camera3Device::stopInjection() {
5157 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5158 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005159 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005160 return mInjectionMethods->stopInjection();
5161}
5162
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005163}; // namespace android