blob: 688b6dff767a766b933f179dd33747264772716a [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,
Emilian Peevc81a7592022-02-14 17:38:18 -0800981 uint64_t consumerUsage, int64_t dynamicRangeProfile, int streamUseCase,
982 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,
Emilian Peevc81a7592022-02-14 17:38:18 -08001016 uint64_t consumerUsage, int64_t dynamicRangeProfile, int streamUseCase, int timestampBase,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001017 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"
Emilian Peevc81a7592022-02-14 17:38:18 -08001025 " dynamicRangeProfile %" PRIx64 ", streamUseCase %d, timestampBase %d, mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001026 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001027 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001028 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001029
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001030 status_t res;
1031 bool wasActive = false;
1032
1033 switch (mStatus) {
1034 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001035 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001036 return INVALID_OPERATION;
1037 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001038 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001039 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001040 case STATUS_UNCONFIGURED:
1041 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001042 // OK
1043 break;
1044 case STATUS_ACTIVE:
1045 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001046 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001048 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001049 return res;
1050 }
1051 wasActive = true;
1052 break;
1053 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001054 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 return INVALID_OPERATION;
1056 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001057 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058
1059 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 if (consumers.size() == 0 && !hasDeferredConsumer) {
1062 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1063 return BAD_VALUE;
1064 }
Zhijun He5d677d12016-05-29 16:52:39 -07001065
Shuzhen Wang0129d522016-10-30 22:43:41 -07001066 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001067 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1068 return BAD_VALUE;
1069 }
1070
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001071 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1072 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1073 // be found in only one sensor pixel mode.
1074 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1075 return BAD_VALUE;
1076 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001078 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001079 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001080 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001081 if (blobBufferSize <= 0) {
1082 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1083 return BAD_VALUE;
1084 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001085 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1086 blobBufferSize = width * height;
1087 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001088 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001089 if (blobBufferSize <= 0) {
1090 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1091 return BAD_VALUE;
1092 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001093 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001094 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001095 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001096 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001097 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001098 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001099 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001100 bool maxResolution =
1101 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1102 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001103 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1104 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001105 if (rawOpaqueBufferSize <= 0) {
1106 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1107 return BAD_VALUE;
1108 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001109 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001110 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001111 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001112 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001113 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001114 } else if (isShared) {
1115 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1116 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001117 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001118 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001119 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001121 newStream = new Camera3OutputStream(mNextStreamId,
1122 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001123 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001124 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001125 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001127 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001128 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001129 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001130 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001131 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 }
Emilian Peev40ead602017-09-26 15:46:36 +01001133
1134 size_t consumerCount = consumers.size();
1135 for (size_t i = 0; i < consumerCount; i++) {
1136 int id = newStream->getSurfaceId(consumers[i]);
1137 if (id < 0) {
1138 SET_ERR_L("Invalid surface id");
1139 return BAD_VALUE;
1140 }
1141 if (surfaceIds != nullptr) {
1142 surfaceIds->push_back(id);
1143 }
1144 }
1145
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001146 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001147
Emilian Peev08dd2452017-04-06 16:55:14 +01001148 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001149
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001150 newStream->setImageDumpMask(mImageDumpMask);
1151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 res = mOutputStreams.add(mNextStreamId, newStream);
1153 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001154 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001155 return res;
1156 }
1157
Shuzhen Wang316781a2020-08-18 18:11:01 -07001158 mSessionStatsBuilder.addStream(mNextStreamId);
1159
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001160 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001161 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001162
1163 // Continue captures if active at start
1164 if (wasActive) {
1165 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001166 // Reuse current operating mode and session parameters for new stream config
1167 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001168 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001169 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1170 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 return res;
1172 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001175 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177}
1178
Emilian Peev710c1422017-08-30 11:19:38 +01001179status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001181 if (nullptr == streamInfo) {
1182 return BAD_VALUE;
1183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001186
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 switch (mStatus) {
1188 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001189 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190 return INVALID_OPERATION;
1191 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001192 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001194 case STATUS_UNCONFIGURED:
1195 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 case STATUS_ACTIVE:
1197 // OK
1198 break;
1199 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 return INVALID_OPERATION;
1202 }
1203
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001204 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1205 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001206 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001207 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 }
1209
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001210 streamInfo->width = stream->getWidth();
1211 streamInfo->height = stream->getHeight();
1212 streamInfo->format = stream->getFormat();
1213 streamInfo->dataSpace = stream->getDataSpace();
1214 streamInfo->formatOverridden = stream->isFormatOverridden();
1215 streamInfo->originalFormat = stream->getOriginalFormat();
1216 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1217 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001218 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
1222status_t Camera3Device::setStreamTransform(int id,
1223 int transform) {
1224 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001227
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 switch (mStatus) {
1229 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001230 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 return INVALID_OPERATION;
1232 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 case STATUS_UNCONFIGURED:
1236 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 case STATUS_ACTIVE:
1238 // OK
1239 break;
1240 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 }
1244
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001245 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1246 if (stream == nullptr) {
1247 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return BAD_VALUE;
1249 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001250 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251}
1252
1253status_t Camera3Device::deleteStream(int id) {
1254 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001255 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 Mutex::Autolock l(mLock);
1257 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001258
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001259 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001260
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 // CameraDevice semantics require device to already be idle before
1262 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001264 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001265 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 }
1267
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001268 if (mStatus == STATUS_ERROR) {
1269 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1270 __FUNCTION__, mId.string());
1271 return -EBUSY;
1272 }
1273
Igor Murashkin2fba5842013-04-22 14:03:54 -07001274 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001275 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 if (mInputStream != NULL && id == mInputStream->getId()) {
1277 deletedStream = mInputStream;
1278 mInputStream.clear();
1279 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001280 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001281 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 return BAD_VALUE;
1283 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001284 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001285 }
1286
1287 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001288 if (stream != nullptr) {
1289 deletedStream = stream;
1290 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291 }
1292
1293 // Free up the stream endpoint so that it can be used by some other stream
1294 res = deletedStream->disconnect();
1295 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001296 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297 // fall through since we want to still list the stream as deleted.
1298 }
1299 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001300 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301
1302 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001303}
1304
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001305status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001306 ATRACE_CALL();
1307 ALOGV("%s: E", __FUNCTION__);
1308
1309 Mutex::Autolock il(mInterfaceLock);
1310 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001311
Emilian Peev811d2952018-05-25 11:08:40 +01001312 // In case the client doesn't include any session parameter, try a
1313 // speculative configuration using the values from the last cached
1314 // default request.
1315 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001316 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001317 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1318 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1319 mLastTemplateId);
1320 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1321 operatingMode);
1322 }
1323
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001324 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1325}
1326
1327status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1328 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001329 //Filter out any incoming session parameters
1330 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001331 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1332 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001333 CameraMetadata filteredParams(availableSessionKeys.count);
1334 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1335 filteredParams.getAndLock());
1336 set_camera_metadata_vendor_id(meta, mVendorTagId);
1337 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001338 if (availableSessionKeys.count > 0) {
1339 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1340 camera_metadata_ro_entry entry = params.find(
1341 availableSessionKeys.data.i32[i]);
1342 if (entry.count > 0) {
1343 filteredParams.update(entry);
1344 }
1345 }
1346 }
1347
1348 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001349}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001350
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001351status_t Camera3Device::getInputBufferProducer(
1352 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001353 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001354 Mutex::Autolock il(mInterfaceLock);
1355 Mutex::Autolock l(mLock);
1356
1357 if (producer == NULL) {
1358 return BAD_VALUE;
1359 } else if (mInputStream == NULL) {
1360 return INVALID_OPERATION;
1361 }
1362
1363 return mInputStream->getInputBufferProducer(producer);
1364}
1365
Emilian Peevf4816702020-04-03 15:44:51 -07001366status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001367 CameraMetadata *request) {
1368 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001369 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001370
Emilian Peevf4816702020-04-03 15:44:51 -07001371 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001372 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001373 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001374 return BAD_VALUE;
1375 }
1376
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001377 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001379 {
1380 Mutex::Autolock l(mLock);
1381 switch (mStatus) {
1382 case STATUS_ERROR:
1383 CLOGE("Device has encountered a serious error");
1384 return INVALID_OPERATION;
1385 case STATUS_UNINITIALIZED:
1386 CLOGE("Device is not initialized!");
1387 return INVALID_OPERATION;
1388 case STATUS_UNCONFIGURED:
1389 case STATUS_CONFIGURED:
1390 case STATUS_ACTIVE:
1391 // OK
1392 break;
1393 default:
1394 SET_ERR_L("Unexpected status: %d", mStatus);
1395 return INVALID_OPERATION;
1396 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001397
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001398 if (!mRequestTemplateCache[templateId].isEmpty()) {
1399 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001400 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001401 return OK;
1402 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001403 }
1404
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001405 camera_metadata_t *rawRequest;
1406 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001407 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001408
1409 {
1410 Mutex::Autolock l(mLock);
1411 if (res == BAD_VALUE) {
1412 ALOGI("%s: template %d is not supported on this camera device",
1413 __FUNCTION__, templateId);
1414 return res;
1415 } else if (res != OK) {
1416 CLOGE("Unable to construct request template %d: %s (%d)",
1417 templateId, strerror(-res), res);
1418 return res;
1419 }
1420
1421 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1422 mRequestTemplateCache[templateId].acquire(rawRequest);
1423
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001424 // Override the template request with zoomRatioMapper
1425 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1426 &mRequestTemplateCache[templateId]);
1427 if (res != OK) {
1428 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1429 templateId, strerror(-res), res);
1430 return res;
1431 }
1432
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001433 // Fill in JPEG_QUALITY if not available
1434 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1435 static const uint8_t kDefaultJpegQuality = 95;
1436 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1437 &kDefaultJpegQuality, 1);
1438 }
1439
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001440 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001441 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001442 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001443 return OK;
1444}
1445
1446status_t Camera3Device::waitUntilDrained() {
1447 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001449 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001451
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001452 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001453}
1454
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001455status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 switch (mStatus) {
1457 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001458 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 ALOGV("%s: Already idle", __FUNCTION__);
1460 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 case STATUS_CONFIGURED:
1462 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 case STATUS_ERROR:
1464 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001465 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 break;
1467 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001468 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return INVALID_OPERATION;
1470 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001471 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1472 maxExpectedDuration);
1473 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001474 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001475 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001476 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1477 res);
1478 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001479 return res;
1480}
1481
Ruben Brunk183f0562015-08-12 12:55:02 -07001482void Camera3Device::internalUpdateStatusLocked(Status status) {
1483 mStatus = status;
1484 mRecentStatusUpdates.add(mStatus);
1485 mStatusChanged.broadcast();
1486}
1487
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001490 if (mRequestThread.get() != nullptr) {
1491 mRequestThread->setPaused(true);
1492 } else {
1493 return NO_INIT;
1494 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001496 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1497 maxExpectedDuration);
1498 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 if (res != OK) {
1500 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001501 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 }
1503
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 return res;
1505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001507// Resume after internalPauseAndWaitLocked
1508status_t Camera3Device::internalResumeLocked() {
1509 status_t res;
1510
1511 mRequestThread->setPaused(false);
1512
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001513 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1514 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1516 if (res != OK) {
1517 SET_ERR_L("Can't transition to active in %f seconds!",
1518 kActiveTimeout/1e9);
1519 }
1520 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522}
1523
Ruben Brunk183f0562015-08-12 12:55:02 -07001524status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001526
1527 size_t startIndex = 0;
1528 if (mStatusWaiters == 0) {
1529 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1530 // this status list
1531 mRecentStatusUpdates.clear();
1532 } else {
1533 // If other threads are waiting on updates to this status list, set the position of the
1534 // first element that this list will check rather than clearing the list.
1535 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 }
1537
Ruben Brunk183f0562015-08-12 12:55:02 -07001538 mStatusWaiters++;
1539
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001540 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001541 if (!active && mUseHalBufManager) {
1542 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001543 if (mStatus == STATUS_ACTIVE) {
1544 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001545 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001546 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001547 mRequestBufferSM.onWaitUntilIdle();
1548 }
1549
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 bool stateSeen = false;
1551 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001552 if (active == (mStatus == STATUS_ACTIVE)) {
1553 // Desired state is current
1554 break;
1555 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556
1557 res = mStatusChanged.waitRelative(mLock, timeout);
1558 if (res != OK) break;
1559
Ruben Brunk183f0562015-08-12 12:55:02 -07001560 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1561 // transitions.
1562 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1563 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1564 __FUNCTION__);
1565
1566 // Encountered desired state since we began waiting
1567 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1569 stateSeen = true;
1570 break;
1571 }
1572 }
1573 } while (!stateSeen);
1574
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001575 if (signalPipelineDrain) {
1576 mRequestThread->resetPipelineDrain();
1577 }
1578
Ruben Brunk183f0562015-08-12 12:55:02 -07001579 mStatusWaiters--;
1580
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001581 return res;
1582}
1583
1584
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001585status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001587 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001589 if (listener != NULL && mListener != NULL) {
1590 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1591 }
1592 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001593 mRequestThread->setNotificationListener(listener);
1594 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001595
1596 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597}
1598
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001599bool Camera3Device::willNotify3A() {
1600 return false;
1601}
1602
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001604 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001605 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001606
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001607 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001608 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1609 if (st == std::cv_status::timeout) {
1610 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001611 }
1612 }
1613 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614}
1615
Jianing Weicb0652e2014-03-12 18:29:36 -07001616status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001618 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001620 if (mResultQueue.empty()) {
1621 return NOT_ENOUGH_DATA;
1622 }
1623
Jianing Weicb0652e2014-03-12 18:29:36 -07001624 if (frame == NULL) {
1625 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1626 return BAD_VALUE;
1627 }
1628
1629 CaptureResult &result = *(mResultQueue.begin());
1630 frame->mResultExtras = result.mResultExtras;
1631 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001632 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001633 mResultQueue.erase(mResultQueue.begin());
1634
1635 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001636}
1637
1638status_t Camera3Device::triggerAutofocus(uint32_t id) {
1639 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001640 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001642 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1643 // Mix-in this trigger into the next request and only the next request.
1644 RequestTrigger trigger[] = {
1645 {
1646 ANDROID_CONTROL_AF_TRIGGER,
1647 ANDROID_CONTROL_AF_TRIGGER_START
1648 },
1649 {
1650 ANDROID_CONTROL_AF_TRIGGER_ID,
1651 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001652 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001653 };
1654
1655 return mRequestThread->queueTrigger(trigger,
1656 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001657}
1658
1659status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1660 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001663 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1664 // Mix-in this trigger into the next request and only the next request.
1665 RequestTrigger trigger[] = {
1666 {
1667 ANDROID_CONTROL_AF_TRIGGER,
1668 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1669 },
1670 {
1671 ANDROID_CONTROL_AF_TRIGGER_ID,
1672 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001673 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001674 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001676 return mRequestThread->queueTrigger(trigger,
1677 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001678}
1679
1680status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1681 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001682 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001683
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001684 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1685 // Mix-in this trigger into the next request and only the next request.
1686 RequestTrigger trigger[] = {
1687 {
1688 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1689 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1690 },
1691 {
1692 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1693 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001694 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001695 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 return mRequestThread->queueTrigger(trigger,
1698 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001699}
1700
Jianing Weicb0652e2014-03-12 18:29:36 -07001701status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001702 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001703 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001705
Zhijun He7ef20392014-04-21 16:04:17 -07001706 {
1707 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001708
1709 // b/116514106 "disconnect()" can get called twice for the same device. The
1710 // camera device will not be initialized during the second run.
1711 if (mStatus == STATUS_UNINITIALIZED) {
1712 return OK;
1713 }
1714
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001715 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001716
1717 // Stop session and stream counter
1718 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001719 }
1720
Emilian Peev08dd2452017-04-06 16:55:14 +01001721 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001722}
1723
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001724status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001725 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1726}
1727
1728status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001729 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001730 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001731 Mutex::Autolock il(mInterfaceLock);
1732 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001733
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001734 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1735 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001736 CLOGE("Stream %d does not exist", streamId);
1737 return BAD_VALUE;
1738 }
1739
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001741 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001742 return BAD_VALUE;
1743 }
1744
1745 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001746 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001747 return BAD_VALUE;
1748 }
1749
Ruben Brunkc78ac262015-08-13 17:58:46 -07001750 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001751}
1752
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001753status_t Camera3Device::tearDown(int streamId) {
1754 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001755 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001756 Mutex::Autolock il(mInterfaceLock);
1757 Mutex::Autolock l(mLock);
1758
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001759 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1760 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001761 CLOGE("Stream %d does not exist", streamId);
1762 return BAD_VALUE;
1763 }
1764
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001765 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1766 CLOGE("Stream %d is a target of a in-progress request", streamId);
1767 return BAD_VALUE;
1768 }
1769
1770 return stream->tearDown();
1771}
1772
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001773status_t Camera3Device::addBufferListenerForStream(int streamId,
1774 wp<Camera3StreamBufferListener> listener) {
1775 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001776 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001777 Mutex::Autolock il(mInterfaceLock);
1778 Mutex::Autolock l(mLock);
1779
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001780 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1781 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001782 CLOGE("Stream %d does not exist", streamId);
1783 return BAD_VALUE;
1784 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001785 stream->addBufferListener(listener);
1786
1787 return OK;
1788}
1789
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001790/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791 * Methods called by subclasses
1792 */
1793
1794void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001795 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001796 std::vector<int> streamIds;
1797 std::vector<hardware::CameraStreamStats> streamStats;
1798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 {
1800 // Need mLock to safely update state and synchronize to current
1801 // state of methods in flight.
1802 Mutex::Autolock l(mLock);
1803 // We can get various system-idle notices from the status tracker
1804 // while starting up. Only care about them if we've actually sent
1805 // in some requests recently.
1806 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1807 return;
1808 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001809 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1810 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001811 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812
1813 // Skip notifying listener if we're doing some user-transparent
1814 // state changes
1815 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001816
1817 // Populate stream statistics in case of Idle
1818 if (idle) {
1819 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1820 auto stream = mOutputStreams[i];
1821 if (stream.get() == nullptr) continue;
1822 streamIds.push_back(stream->getId());
1823 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1824 int64_t usage = 0LL;
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001825 int streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001826 if (camera3Stream != nullptr) {
1827 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001828 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001829 }
1830 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1831 stream->getFormat(), stream->getDataSpace(), usage,
1832 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001833 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001834 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001835 }
1836 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001837 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001838
1839 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001840 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001841 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001842 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001844 status_t res = OK;
1845 if (listener != nullptr) {
1846 if (idle) {
1847 // Get session stats from the builder, and notify the listener.
1848 int64_t requestCount, resultErrorCount;
1849 bool deviceError;
1850 std::map<int, StreamStats> streamStatsMap;
1851 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1852 &deviceError, &streamStatsMap);
1853 for (size_t i = 0; i < streamIds.size(); i++) {
1854 int streamId = streamIds[i];
1855 auto stats = streamStatsMap.find(streamId);
1856 if (stats != streamStatsMap.end()) {
1857 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1858 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1859 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1860 streamStats[i].mHistogramType =
1861 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1862 streamStats[i].mHistogramBins.assign(
1863 stats->second.mCaptureLatencyBins.begin(),
1864 stats->second.mCaptureLatencyBins.end());
1865 streamStats[i].mHistogramCounts.assign(
1866 stats->second.mCaptureLatencyHistogram.begin(),
1867 stats->second.mCaptureLatencyHistogram.end());
1868 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001869 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001870 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1871 } else {
1872 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001873 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001874 }
1875 if (res != OK) {
1876 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1877 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 }
1879}
1880
Shuzhen Wang758c2152017-01-10 18:26:18 -08001881status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001882 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001883 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001884 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1885 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001886
1887 if (surfaceIds == nullptr) {
1888 return BAD_VALUE;
1889 }
1890
Zhijun He5d677d12016-05-29 16:52:39 -07001891 Mutex::Autolock il(mInterfaceLock);
1892 Mutex::Autolock l(mLock);
1893
Shuzhen Wang758c2152017-01-10 18:26:18 -08001894 if (consumers.size() == 0) {
1895 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001896 return BAD_VALUE;
1897 }
1898
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001899 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1900 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001901 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001902 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001903 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001904
1905 // isConsumerConfigurationDeferred will be off after setConsumers
1906 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001907 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001908 if (res != OK) {
1909 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1910 return res;
1911 }
1912
Emilian Peev40ead602017-09-26 15:46:36 +01001913 for (auto &consumer : consumers) {
1914 int id = stream->getSurfaceId(consumer);
1915 if (id < 0) {
1916 CLOGE("Invalid surface id!");
1917 return BAD_VALUE;
1918 }
1919 surfaceIds->push_back(id);
1920 }
1921
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001922 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001923 if (!stream->isConfiguring()) {
1924 CLOGE("Stream %d was already fully configured.", streamId);
1925 return INVALID_OPERATION;
1926 }
Zhijun He5d677d12016-05-29 16:52:39 -07001927
Shuzhen Wang0129d522016-10-30 22:43:41 -07001928 res = stream->finishConfiguration();
1929 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001930 // If finishConfiguration fails due to abandoned surface, do not set
1931 // device to error state.
1932 bool isSurfaceAbandoned =
1933 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1934 if (!isSurfaceAbandoned) {
1935 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1936 stream->getId(), strerror(-res), res);
1937 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001938 return res;
1939 }
Zhijun He5d677d12016-05-29 16:52:39 -07001940 }
1941
1942 return OK;
1943}
1944
Emilian Peev40ead602017-09-26 15:46:36 +01001945status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1946 const std::vector<OutputStreamInfo> &outputInfo,
1947 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1948 Mutex::Autolock il(mInterfaceLock);
1949 Mutex::Autolock l(mLock);
1950
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001951 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1952 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001953 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001954 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001955 }
1956
1957 for (const auto &it : removedSurfaceIds) {
1958 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1959 CLOGE("Shared surface still part of a pending request!");
1960 return -EBUSY;
1961 }
1962 }
1963
Emilian Peev40ead602017-09-26 15:46:36 +01001964 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1965 if (res != OK) {
1966 CLOGE("Stream %d failed to update stream (error %d %s) ",
1967 streamId, res, strerror(-res));
1968 if (res == UNKNOWN_ERROR) {
1969 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1970 __FUNCTION__);
1971 }
1972 return res;
1973 }
1974
1975 return res;
1976}
1977
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001978status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1979 Mutex::Autolock il(mInterfaceLock);
1980 Mutex::Autolock l(mLock);
1981
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001982 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1983 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001984 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1985 return BAD_VALUE;
1986 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001987
1988 if (dropping) {
1989 mSessionStatsBuilder.stopCounter(streamId);
1990 } else {
1991 mSessionStatsBuilder.startCounter(streamId);
1992 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001993 return stream->dropBuffers(dropping);
1994}
1995
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001996/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001997 * Camera3Device private methods
1998 */
1999
2000sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002001 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002002 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002003
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002004 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002005 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002006
2007 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002008 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002009 if (inputStreams.count > 0) {
2010 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002011 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002012 CLOGE("Request references unknown input stream %d",
2013 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002014 return NULL;
2015 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002016
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002017 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002018 SET_ERR_L("%s: input stream %d is not configured!",
2019 __FUNCTION__, mInputStream->getId());
2020 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002021 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002022 // Check if stream prepare is blocking requests.
2023 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002024 CLOGE("Request references an input stream that's being prepared!");
2025 return NULL;
2026 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027
2028 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002029 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002030 }
2031
2032 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002033 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002034 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002035 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002036 return NULL;
2037 }
2038
2039 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002040 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2041 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002042 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002043 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002044 return NULL;
2045 }
Zhijun He5d677d12016-05-29 16:52:39 -07002046 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002047 auto iter = surfaceMap.find(streams.data.i32[i]);
2048 if (iter != surfaceMap.end()) {
2049 const std::vector<size_t>& surfaces = iter->second;
2050 for (const auto& surface : surfaces) {
2051 if (stream->isConsumerConfigurationDeferred(surface)) {
2052 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2053 "due to deferred consumer", stream->getId(), surface);
2054 return NULL;
2055 }
2056 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002057 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002058 }
2059
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002060 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002061 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2062 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002064 // Check if stream prepare is blocking requests.
2065 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002066 CLOGE("Request references an output stream that's being prepared!");
2067 return NULL;
2068 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069
2070 newRequest->mOutputStreams.push(stream);
2071 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002072 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002073 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002075 auto rotateAndCropEntry =
2076 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2077 if (rotateAndCropEntry.count > 0 &&
2078 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2079 newRequest->mRotateAndCropAuto = true;
2080 } else {
2081 newRequest->mRotateAndCropAuto = false;
2082 }
2083
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002084 auto zoomRatioEntry =
2085 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2086 if (zoomRatioEntry.count > 0 &&
2087 zoomRatioEntry.data.f[0] == 1.0f) {
2088 newRequest->mZoomRatioIs1x = true;
2089 } else {
2090 newRequest->mZoomRatioIs1x = false;
2091 }
2092
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002093 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002094 for (auto& settings : newRequest->mSettingsList) {
2095 auto testPatternModeEntry =
2096 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2097 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2098 testPatternModeEntry.data.i32[0] :
2099 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002100
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002101 auto testPatternDataEntry =
2102 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2103 if (testPatternDataEntry.count >= 4) {
2104 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2105 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2106 } else {
2107 settings.mOriginalTestPatternData[0] = 0;
2108 settings.mOriginalTestPatternData[1] = 0;
2109 settings.mOriginalTestPatternData[2] = 0;
2110 settings.mOriginalTestPatternData[3] = 0;
2111 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002112 }
2113 }
2114
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002116}
2117
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002118void Camera3Device::cancelStreamsConfigurationLocked() {
2119 int res = OK;
2120 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2121 res = mInputStream->cancelConfiguration();
2122 if (res != OK) {
2123 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2124 mInputStream->getId(), strerror(-res), res);
2125 }
2126 }
2127
2128 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002130 if (outputStream->isConfiguring()) {
2131 res = outputStream->cancelConfiguration();
2132 if (res != OK) {
2133 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2134 outputStream->getId(), strerror(-res), res);
2135 }
2136 }
2137 }
2138
2139 // Return state to that at start of call, so that future configures
2140 // properly clean things up
2141 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2142 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002143
2144 res = mPreparerThread->resume();
2145 if (res != OK) {
2146 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2147 }
2148}
2149
Emilian Peev0d0191e2020-04-21 17:01:18 -07002150bool Camera3Device::checkAbandonedStreamsLocked() {
2151 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2152 return true;
2153 }
2154
2155 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2156 auto stream = mOutputStreams[i];
2157 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2158 return true;
2159 }
2160 }
2161
2162 return false;
2163}
2164
Emilian Peev3bead5f2020-05-28 17:29:08 -07002165bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002166 ATRACE_CALL();
2167 bool ret = false;
2168
Shuzhen Wang316781a2020-08-18 18:11:01 -07002169 nsecs_t startTime = systemTime();
2170
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002171 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002172 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2173
2174 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002175 if (checkAbandonedStreamsLocked()) {
2176 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2177 __FUNCTION__);
2178 return true;
2179 }
2180
Emilian Peev3bead5f2020-05-28 17:29:08 -07002181 status_t rc = NO_ERROR;
2182 bool markClientActive = false;
2183 if (mStatus == STATUS_ACTIVE) {
2184 markClientActive = true;
2185 mPauseStateNotify = true;
2186 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2187
2188 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2189 }
2190
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002191 if (rc == NO_ERROR) {
2192 mNeedConfig = true;
2193 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2194 if (rc == NO_ERROR) {
2195 ret = true;
2196 mPauseStateNotify = false;
2197 //Moving to active state while holding 'mLock' is important.
2198 //There could be pending calls to 'create-/deleteStream' which
2199 //will trigger another stream configuration while the already
2200 //present streams end up with outstanding buffers that will
2201 //not get drained.
2202 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002203 } else if (rc == DEAD_OBJECT) {
2204 // DEAD_OBJECT can be returned if either the consumer surface is
2205 // abandoned, or the HAL has died.
2206 // - If the HAL has died, configureStreamsLocked call will set
2207 // device to error state,
2208 // - If surface is abandoned, we should not set device to error
2209 // state.
2210 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002211 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002212 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002213 }
2214 } else {
2215 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2216 }
2217
Shuzhen Wang316781a2020-08-18 18:11:01 -07002218 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2219 ns2ms(systemTime() - startTime));
2220
Emilian Peev3bead5f2020-05-28 17:29:08 -07002221 if (markClientActive) {
2222 mStatusTracker->markComponentActive(clientStatusId);
2223 }
2224
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002225 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002226}
2227
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002228status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002229 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002230 ATRACE_CALL();
2231 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002232
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002234 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235 return INVALID_OPERATION;
2236 }
2237
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002238 if (operatingMode < 0) {
2239 CLOGE("Invalid operating mode: %d", operatingMode);
2240 return BAD_VALUE;
2241 }
2242
2243 bool isConstrainedHighSpeed =
2244 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2245 operatingMode;
2246
2247 if (mOperatingMode != operatingMode) {
2248 mNeedConfig = true;
2249 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2250 mOperatingMode = operatingMode;
2251 }
2252
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002253 // In case called from configureStreams, abort queued input buffers not belonging to
2254 // any pending requests.
2255 if (mInputStream != NULL && notifyRequestThread) {
2256 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002257 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002258 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002259 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002260 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002261 if (res != OK) {
2262 // Exhausted acquiring all input buffers.
2263 break;
2264 }
2265
Emilian Peevf4816702020-04-03 15:44:51 -07002266 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002267 res = mInputStream->returnInputBuffer(inputBuffer);
2268 if (res != OK) {
2269 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2270 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2271 }
2272 }
2273 }
2274
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002275 if (!mNeedConfig) {
2276 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2277 return OK;
2278 }
2279
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002280 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002281 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002282 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2283 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002284 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002285 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002286 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002287 }
2288
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002290 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002292 mPreparerThread->pause();
2293
Emilian Peevf4816702020-04-03 15:44:51 -07002294 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002295 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002297 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298
Emilian Peevf4816702020-04-03 15:44:51 -07002299 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002301 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002302
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002303
2304 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002305 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 inputStream = mInputStream->startConfiguration();
2307 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002308 CLOGE("Can't start input stream configuration");
2309 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 return INVALID_OPERATION;
2311 }
2312 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002313
2314 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002315 }
2316
Shuzhen Wang99080502021-03-07 21:08:20 -08002317 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002318 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002320
2321 // Don't configure bidi streams twice, nor add them twice to the list
2322 if (mOutputStreams[i].get() ==
2323 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2324
2325 config.num_streams--;
2326 continue;
2327 }
2328
Emilian Peevf4816702020-04-03 15:44:51 -07002329 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002330 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002332 CLOGE("Can't start output stream configuration");
2333 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002334 return INVALID_OPERATION;
2335 }
2336 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002337
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002338 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002339 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2340 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002341 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2342 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002343 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2344 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002345 } else if (outputStream->data_space ==
2346 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2347 bufferSizes[k] = outputStream->width * outputStream->height;
2348 } else {
2349 ALOGW("%s: Blob dataSpace %d not supported",
2350 __FUNCTION__, outputStream->data_space);
2351 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002352 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002353
2354 if (mOutputStreams[i]->isMultiResolution()) {
2355 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2356 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2357 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2358 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002359
2360 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2361 composerSurfacePresent = true;
2362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363 }
2364
2365 config.streams = streams.editArray();
2366
2367 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002368 // max_buffers, usage, and priv fields, as well as data_space and format
2369 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002370
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002371 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002372 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002373 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002375 if (res == BAD_VALUE) {
2376 // HAL rejected this set of streams as unsupported, clean up config
2377 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002378 CLOGE("Set of requested inputs/outputs not supported by HAL");
2379 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002380 return BAD_VALUE;
2381 } else if (res != OK) {
2382 // Some other kind of error from configure_streams - this is not
2383 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002384 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2385 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386 return res;
2387 }
2388
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002389 // Finish all stream configuration immediately.
2390 // TODO: Try to relax this later back to lazy completion, which should be
2391 // faster
2392
Igor Murashkin073f8572013-05-02 14:59:28 -07002393 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002394 bool streamReConfigured = false;
2395 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002396 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002397 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002398 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002399 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002400 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2401 return DEAD_OBJECT;
2402 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002403 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002404 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002405 if (streamReConfigured) {
2406 mInterface->onStreamReConfigured(mInputStream->getId());
2407 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002408 }
2409
2410 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002411 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002412 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002413 bool streamReConfigured = false;
2414 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002415 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002416 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002417 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002418 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002419 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2420 return DEAD_OBJECT;
2421 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002422 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002423 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002424 if (streamReConfigured) {
2425 mInterface->onStreamReConfigured(outputStream->getId());
2426 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002427 }
2428 }
2429
Emilian Peeve23f1d92021-09-20 14:56:01 -07002430 mRequestThread->setComposerSurface(composerSurfacePresent);
2431
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002432 // Request thread needs to know to avoid using repeat-last-settings protocol
2433 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002434 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002435 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2436 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002437 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002438
Zhijun He90f7c372016-08-16 16:19:43 -07002439 char value[PROPERTY_VALUE_MAX];
2440 property_get("camera.fifo.disable", value, "0");
2441 int32_t disableFifo = atoi(value);
2442 if (disableFifo != 1) {
2443 // Boost priority of request thread to SCHED_FIFO.
2444 pid_t requestThreadTid = mRequestThread->getTid();
2445 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002446 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002447 if (res != OK) {
2448 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2449 strerror(-res), res);
2450 } else {
2451 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2452 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002453 }
2454
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002455 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002456 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2457 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2458 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2459 sessionParams.unlock(newSessionParams);
2460 mSessionParams.unlock(currentSessionParams);
2461 if (updateSessionParams) {
2462 mSessionParams = sessionParams;
2463 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002465 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002467 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002468 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002469
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002470 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002471
Zhijun He0a210512014-07-24 13:45:15 -07002472 // tear down the deleted streams after configure streams.
2473 mDeletedStreams.clear();
2474
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002475 auto rc = mPreparerThread->resume();
2476 if (rc != OK) {
2477 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2478 return rc;
2479 }
2480
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002481 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002482 mRequestBufferSM.onStreamsConfigured();
2483 }
2484
Cliff Wu3b268182021-07-06 15:44:43 +08002485 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002486 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002487 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002488 // configure the injection streams.
2489 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002490 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002491 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2492 res = mInjectionMethods->injectCamera(config, bufferSizes);
2493 if (res != OK) {
2494 ALOGE("Can't finish inject camera process!");
2495 return res;
2496 }
Cliff Wu3b268182021-07-06 15:44:43 +08002497 } else {
2498 // First run configureStreamsLocked() and then call injectCamera() case:
2499 // If the stream configuration has been completed and camera deive is active, but the
2500 // injection camera has not been injected yet, we need to store the stream configuration of
2501 // the internal camera (because the stream configuration of the injection camera is based
2502 // on the internal camera). When injecting occurs later, this configuration can be used by
2503 // the injection camera.
2504 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2505 " injection camera has not been injected yet.", __FUNCTION__);
2506 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002507 }
2508
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002509 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002510}
2511
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002512status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002513 ATRACE_CALL();
2514 status_t res;
2515
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002516 if (mFakeStreamId != NO_STREAM) {
2517 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002518 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002519 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002520 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002521 return INVALID_OPERATION;
2522 }
2523
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002524 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002525
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002526 sp<Camera3OutputStreamInterface> fakeStream =
2527 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002528
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002529 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002530 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002531 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002532 return res;
2533 }
2534
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002535 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002536 mNextStreamId++;
2537
2538 return OK;
2539}
2540
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002541status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002542 ATRACE_CALL();
2543 status_t res;
2544
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002545 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002546 if (mOutputStreams.size() == 1) return OK;
2547
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002548 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002549
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 // Ok, have a fake stream and there's at least one other output stream,
2551 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002552
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002553 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002554 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 return INVALID_OPERATION;
2557 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002558 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002559
2560 // Free up the stream endpoint so that it can be used by some other stream
2561 res = deletedStream->disconnect();
2562 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002563 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002564 // fall through since we want to still list the stream as deleted.
2565 }
2566 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002567 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002568
2569 return res;
2570}
2571
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002572void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002573 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002574 Mutex::Autolock l(mLock);
2575 va_list args;
2576 va_start(args, fmt);
2577
2578 setErrorStateLockedV(fmt, args);
2579
2580 va_end(args);
2581}
2582
2583void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002584 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002585 Mutex::Autolock l(mLock);
2586 setErrorStateLockedV(fmt, args);
2587}
2588
2589void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2590 va_list args;
2591 va_start(args, fmt);
2592
2593 setErrorStateLockedV(fmt, args);
2594
2595 va_end(args);
2596}
2597
2598void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002599 // Print out all error messages to log
2600 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002601 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002602
2603 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002604 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002605
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002606 mErrorCause = errorCause;
2607
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002608 if (mRequestThread != nullptr) {
2609 mRequestThread->setPaused(true);
2610 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002611 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002612
2613 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002614 sp<NotificationListener> listener = mListener.promote();
2615 if (listener != NULL) {
2616 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002617 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002618 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002619 }
2620
2621 // Save stack trace. View by dumping it later.
2622 CameraTraces::saveTrace();
2623 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002624}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002625
2626/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002627 * In-flight request management
2628 */
2629
Jianing Weicb0652e2014-03-12 18:29:36 -07002630status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002631 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002632 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002633 const std::set<std::set<String8>>& physicalCameraIds,
2634 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2635 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002636 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002637 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002638 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002639
2640 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002641 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002642 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002643 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002644 if (res < 0) return res;
2645
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002646 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002647 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2648 // avoid a deadlock during reprocess requests.
2649 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002650 if (mStatusTracker != nullptr) {
2651 mStatusTracker->markComponentActive(mInFlightStatusId);
2652 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002653 }
2654
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002655 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002656 return OK;
2657}
2658
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002659void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002660 // Indicate idle inFlightMap to the status tracker
2661 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002662 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002663 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2664 // avoid a deadlock during reprocess requests.
2665 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002666 if (mStatusTracker != nullptr) {
2667 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2668 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002669 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002670 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002671}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002672
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002673void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002674 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002675 // something has likely gone wrong. This might still be legit only if application send in
2676 // a long burst of long exposure requests.
2677 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2678 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2679 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2680 mInFlightMap.size(), mExpectedInflightDuration);
2681 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2682 kInFlightWarnLimitHighSpeed) {
2683 CLOGW("In-flight list too large for high speed configuration: %zu,"
2684 "total inflight duration %" PRIu64,
2685 mInFlightMap.size(), mExpectedInflightDuration);
2686 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002687 }
2688}
2689
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002690void Camera3Device::onInflightMapFlushedLocked() {
2691 mExpectedInflightDuration = 0;
2692}
2693
2694void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002695 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002696 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2697 mInFlightMap.removeItemsAt(idx, 1);
2698
2699 onInflightEntryRemovedLocked(duration);
2700}
2701
2702
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002703void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002704 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002705 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002706 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002707 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002708 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002709 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002710
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002711 FlushInflightReqStates states {
2712 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002713 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002714
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002715 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002716}
2717
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002718CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002719 ALOGV("%s", __FUNCTION__);
2720
Igor Murashkin1e479c02013-09-06 16:55:14 -07002721 CameraMetadata retVal;
2722
2723 if (mRequestThread != NULL) {
2724 retVal = mRequestThread->getLatestRequest();
2725 }
2726
Igor Murashkin1e479c02013-09-06 16:55:14 -07002727 return retVal;
2728}
2729
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002730void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002731 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002732 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002733 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2734 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002735
2736 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002737 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002738}
2739
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002740void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002741 std::vector<native_handle_t*> *handles, bool closeFd) {
2742 if (handles == nullptr) {
2743 return;
2744 }
2745 if (closeFd) {
2746 for (auto& handle : *handles) {
2747 native_handle_close(handle);
2748 }
2749 }
2750 for (auto& handle : *handles) {
2751 native_handle_delete(handle);
2752 }
2753 handles->clear();
2754 return;
2755}
2756
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002757/**
2758 * HalInterface inner class methods
2759 */
2760
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002761void Camera3Device::HalInterface::getInflightBufferKeys(
2762 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002763 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002764 return;
2765}
2766
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002767void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2768 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002769 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002770 return;
2771}
2772
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002773bool Camera3Device::HalInterface::verifyBufferIds(
2774 int32_t streamId, std::vector<uint64_t>& bufIds) {
2775 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002776}
2777
2778status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002779 int32_t frameNumber, int32_t streamId,
2780 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002781 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002782}
2783
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002784status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002785 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002786 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002787}
2788
2789// Find and pop a buffer_handle_t based on bufferId
2790status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002791 uint64_t bufferId,
2792 /*out*/ buffer_handle_t** buffer,
2793 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002794 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002795}
2796
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002797std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2798 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002799 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002800}
2801
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002802uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2803 const native_handle_t* handle) {
2804 return mBufferRecords.removeOneBufferCache(streamId, handle);
2805}
2806
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002807void Camera3Device::HalInterface::onBufferFreed(
2808 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002809 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2810 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2811 if (bufferId != BUFFER_ID_NO_BUFFER) {
2812 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002813 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002814}
2815
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002816void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002817 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2818 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2819 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002820 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2821 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002822}
2823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825 * RequestThread inner class methods
2826 */
2827
2828Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002829 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002830 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002831 bool useHalBufManager,
2832 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002833 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002834 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002835 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002836 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002837 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002838 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002839 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002840 mReconfigured(false),
2841 mDoPause(false),
2842 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002843 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002844 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002845 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002846 mCurrentAfTriggerId(0),
2847 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002848 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002849 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002850 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002851 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002852 mRepeatingLastFrameNumber(
2853 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002854 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002855 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002856 mRequestLatency(kRequestLatencyBinSize),
2857 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002858 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002859 mUseHalBufManager(useHalBufManager),
2860 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002861 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862}
2863
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002864Camera3Device::RequestThread::~RequestThread() {}
2865
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002866void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002867 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002868 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869 Mutex::Autolock l(mRequestLock);
2870 mListener = listener;
2871}
2872
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002873void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002874 const CameraMetadata& sessionParams,
2875 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002876 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002877 Mutex::Autolock l(mRequestLock);
2878 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002879 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002880 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002881 // Prepare video stream for high speed recording.
2882 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002883 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002884}
2885
Jianing Wei90e59c92014-03-12 18:29:36 -07002886status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002887 List<sp<CaptureRequest> > &requests,
2888 /*out*/
2889 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002890 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002891 Mutex::Autolock l(mRequestLock);
2892 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2893 ++it) {
2894 mRequestQueue.push_back(*it);
2895 }
2896
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002897 if (lastFrameNumber != NULL) {
2898 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2899 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2900 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2901 *lastFrameNumber);
2902 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002903
Jianing Wei90e59c92014-03-12 18:29:36 -07002904 unpauseForNewRequests();
2905
2906 return OK;
2907}
2908
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002909
2910status_t Camera3Device::RequestThread::queueTrigger(
2911 RequestTrigger trigger[],
2912 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002913 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002914 Mutex::Autolock l(mTriggerMutex);
2915 status_t ret;
2916
2917 for (size_t i = 0; i < count; ++i) {
2918 ret = queueTriggerLocked(trigger[i]);
2919
2920 if (ret != OK) {
2921 return ret;
2922 }
2923 }
2924
2925 return OK;
2926}
2927
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002928const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2929 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002930 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002931 if (d != nullptr) return d->mId;
2932 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002933}
2934
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002935status_t Camera3Device::RequestThread::queueTriggerLocked(
2936 RequestTrigger trigger) {
2937
2938 uint32_t tag = trigger.metadataTag;
2939 ssize_t index = mTriggerMap.indexOfKey(tag);
2940
2941 switch (trigger.getTagType()) {
2942 case TYPE_BYTE:
2943 // fall-through
2944 case TYPE_INT32:
2945 break;
2946 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002947 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2948 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002949 return INVALID_OPERATION;
2950 }
2951
2952 /**
2953 * Collect only the latest trigger, since we only have 1 field
2954 * in the request settings per trigger tag, and can't send more than 1
2955 * trigger per request.
2956 */
2957 if (index != NAME_NOT_FOUND) {
2958 mTriggerMap.editValueAt(index) = trigger;
2959 } else {
2960 mTriggerMap.add(tag, trigger);
2961 }
2962
2963 return OK;
2964}
2965
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002966status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002967 const RequestList &requests,
2968 /*out*/
2969 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002970 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002972 if (lastFrameNumber != NULL) {
2973 *lastFrameNumber = mRepeatingLastFrameNumber;
2974 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002975 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002976 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2978 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002979
2980 unpauseForNewRequests();
2981
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002982 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002983 return OK;
2984}
2985
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002986bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002987 if (mRepeatingRequests.empty()) {
2988 return false;
2989 }
2990 int32_t requestId = requestIn->mResultExtras.requestId;
2991 const RequestList &repeatRequests = mRepeatingRequests;
2992 // All repeating requests are guaranteed to have same id so only check first quest
2993 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2994 return (firstRequest->mResultExtras.requestId == requestId);
2995}
2996
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002997status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002998 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002999 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003000 return clearRepeatingRequestsLocked(lastFrameNumber);
3001
3002}
3003
3004status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003005 std::vector<int32_t> streamIds;
3006 for (const auto& request : mRepeatingRequests) {
3007 for (const auto& stream : request->mOutputStreams) {
3008 streamIds.push_back(stream->getId());
3009 }
3010 }
3011
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003012 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003013 if (lastFrameNumber != NULL) {
3014 *lastFrameNumber = mRepeatingLastFrameNumber;
3015 }
Emilian Peev2295df72021-11-12 18:14:10 -08003016
3017 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3018
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003020 return OK;
3021}
3022
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003023status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003024 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003025 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003026 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003027 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003028
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003029 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003030
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003031 // Send errors for all requests pending in the request queue, including
3032 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003033 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003034 if (listener != NULL) {
3035 for (RequestList::iterator it = mRequestQueue.begin();
3036 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003037 // Abort the input buffers for reprocess requests.
3038 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003039 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003040 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003041 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003042 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003043 if (res != OK) {
3044 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3045 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3046 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003047 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003048 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3049 if (res != OK) {
3050 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3051 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3052 }
3053 }
3054 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003055 // Set the frame number this request would have had, if it
3056 // had been submitted; this frame number will not be reused.
3057 // The requestId and burstId fields were set when the request was
3058 // submitted originally (in convertMetadataListToRequestListLocked)
3059 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003060 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003061 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003062 }
3063 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003064 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003065
3066 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003067 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003068 if (lastFrameNumber != NULL) {
3069 *lastFrameNumber = mRepeatingLastFrameNumber;
3070 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003072 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003073 return OK;
3074}
3075
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003076status_t Camera3Device::RequestThread::flush() {
3077 ATRACE_CALL();
3078 Mutex::Autolock l(mFlushLock);
3079
Emilian Peev08dd2452017-04-06 16:55:14 +01003080 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003081}
3082
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003083void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003084 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003085 Mutex::Autolock l(mPauseLock);
3086 mDoPause = paused;
3087 mDoPauseSignal.signal();
3088}
3089
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003090status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3091 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003092 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003093 Mutex::Autolock l(mLatestRequestMutex);
3094 status_t res;
3095 while (mLatestRequestId != requestId) {
3096 nsecs_t startTime = systemTime();
3097
3098 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3099 if (res != OK) return res;
3100
3101 timeout -= (systemTime() - startTime);
3102 }
3103
3104 return OK;
3105}
3106
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003107void Camera3Device::RequestThread::requestExit() {
3108 // Call parent to set up shutdown
3109 Thread::requestExit();
3110 // The exit from any possible waits
3111 mDoPauseSignal.signal();
3112 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003113
3114 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3115 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003116}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003117
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003118void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003119 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003120 bool surfaceAbandoned = false;
3121 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003122 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003123 {
3124 Mutex::Autolock l(mRequestLock);
3125 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3126 // repeating requests.
3127 for (const auto& request : mRepeatingRequests) {
3128 for (const auto& s : request->mOutputStreams) {
3129 if (s->isAbandoned()) {
3130 surfaceAbandoned = true;
3131 clearRepeatingRequestsLocked(&lastFrameNumber);
3132 break;
3133 }
3134 }
3135 if (surfaceAbandoned) {
3136 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003137 }
3138 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003139 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003140 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003141
3142 if (listener != NULL && surfaceAbandoned) {
3143 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003144 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003145}
3146
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003147bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003148 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003149 status_t res;
3150 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003151 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003152 uint32_t numRequestProcessed = 0;
3153 for (size_t i = 0; i < batchSize; i++) {
3154 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003155 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003156 }
3157
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003158 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3159
3160 bool triggerRemoveFailed = false;
3161 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3162 for (size_t i = 0; i < numRequestProcessed; i++) {
3163 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3164 nextRequest.submitted = true;
3165
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003166 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003167
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003168 if (!triggerRemoveFailed) {
3169 // Remove any previously queued triggers (after unlock)
3170 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3171 if (removeTriggerRes != OK) {
3172 triggerRemoveFailed = true;
3173 triggerFailedRequest = nextRequest;
3174 }
3175 }
3176 }
3177
3178 if (triggerRemoveFailed) {
3179 SET_ERR("RequestThread: Unable to remove triggers "
3180 "(capture request %d, HAL device: %s (%d)",
3181 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3182 cleanUpFailedRequests(/*sendRequestError*/ false);
3183 return false;
3184 }
3185
3186 if (res != OK) {
3187 // Should only get a failure here for malformed requests or device-level
3188 // errors, so consider all errors fatal. Bad metadata failures should
3189 // come through notify.
3190 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3191 mNextRequests[numRequestProcessed].halRequest.frame_number,
3192 strerror(-res), res);
3193 cleanUpFailedRequests(/*sendRequestError*/ false);
3194 return false;
3195 }
3196 return true;
3197}
3198
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003199nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3200 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3201 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3202 find_camera_metadata_ro_entry(request,
3203 ANDROID_CONTROL_AE_MODE,
3204 &e);
3205 if (e.count == 0) return maxExpectedDuration;
3206
3207 switch (e.data.u8[0]) {
3208 case ANDROID_CONTROL_AE_MODE_OFF:
3209 find_camera_metadata_ro_entry(request,
3210 ANDROID_SENSOR_EXPOSURE_TIME,
3211 &e);
3212 if (e.count > 0) {
3213 maxExpectedDuration = e.data.i64[0];
3214 }
3215 find_camera_metadata_ro_entry(request,
3216 ANDROID_SENSOR_FRAME_DURATION,
3217 &e);
3218 if (e.count > 0) {
3219 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3220 }
3221 break;
3222 default:
3223 find_camera_metadata_ro_entry(request,
3224 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3225 &e);
3226 if (e.count > 1) {
3227 maxExpectedDuration = 1e9 / e.data.u8[0];
3228 }
3229 break;
3230 }
3231
3232 return maxExpectedDuration;
3233}
3234
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003235bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3236 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3237 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3238 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3239 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3240 return true;
3241 }
3242
3243 return false;
3244}
3245
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003246void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3247 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003248 camera_capture_request_t& halRequest = nextRequest.halRequest;
3249 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003250 Mutex::Autolock al(mLatestRequestMutex);
3251
Shuzhen Wang83bff122020-11-20 15:51:39 -08003252 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003253 mLatestRequest.acquire(cloned);
3254
3255 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003256 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3257 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3258 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003259 CameraMetadata(cloned));
3260 }
3261
3262 sp<Camera3Device> parent = mParent.promote();
3263 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003264 int32_t inputStreamId = -1;
3265 if (halRequest.input_buffer != nullptr) {
3266 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3267 }
3268
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003269 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003270 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003271 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3272 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003273 }
3274 }
3275
Shuzhen Wang83bff122020-11-20 15:51:39 -08003276 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003277 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003278 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003279 }
3280
Shuzhen Wang83bff122020-11-20 15:51:39 -08003281 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003282}
3283
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003284bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3285 ATRACE_CALL();
3286 bool updatesDetected = false;
3287
Emilian Peev4ec17882019-01-24 17:16:58 -08003288 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003289 for (auto tag : mSessionParamKeys) {
3290 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003291 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003292
3293 if (entry.count > 0) {
3294 bool isDifferent = false;
3295 if (lastEntry.count > 0) {
3296 // Have a last value, compare to see if changed
3297 if (lastEntry.type == entry.type &&
3298 lastEntry.count == entry.count) {
3299 // Same type and count, compare values
3300 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3301 size_t entryBytes = bytesPerValue * lastEntry.count;
3302 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3303 if (cmp != 0) {
3304 isDifferent = true;
3305 }
3306 } else {
3307 // Count or type has changed
3308 isDifferent = true;
3309 }
3310 } else {
3311 // No last entry, so always consider to be different
3312 isDifferent = true;
3313 }
3314
3315 if (isDifferent) {
3316 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003317 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3318 updatesDetected = true;
3319 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003320 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003321 }
3322 } else if (lastEntry.count > 0) {
3323 // Value has been removed
3324 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003325 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003326 updatesDetected = true;
3327 }
3328 }
3329
Emilian Peev4ec17882019-01-24 17:16:58 -08003330 bool reconfigureRequired;
3331 if (updatesDetected) {
3332 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3333 updatedParams);
3334 mLatestSessionParams = updatedParams;
3335 } else {
3336 reconfigureRequired = false;
3337 }
3338
3339 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003340}
3341
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003342bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003343 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003344 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003345 // Any function called from threadLoop() must not hold mInterfaceLock since
3346 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3347 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003348
3349 // Handle paused state.
3350 if (waitIfPaused()) {
3351 return true;
3352 }
3353
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003354 // Wait for the next batch of requests.
3355 waitForNextRequestBatch();
3356 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003357 return true;
3358 }
3359
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003360 // Get the latest request ID, if any
3361 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003362 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003363 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003364 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003365 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003366 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003367 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3368 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003369 }
3370
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003371 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3372 // or a single request from streaming or burst. In either case the first element
3373 // should contain the latest camera settings that we need to check for any session
3374 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003375 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003376 res = OK;
3377
3378 //Input stream buffers are already acquired at this point so an input stream
3379 //will not be able to move to idle state unless we force it.
3380 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3381 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3382 if (res != OK) {
3383 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3384 cleanUpFailedRequests(/*sendRequestError*/ false);
3385 return false;
3386 }
3387 }
3388
3389 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003390 sp<Camera3Device> parent = mParent.promote();
3391 if (parent != nullptr) {
3392 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003393 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003394 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003395
3396 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3397 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3398 if (res != OK) {
3399 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3400 cleanUpFailedRequests(/*sendRequestError*/ false);
3401 return false;
3402 }
3403 }
3404 }
3405 }
3406
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003407 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003408 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003409 if (res == TIMED_OUT) {
3410 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003411 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003412 // Check if any stream is abandoned.
3413 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003414 return true;
3415 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003416 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003417 return false;
3418 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003419
Zhijun Hecc27e112013-10-03 16:12:43 -07003420 // Inform waitUntilRequestProcessed thread of a new request ID
3421 {
3422 Mutex::Autolock al(mLatestRequestMutex);
3423
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003424 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003425 mLatestRequestSignal.signal();
3426 }
3427
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003428 // Submit a batch of requests to HAL.
3429 // Use flush lock only when submitting multilple requests in a batch.
3430 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3431 // which may take a long time to finish so synchronizing flush() and
3432 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3433 // For now, only synchronize for high speed recording and we should figure something out for
3434 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003435 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003436
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003437 if (useFlushLock) {
3438 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003439 }
3440
Zhijun Hef0645c12016-08-02 00:58:11 -07003441 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003442 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003443
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003444 sp<Camera3Device> parent = mParent.promote();
3445 if (parent != nullptr) {
3446 parent->mRequestBufferSM.onSubmittingRequest();
3447 }
3448
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003449 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003450 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003451 submitRequestSuccess = sendRequestsBatch();
3452
Shuzhen Wang686f6442017-06-20 16:16:04 -07003453 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3454 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003455
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003456 if (useFlushLock) {
3457 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003458 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003459
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003460 // Unset as current request
3461 {
3462 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003463 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003464 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003465 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003466
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003467 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003468}
3469
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003470status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3471 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3472 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3473 ANDROID_SCALER_CROP_REGION_SET};
3474 if (request == nullptr) {
3475 ALOGE("%s request metadata nullptr", __FUNCTION__);
3476 return BAD_VALUE;
3477 }
3478 status_t res = OK;
3479 for (const auto &key : kFwkOnlyRegionKeys) {
3480 if (request->exists(key)) {
3481 res = request->erase(key);
3482 if (res != OK) {
3483 return res;
3484 }
3485 }
3486 }
3487 return OK;
3488}
3489
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003490status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003491 ATRACE_CALL();
3492
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003493 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003494 for (size_t i = 0; i < mNextRequests.size(); i++) {
3495 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003496 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003497 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3498 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003499
3500 // Prepare a request to HAL
3501 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3502
3503 // Insert any queued triggers (before metadata is locked)
3504 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003505 if (res < 0) {
3506 SET_ERR("RequestThread: Unable to insert triggers "
3507 "(capture request %d, HAL device: %s (%d)",
3508 halRequest->frame_number, strerror(-res), res);
3509 return INVALID_OPERATION;
3510 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003511
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003512 int triggerCount = res;
3513 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3514 mPrevTriggers = triggerCount;
3515
Emilian Peeve23f1d92021-09-20 14:56:01 -07003516 // Do not override rotate&crop for stream configurations that include
3517 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3518 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3519 bool rotateAndCropChanged = mComposerOutput ? false :
3520 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003521 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003522
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003523 // If the request is the same as last, or we had triggers now or last time or
3524 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003525 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003526 (mPrevRequest != captureRequest || triggersMixedIn ||
3527 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003528 // Request settings are all the same within one batch, so only treat the first
3529 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003530 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003531 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003532 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003533 /**
3534 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003535 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003536 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003537 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003538 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003539 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003540 "(capture request %d, HAL device: %s (%d)",
3541 halRequest->frame_number, strerror(-res), res);
3542 return INVALID_OPERATION;
3543 }
3544
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003545 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003546 sp<Camera3Device> parent = mParent.promote();
3547 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003548 List<PhysicalCameraSettings>::iterator it;
3549 for (it = captureRequest->mSettingsList.begin();
3550 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003551 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3552 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003553 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3554 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3555 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3556 res);
3557 return INVALID_OPERATION;
3558 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003559 continue;
3560 }
3561
3562 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3563 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3564 updateCaptureRequest(&(it->metadata));
3565 if (res != OK) {
3566 SET_ERR("RequestThread: Unable to correct capture requests "
3567 "for scaler crop region and metering regions for request "
3568 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3569 res);
3570 return INVALID_OPERATION;
3571 }
3572 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
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 }
3580 }
3581
3582 // Correct metadata regions for distortion correction if enabled
3583 for (it = captureRequest->mSettingsList.begin();
3584 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003585 if (parent->mDistortionMappers.find(it->cameraId) ==
3586 parent->mDistortionMappers.end()) {
3587 continue;
3588 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003589
3590 if (!captureRequest->mDistortionCorrectionUpdated) {
3591 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3592 &(it->metadata));
3593 if (res != OK) {
3594 SET_ERR("RequestThread: Unable to correct capture requests "
3595 "for lens distortion for request %d: %s (%d)",
3596 halRequest->frame_number, strerror(-res), res);
3597 return INVALID_OPERATION;
3598 }
3599 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003600 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003601 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003602
3603 for (it = captureRequest->mSettingsList.begin();
3604 it != captureRequest->mSettingsList.end(); it++) {
3605 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3606 parent->mZoomRatioMappers.end()) {
3607 continue;
3608 }
3609
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003610 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003611 cameraIdsWithZoom.insert(it->cameraId);
3612 }
3613
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003614 if (!captureRequest->mZoomRatioUpdated) {
3615 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3616 &(it->metadata));
3617 if (res != OK) {
3618 SET_ERR("RequestThread: Unable to correct capture requests "
3619 "for zoom ratio for request %d: %s (%d)",
3620 halRequest->frame_number, strerror(-res), res);
3621 return INVALID_OPERATION;
3622 }
3623 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003624 }
3625 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003626 if (captureRequest->mRotateAndCropAuto &&
3627 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003628 for (it = captureRequest->mSettingsList.begin();
3629 it != captureRequest->mSettingsList.end(); it++) {
3630 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3631 if (mapper != parent->mRotateAndCropMappers.end()) {
3632 res = mapper->second.updateCaptureRequest(&(it->metadata));
3633 if (res != OK) {
3634 SET_ERR("RequestThread: Unable to correct capture requests "
3635 "for rotate-and-crop for request %d: %s (%d)",
3636 halRequest->frame_number, strerror(-res), res);
3637 return INVALID_OPERATION;
3638 }
3639 }
3640 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003641 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003642 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003643 }
3644 }
3645
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003646 /**
3647 * The request should be presorted so accesses in HAL
3648 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3649 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003650 captureRequest->mSettingsList.begin()->metadata.sort();
3651 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003652 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003653 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003654 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3655
3656 IF_ALOGV() {
3657 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3658 find_camera_metadata_ro_entry(
3659 halRequest->settings,
3660 ANDROID_CONTROL_AF_TRIGGER,
3661 &e
3662 );
3663 if (e.count > 0) {
3664 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3665 __FUNCTION__,
3666 halRequest->frame_number,
3667 e.data.u8[0]);
3668 }
3669 }
3670 } else {
3671 // leave request.settings NULL to indicate 'reuse latest given'
3672 ALOGVV("%s: Request settings are REUSED",
3673 __FUNCTION__);
3674 }
3675
Emilian Peevaebbe412018-01-15 13:53:24 +00003676 if (captureRequest->mSettingsList.size() > 1) {
3677 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3678 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003679 if (newRequest) {
3680 halRequest->physcam_settings =
3681 new const camera_metadata* [halRequest->num_physcam_settings];
3682 } else {
3683 halRequest->physcam_settings = nullptr;
3684 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003685 auto it = ++captureRequest->mSettingsList.begin();
3686 size_t i = 0;
3687 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3688 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003689 if (newRequest) {
3690 it->metadata.sort();
3691 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3692 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003693 }
3694 }
3695
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003696 uint32_t totalNumBuffers = 0;
3697
3698 // Fill in buffers
3699 if (captureRequest->mInputStream != NULL) {
3700 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003701
3702 halRequest->input_width = captureRequest->mInputBufferSize.width;
3703 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003704 totalNumBuffers += 1;
3705 } else {
3706 halRequest->input_buffer = NULL;
3707 }
3708
Emilian Peevf4816702020-04-03 15:44:51 -07003709 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003710 captureRequest->mOutputStreams.size());
3711 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003712 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003713
3714 sp<Camera3Device> parent = mParent.promote();
3715 if (parent == NULL) {
3716 // Should not happen, and nowhere to send errors to, so just log it
3717 CLOGE("RequestThread: Parent is gone");
3718 return INVALID_OPERATION;
3719 }
3720 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3721
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003722 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003723 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003724 sp<Camera3OutputStreamInterface> outputStream =
3725 captureRequest->mOutputStreams.editItemAt(j);
3726 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003727
3728 // Prepare video buffers for high speed recording on the first video request.
3729 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3730 // Only try to prepare video stream on the first video request.
3731 mPrepareVideoStream = false;
3732
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003733 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3734 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003735 while (res == NOT_ENOUGH_DATA) {
3736 res = outputStream->prepareNextBuffer();
3737 }
3738 if (res != OK) {
3739 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3740 __FUNCTION__, strerror(-res), res);
3741 outputStream->cancelPrepare();
3742 }
3743 }
3744
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003745 std::vector<size_t> uniqueSurfaceIds;
3746 res = outputStream->getUniqueSurfaceIds(
3747 captureRequest->mOutputSurfaces[streamId],
3748 &uniqueSurfaceIds);
3749 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3750 if (res != OK && res != INVALID_OPERATION) {
3751 ALOGE("%s: failed to query stream %d unique surface IDs",
3752 __FUNCTION__, streamId);
3753 return res;
3754 }
3755 if (res == OK) {
3756 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3757 }
3758
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003759 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003760 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003761 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003762 return TIMED_OUT;
3763 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003764 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003765 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003766 buffer.stream = outputStream->asHalStream();
3767 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003768 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003769 buffer.acquire_fence = -1;
3770 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003771 // Mark the output stream as unpreparable to block clients from calling
3772 // 'prepare' after this request reaches CameraHal and before the respective
3773 // buffers are requested.
3774 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003775 } else {
3776 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3777 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003778 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003779 if (res != OK) {
3780 // Can't get output buffer from gralloc queue - this could be due to
3781 // abandoned queue or other consumer misbehavior, so not a fatal
3782 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003783 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003784 " %s (%d)", strerror(-res), res);
3785
3786 return TIMED_OUT;
3787 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003788 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003789
3790 {
3791 sp<Camera3Device> parent = mParent.promote();
3792 if (parent != nullptr) {
3793 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3794 for (const auto& settings : captureRequest->mSettingsList) {
3795 if ((streamCameraId.isEmpty() &&
3796 parent->getId() == settings.cameraId.c_str()) ||
3797 streamCameraId == settings.cameraId.c_str()) {
3798 outputStream->fireBufferRequestForFrameNumber(
3799 captureRequest->mResultExtras.frameNumber,
3800 settings.metadata);
3801 }
3802 }
3803 }
3804 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003805
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003806 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003807 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3808 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3809 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3810 } else if (!physicalCameraId.isEmpty()) {
3811 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003812 }
3813 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003814 }
3815 totalNumBuffers += halRequest->num_output_buffers;
3816
3817 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003818 // If this request list is for constrained high speed recording (not
3819 // preview), and the current request is not the last one in the batch,
3820 // do not send callback to the app.
3821 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003822 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003823 hasCallback = false;
3824 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003825 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003826 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003827 const camera_metadata_t* settings = halRequest->settings;
3828 bool shouldUnlockSettings = false;
3829 if (settings == nullptr) {
3830 shouldUnlockSettings = true;
3831 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3832 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003833 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3834 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003835 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003836 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3837 isStillCapture = true;
3838 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3839 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003840
Emilian Peevaf8416e2021-02-04 17:52:43 -08003841 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003842 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003843 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3844 isZslCapture = true;
3845 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003846 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003847 res = parent->registerInFlight(halRequest->frame_number,
3848 totalNumBuffers, captureRequest->mResultExtras,
3849 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003850 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003851 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003852 requestedPhysicalCameras, isStillCapture, isZslCapture,
3853 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003854 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003855 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003856 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3857 ", burstId = %" PRId32 ".",
3858 __FUNCTION__,
3859 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3860 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003861
3862 if (shouldUnlockSettings) {
3863 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3864 }
3865
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003866 if (res != OK) {
3867 SET_ERR("RequestThread: Unable to register new in-flight request:"
3868 " %s (%d)", strerror(-res), res);
3869 return INVALID_OPERATION;
3870 }
3871 }
3872
3873 return OK;
3874}
3875
Igor Murashkin1e479c02013-09-06 16:55:14 -07003876CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003877 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003878 Mutex::Autolock al(mLatestRequestMutex);
3879
3880 ALOGV("RequestThread::%s", __FUNCTION__);
3881
3882 return mLatestRequest;
3883}
3884
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003885bool Camera3Device::RequestThread::isStreamPending(
3886 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003887 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003888 Mutex::Autolock l(mRequestLock);
3889
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003890 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003891 if (!nextRequest.submitted) {
3892 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3893 if (stream == s) return true;
3894 }
3895 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003896 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003897 }
3898
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003899 for (const auto& request : mRequestQueue) {
3900 for (const auto& s : request->mOutputStreams) {
3901 if (stream == s) return true;
3902 }
3903 if (stream == request->mInputStream) return true;
3904 }
3905
3906 for (const auto& request : mRepeatingRequests) {
3907 for (const auto& s : request->mOutputStreams) {
3908 if (stream == s) return true;
3909 }
3910 if (stream == request->mInputStream) return true;
3911 }
3912
3913 return false;
3914}
Jianing Weicb0652e2014-03-12 18:29:36 -07003915
Emilian Peev40ead602017-09-26 15:46:36 +01003916bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3917 ATRACE_CALL();
3918 Mutex::Autolock l(mRequestLock);
3919
3920 for (const auto& nextRequest : mNextRequests) {
3921 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3922 if (s.first == streamId) {
3923 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3924 if (it != s.second.end()) {
3925 return true;
3926 }
3927 }
3928 }
3929 }
3930
3931 for (const auto& request : mRequestQueue) {
3932 for (const auto& s : request->mOutputSurfaces) {
3933 if (s.first == streamId) {
3934 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3935 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003936 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003937 }
3938 }
3939 }
3940 }
3941
3942 for (const auto& request : mRepeatingRequests) {
3943 for (const auto& s : request->mOutputSurfaces) {
3944 if (s.first == streamId) {
3945 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3946 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003947 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003948 }
3949 }
3950 }
3951 }
3952
3953 return false;
3954}
3955
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003956void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3957 if (!mUseHalBufManager) {
3958 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3959 return;
3960 }
3961
3962 Mutex::Autolock pl(mPauseLock);
3963 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003964 mInterface->signalPipelineDrain(streamIds);
3965 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003966 }
3967 // If request thread is still busy, wait until paused then notify HAL
3968 mNotifyPipelineDrain = true;
3969 mStreamIdsToBeDrained = streamIds;
3970}
3971
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003972void Camera3Device::RequestThread::resetPipelineDrain() {
3973 Mutex::Autolock pl(mPauseLock);
3974 mNotifyPipelineDrain = false;
3975 mStreamIdsToBeDrained.clear();
3976}
3977
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003978void Camera3Device::RequestThread::clearPreviousRequest() {
3979 Mutex::Autolock l(mRequestLock);
3980 mPrevRequest.clear();
3981}
3982
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003983status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3984 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3985 ATRACE_CALL();
3986 Mutex::Autolock l(mTriggerMutex);
3987 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3988 return BAD_VALUE;
3989 }
3990 mRotateAndCropOverride = rotateAndCropValue;
3991 return OK;
3992}
3993
Emilian Peeve23f1d92021-09-20 14:56:01 -07003994status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3995 ATRACE_CALL();
3996 Mutex::Autolock l(mTriggerMutex);
3997 mComposerOutput = composerSurfacePresent;
3998 return OK;
3999}
4000
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004001status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004002 ATRACE_CALL();
4003 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004004 if (muteMode != mCameraMute) {
4005 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004006 mCameraMuteChanged = true;
4007 }
4008 return OK;
4009}
4010
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004011nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004012 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004013 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004014 return mExpectedInflightDuration > kMinInflightDuration ?
4015 mExpectedInflightDuration : kMinInflightDuration;
4016}
4017
Emilian Peevaebbe412018-01-15 13:53:24 +00004018void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004019 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004020 if ((request == nullptr) || (halRequest == nullptr)) {
4021 ALOGE("%s: Invalid request!", __FUNCTION__);
4022 return;
4023 }
4024
4025 if (halRequest->num_physcam_settings > 0) {
4026 if (halRequest->physcam_id != nullptr) {
4027 delete [] halRequest->physcam_id;
4028 halRequest->physcam_id = nullptr;
4029 }
4030 if (halRequest->physcam_settings != nullptr) {
4031 auto it = ++(request->mSettingsList.begin());
4032 size_t i = 0;
4033 for (; it != request->mSettingsList.end(); it++, i++) {
4034 it->metadata.unlock(halRequest->physcam_settings[i]);
4035 }
4036 delete [] halRequest->physcam_settings;
4037 halRequest->physcam_settings = nullptr;
4038 }
4039 }
4040}
4041
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004042void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4043 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004044 return;
4045 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004046
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004047 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004048 // Skip the ones that have been submitted successfully.
4049 if (nextRequest.submitted) {
4050 continue;
4051 }
4052
4053 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004054 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4055 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004056
4057 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004058 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004059 }
4060
Emilian Peevaebbe412018-01-15 13:53:24 +00004061 cleanupPhysicalSettings(captureRequest, halRequest);
4062
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004063 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004064 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004065 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4066 }
4067
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004068 // No output buffer can be returned when using HAL buffer manager
4069 if (!mUseHalBufManager) {
4070 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4071 //Buffers that failed processing could still have
4072 //valid acquire fence.
4073 int acquireFence = (*outputBuffers)[i].acquire_fence;
4074 if (0 <= acquireFence) {
4075 close(acquireFence);
4076 outputBuffers->editItemAt(i).acquire_fence = -1;
4077 }
Emilian Peevf4816702020-04-03 15:44:51 -07004078 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004079 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4080 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004081 /*timestampIncreasing*/true, std::vector<size_t> (),
4082 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004083 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004084 }
4085
4086 if (sendRequestError) {
4087 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004088 sp<NotificationListener> listener = mListener.promote();
4089 if (listener != NULL) {
4090 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004091 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004092 captureRequest->mResultExtras);
4093 }
4094 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004095
4096 // Remove yet-to-be submitted inflight request from inflightMap
4097 {
4098 sp<Camera3Device> parent = mParent.promote();
4099 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004100 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004101 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4102 if (idx >= 0) {
4103 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4104 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4105 parent->removeInFlightMapEntryLocked(idx);
4106 }
4107 }
4108 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004109 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004110
4111 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004112 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004113}
4114
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004115void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004116 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004117 // Optimized a bit for the simple steady-state case (single repeating
4118 // request), to avoid putting that request in the queue temporarily.
4119 Mutex::Autolock l(mRequestLock);
4120
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004121 assert(mNextRequests.empty());
4122
4123 NextRequest nextRequest;
4124 nextRequest.captureRequest = waitForNextRequestLocked();
4125 if (nextRequest.captureRequest == nullptr) {
4126 return;
4127 }
4128
Emilian Peevf4816702020-04-03 15:44:51 -07004129 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004130 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004131 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132
4133 // Wait for additional requests
4134 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4135
4136 for (size_t i = 1; i < batchSize; i++) {
4137 NextRequest additionalRequest;
4138 additionalRequest.captureRequest = waitForNextRequestLocked();
4139 if (additionalRequest.captureRequest == nullptr) {
4140 break;
4141 }
4142
Emilian Peevf4816702020-04-03 15:44:51 -07004143 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004144 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004145 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004146 }
4147
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004148 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004149 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004150 mNextRequests.size(), batchSize);
4151 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004152 }
4153
4154 return;
4155}
4156
4157sp<Camera3Device::CaptureRequest>
4158 Camera3Device::RequestThread::waitForNextRequestLocked() {
4159 status_t res;
4160 sp<CaptureRequest> nextRequest;
4161
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004162 while (mRequestQueue.empty()) {
4163 if (!mRepeatingRequests.empty()) {
4164 // Always atomically enqueue all requests in a repeating request
4165 // list. Guarantees a complete in-sequence set of captures to
4166 // application.
4167 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004168 if (mFirstRepeating) {
4169 mFirstRepeating = false;
4170 } else {
4171 for (auto& request : requests) {
4172 // For repeating requests, override timestamp request using
4173 // the time a request is inserted into the request queue,
4174 // because the original repeating request will have an old
4175 // fixed timestamp.
4176 request->mRequestTimeNs = systemTime();
4177 }
4178 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004179 RequestList::const_iterator firstRequest =
4180 requests.begin();
4181 nextRequest = *firstRequest;
4182 mRequestQueue.insert(mRequestQueue.end(),
4183 ++firstRequest,
4184 requests.end());
4185 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004186
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004187 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004188
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004189 break;
4190 }
4191
4192 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4193
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004194 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4195 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004196 Mutex::Autolock pl(mPauseLock);
4197 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004198 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004199 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004200 if (mNotifyPipelineDrain) {
4201 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4202 mNotifyPipelineDrain = false;
4203 mStreamIdsToBeDrained.clear();
4204 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004205 // Let the tracker know
4206 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4207 if (statusTracker != 0) {
4208 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4209 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004210 sp<Camera3Device> parent = mParent.promote();
4211 if (parent != nullptr) {
4212 parent->mRequestBufferSM.onRequestThreadPaused();
4213 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 }
4215 // Stop waiting for now and let thread management happen
4216 return NULL;
4217 }
4218 }
4219
4220 if (nextRequest == NULL) {
4221 // Don't have a repeating request already in hand, so queue
4222 // must have an entry now.
4223 RequestList::iterator firstRequest =
4224 mRequestQueue.begin();
4225 nextRequest = *firstRequest;
4226 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004227 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4228 sp<NotificationListener> listener = mListener.promote();
4229 if (listener != NULL) {
4230 listener->notifyRequestQueueEmpty();
4231 }
4232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004233 }
4234
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004235 // In case we've been unpaused by setPaused clearing mDoPause, need to
4236 // update internal pause state (capture/setRepeatingRequest unpause
4237 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004238 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004239 if (mPaused) {
4240 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4241 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4242 if (statusTracker != 0) {
4243 statusTracker->markComponentActive(mStatusId);
4244 }
4245 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004246 mPaused = false;
4247
4248 // Check if we've reconfigured since last time, and reset the preview
4249 // request if so. Can't use 'NULL request == repeat' across configure calls.
4250 if (mReconfigured) {
4251 mPrevRequest.clear();
4252 mReconfigured = false;
4253 }
4254
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004255 if (nextRequest != NULL) {
4256 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004257 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4258 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004259
4260 // Since RequestThread::clear() removes buffers from the input stream,
4261 // get the right buffer here before unlocking mRequestLock
4262 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004263 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4264 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004265 if (res != OK) {
4266 // Can't get input buffer from gralloc queue - this could be due to
4267 // disconnected queue or other producer misbehavior, so not a fatal
4268 // error
4269 ALOGE("%s: Can't get input buffer, skipping request:"
4270 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004271
4272 sp<NotificationListener> listener = mListener.promote();
4273 if (listener != NULL) {
4274 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004275 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004276 nextRequest->mResultExtras);
4277 }
4278 return NULL;
4279 }
4280 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004281 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004282
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004283 return nextRequest;
4284}
4285
4286bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004287 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004288 status_t res;
4289 Mutex::Autolock l(mPauseLock);
4290 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004291 if (mPaused == false) {
4292 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004293 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004294 if (mNotifyPipelineDrain) {
4295 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4296 mNotifyPipelineDrain = false;
4297 mStreamIdsToBeDrained.clear();
4298 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004299 // Let the tracker know
4300 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4301 if (statusTracker != 0) {
4302 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4303 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004304 sp<Camera3Device> parent = mParent.promote();
4305 if (parent != nullptr) {
4306 parent->mRequestBufferSM.onRequestThreadPaused();
4307 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004309
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004311 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 return true;
4313 }
4314 }
4315 // We don't set mPaused to false here, because waitForNextRequest needs
4316 // to further manage the paused state in case of starvation.
4317 return false;
4318}
4319
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004320void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004321 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004322 // With work to do, mark thread as unpaused.
4323 // If paused by request (setPaused), don't resume, to avoid
4324 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004325 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004326 Mutex::Autolock p(mPauseLock);
4327 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4329 if (mPaused) {
4330 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4331 if (statusTracker != 0) {
4332 statusTracker->markComponentActive(mStatusId);
4333 }
4334 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004335 mPaused = false;
4336 }
4337}
4338
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004339void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4340 sp<Camera3Device> parent = mParent.promote();
4341 if (parent != NULL) {
4342 va_list args;
4343 va_start(args, fmt);
4344
4345 parent->setErrorStateV(fmt, args);
4346
4347 va_end(args);
4348 }
4349}
4350
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004351status_t Camera3Device::RequestThread::insertTriggers(
4352 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004353 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004354 Mutex::Autolock al(mTriggerMutex);
4355
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004356 sp<Camera3Device> parent = mParent.promote();
4357 if (parent == NULL) {
4358 CLOGE("RequestThread: Parent is gone");
4359 return DEAD_OBJECT;
4360 }
4361
Emilian Peevaebbe412018-01-15 13:53:24 +00004362 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004363 size_t count = mTriggerMap.size();
4364
4365 for (size_t i = 0; i < count; ++i) {
4366 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004367 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004368
4369 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4370 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4371 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004372 if (isAeTrigger) {
4373 request->mResultExtras.precaptureTriggerId = triggerId;
4374 mCurrentPreCaptureTriggerId = triggerId;
4375 } else {
4376 request->mResultExtras.afTriggerId = triggerId;
4377 mCurrentAfTriggerId = triggerId;
4378 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004379 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004380 }
4381
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004382 camera_metadata_entry entry = metadata.find(tag);
4383
4384 if (entry.count > 0) {
4385 /**
4386 * Already has an entry for this trigger in the request.
4387 * Rewrite it with our requested trigger value.
4388 */
4389 RequestTrigger oldTrigger = trigger;
4390
4391 oldTrigger.entryValue = entry.data.u8[0];
4392
4393 mTriggerReplacedMap.add(tag, oldTrigger);
4394 } else {
4395 /**
4396 * More typical, no trigger entry, so we just add it
4397 */
4398 mTriggerRemovedMap.add(tag, trigger);
4399 }
4400
4401 status_t res;
4402
4403 switch (trigger.getTagType()) {
4404 case TYPE_BYTE: {
4405 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4406 res = metadata.update(tag,
4407 &entryValue,
4408 /*count*/1);
4409 break;
4410 }
4411 case TYPE_INT32:
4412 res = metadata.update(tag,
4413 &trigger.entryValue,
4414 /*count*/1);
4415 break;
4416 default:
4417 ALOGE("%s: Type not supported: 0x%x",
4418 __FUNCTION__,
4419 trigger.getTagType());
4420 return INVALID_OPERATION;
4421 }
4422
4423 if (res != OK) {
4424 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4425 ", value %d", __FUNCTION__, trigger.getTagName(),
4426 trigger.entryValue);
4427 return res;
4428 }
4429
4430 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4431 trigger.getTagName(),
4432 trigger.entryValue);
4433 }
4434
4435 mTriggerMap.clear();
4436
4437 return count;
4438}
4439
4440status_t Camera3Device::RequestThread::removeTriggers(
4441 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004442 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004443 Mutex::Autolock al(mTriggerMutex);
4444
Emilian Peevaebbe412018-01-15 13:53:24 +00004445 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004446
4447 /**
4448 * Replace all old entries with their old values.
4449 */
4450 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4451 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4452
4453 status_t res;
4454
4455 uint32_t tag = trigger.metadataTag;
4456 switch (trigger.getTagType()) {
4457 case TYPE_BYTE: {
4458 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4459 res = metadata.update(tag,
4460 &entryValue,
4461 /*count*/1);
4462 break;
4463 }
4464 case TYPE_INT32:
4465 res = metadata.update(tag,
4466 &trigger.entryValue,
4467 /*count*/1);
4468 break;
4469 default:
4470 ALOGE("%s: Type not supported: 0x%x",
4471 __FUNCTION__,
4472 trigger.getTagType());
4473 return INVALID_OPERATION;
4474 }
4475
4476 if (res != OK) {
4477 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4478 ", trigger value %d", __FUNCTION__,
4479 trigger.getTagName(), trigger.entryValue);
4480 return res;
4481 }
4482 }
4483 mTriggerReplacedMap.clear();
4484
4485 /**
4486 * Remove all new entries.
4487 */
4488 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4489 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4490 status_t res = metadata.erase(trigger.metadataTag);
4491
4492 if (res != OK) {
4493 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4494 ", trigger value %d", __FUNCTION__,
4495 trigger.getTagName(), trigger.entryValue);
4496 return res;
4497 }
4498 }
4499 mTriggerRemovedMap.clear();
4500
4501 return OK;
4502}
4503
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004504status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004505 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004506 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004507 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004508 status_t res;
4509
Emilian Peevaebbe412018-01-15 13:53:24 +00004510 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004511
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004512 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004513 // exists
4514 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4515 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4516 if (afTrigger.count > 0 &&
4517 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4518 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004519 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004520 if (res != OK) return res;
4521 }
4522
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004523 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004524 // if none already exists
4525 camera_metadata_entry pcTrigger =
4526 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4527 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4528 if (pcTrigger.count > 0 &&
4529 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4530 pcId.count == 0) {
4531 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004532 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004533 if (res != OK) return res;
4534 }
4535
4536 return OK;
4537}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004538
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004539bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4540 const sp<CaptureRequest> &request) {
4541 ATRACE_CALL();
4542
4543 if (request->mRotateAndCropAuto) {
4544 Mutex::Autolock l(mTriggerMutex);
4545 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4546
4547 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4548 if (rotateAndCropEntry.count > 0) {
4549 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4550 return false;
4551 } else {
4552 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4553 return true;
4554 }
4555 } else {
4556 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4557 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4558 &rotateAndCrop_u8, 1);
4559 return true;
4560 }
4561 }
4562 return false;
4563}
4564
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004565bool Camera3Device::RequestThread::overrideTestPattern(
4566 const sp<CaptureRequest> &request) {
4567 ATRACE_CALL();
4568
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004569 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004570
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004571 Mutex::Autolock l(mTriggerMutex);
4572
4573 bool changed = false;
4574
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004575 // For a multi-camera, the physical cameras support the same set of
4576 // test pattern modes as the logical camera.
4577 for (auto& settings : request->mSettingsList) {
4578 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004579
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004580 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4581 int32_t testPatternData[4] = {
4582 settings.mOriginalTestPatternData[0],
4583 settings.mOriginalTestPatternData[1],
4584 settings.mOriginalTestPatternData[2],
4585 settings.mOriginalTestPatternData[3]
4586 };
4587 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4588 testPatternMode = mCameraMute;
4589 testPatternData[0] = 0;
4590 testPatternData[1] = 0;
4591 testPatternData[2] = 0;
4592 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004593 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004594
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004595 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4596 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4597 if (testPatternEntry.count > 0) {
4598 if (testPatternEntry.data.i32[0] != testPatternMode) {
4599 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004600 changed = true;
4601 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004602 } else if (supportTestPatternModeKey) {
4603 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4604 &testPatternMode, 1);
4605 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004606 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004607
4608 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4609 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4610 if (testPatternColor.count >= 4) {
4611 for (size_t i = 0; i < 4; i++) {
4612 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4613 testPatternColor.data.i32[i] = testPatternData[i];
4614 changed = true;
4615 }
4616 }
4617 } else if (supportTestPatternDataKey) {
4618 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4619 testPatternData, 4);
4620 changed = true;
4621 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004622 }
4623
4624 return changed;
4625}
4626
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004627status_t Camera3Device::RequestThread::setHalInterface(
4628 sp<HalInterface> newHalInterface) {
4629 if (newHalInterface.get() == nullptr) {
4630 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4631 return DEAD_OBJECT;
4632 }
4633
4634 mInterface = newHalInterface;
4635
4636 return OK;
4637}
4638
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004639/**
4640 * PreparerThread inner class methods
4641 */
4642
4643Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004644 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004645 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004646}
4647
4648Camera3Device::PreparerThread::~PreparerThread() {
4649 Thread::requestExitAndWait();
4650 if (mCurrentStream != nullptr) {
4651 mCurrentStream->cancelPrepare();
4652 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4653 mCurrentStream.clear();
4654 }
4655 clear();
4656}
4657
Ruben Brunkc78ac262015-08-13 17:58:46 -07004658status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004659 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004660 status_t res;
4661
4662 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004663 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004664
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004665 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004666 if (res == OK) {
4667 // No preparation needed, fire listener right off
4668 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004669 if (listener != NULL) {
4670 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004671 }
4672 return OK;
4673 } else if (res != NOT_ENOUGH_DATA) {
4674 return res;
4675 }
4676
4677 // Need to prepare, start up thread if necessary
4678 if (!mActive) {
4679 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4680 // isn't running
4681 Thread::requestExitAndWait();
4682 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4683 if (res != OK) {
4684 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004685 if (listener != NULL) {
4686 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004687 }
4688 return res;
4689 }
4690 mCancelNow = false;
4691 mActive = true;
4692 ALOGV("%s: Preparer stream started", __FUNCTION__);
4693 }
4694
4695 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004696 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004697 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4698
4699 return OK;
4700}
4701
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004702void Camera3Device::PreparerThread::pause() {
4703 ATRACE_CALL();
4704
4705 Mutex::Autolock l(mLock);
4706
4707 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4708 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4709 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4710 int currentMaxCount = mCurrentMaxCount;
4711 mPendingStreams.clear();
4712 mCancelNow = true;
4713 while (mActive) {
4714 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4715 if (res == TIMED_OUT) {
4716 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4717 return;
4718 } else if (res != OK) {
4719 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4720 return;
4721 }
4722 }
4723
4724 //Check whether the prepare thread was able to complete the current
4725 //stream. In case work is still pending emplace it along with the rest
4726 //of the streams in the pending list.
4727 if (currentStream != nullptr) {
4728 if (!mCurrentPrepareComplete) {
4729 pendingStreams.emplace(currentMaxCount, currentStream);
4730 }
4731 }
4732
4733 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4734 for (const auto& it : mPendingStreams) {
4735 it.second->cancelPrepare();
4736 }
4737}
4738
4739status_t Camera3Device::PreparerThread::resume() {
4740 ATRACE_CALL();
4741 status_t res;
4742
4743 Mutex::Autolock l(mLock);
4744 sp<NotificationListener> listener = mListener.promote();
4745
4746 if (mActive) {
4747 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4748 return NO_INIT;
4749 }
4750
4751 auto it = mPendingStreams.begin();
4752 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004753 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004754 if (res == OK) {
4755 if (listener != NULL) {
4756 listener->notifyPrepared(it->second->getId());
4757 }
4758 it = mPendingStreams.erase(it);
4759 } else if (res != NOT_ENOUGH_DATA) {
4760 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4761 res, strerror(-res));
4762 it = mPendingStreams.erase(it);
4763 } else {
4764 it++;
4765 }
4766 }
4767
4768 if (mPendingStreams.empty()) {
4769 return OK;
4770 }
4771
4772 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4773 if (res != OK) {
4774 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4775 __FUNCTION__, res, strerror(-res));
4776 return res;
4777 }
4778 mCancelNow = false;
4779 mActive = true;
4780 ALOGV("%s: Preparer stream started", __FUNCTION__);
4781
4782 return OK;
4783}
4784
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004785status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004786 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004787 Mutex::Autolock l(mLock);
4788
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004789 for (const auto& it : mPendingStreams) {
4790 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004791 }
4792 mPendingStreams.clear();
4793 mCancelNow = true;
4794
4795 return OK;
4796}
4797
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004798void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004799 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004800 Mutex::Autolock l(mLock);
4801 mListener = listener;
4802}
4803
4804bool Camera3Device::PreparerThread::threadLoop() {
4805 status_t res;
4806 {
4807 Mutex::Autolock l(mLock);
4808 if (mCurrentStream == nullptr) {
4809 // End thread if done with work
4810 if (mPendingStreams.empty()) {
4811 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4812 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4813 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4814 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004815 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004816 return false;
4817 }
4818
4819 // Get next stream to prepare
4820 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004821 mCurrentStream = it->second;
4822 mCurrentMaxCount = it->first;
4823 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004824 mPendingStreams.erase(it);
4825 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4826 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4827 } else if (mCancelNow) {
4828 mCurrentStream->cancelPrepare();
4829 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4830 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4831 mCurrentStream.clear();
4832 mCancelNow = false;
4833 return true;
4834 }
4835 }
4836
4837 res = mCurrentStream->prepareNextBuffer();
4838 if (res == NOT_ENOUGH_DATA) return true;
4839 if (res != OK) {
4840 // Something bad happened; try to recover by cancelling prepare and
4841 // signalling listener anyway
4842 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4843 mCurrentStream->getId(), res, strerror(-res));
4844 mCurrentStream->cancelPrepare();
4845 }
4846
4847 // This stream has finished, notify listener
4848 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004849 sp<NotificationListener> listener = mListener.promote();
4850 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004851 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4852 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004853 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004854 }
4855
4856 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4857 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004858 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004859
4860 return true;
4861}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004862
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004863status_t Camera3Device::RequestBufferStateMachine::initialize(
4864 sp<camera3::StatusTracker> statusTracker) {
4865 if (statusTracker == nullptr) {
4866 ALOGE("%s: statusTracker is null", __FUNCTION__);
4867 return BAD_VALUE;
4868 }
4869
4870 std::lock_guard<std::mutex> lock(mLock);
4871 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004872 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004873 return OK;
4874}
4875
4876bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4877 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004878 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004879 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004880 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004881 return true;
4882 }
4883 return false;
4884}
4885
4886void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4887 std::lock_guard<std::mutex> lock(mLock);
4888 if (!mRequestBufferOngoing) {
4889 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4890 return;
4891 }
4892 mRequestBufferOngoing = false;
4893 if (mStatus == RB_STATUS_PENDING_STOP) {
4894 checkSwitchToStopLocked();
4895 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004896 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004897}
4898
4899void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4900 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004901 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004902 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004903 return;
4904}
4905
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004906void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004907 std::lock_guard<std::mutex> lock(mLock);
4908 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004909 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4910 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004911 mInflightMapEmpty = false;
4912 if (mStatus == RB_STATUS_STOPPED) {
4913 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004914 }
4915 return;
4916}
4917
4918void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4919 std::lock_guard<std::mutex> lock(mLock);
4920 mRequestThreadPaused = true;
4921 if (mStatus == RB_STATUS_PENDING_STOP) {
4922 checkSwitchToStopLocked();
4923 }
4924 return;
4925}
4926
4927void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4928 std::lock_guard<std::mutex> lock(mLock);
4929 mInflightMapEmpty = true;
4930 if (mStatus == RB_STATUS_PENDING_STOP) {
4931 checkSwitchToStopLocked();
4932 }
4933 return;
4934}
4935
4936void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4937 std::lock_guard<std::mutex> lock(mLock);
4938 if (!checkSwitchToStopLocked()) {
4939 mStatus = RB_STATUS_PENDING_STOP;
4940 }
4941 return;
4942}
4943
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004944bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4945 std::lock_guard<std::mutex> lock(mLock);
4946 if (mRequestBufferOngoing) {
4947 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4948 __FUNCTION__);
4949 return false;
4950 }
4951 mSwitchedToOffline = true;
4952 mInflightMapEmpty = true;
4953 mRequestThreadPaused = true;
4954 mStatus = RB_STATUS_STOPPED;
4955 return true;
4956}
4957
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004958void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4959 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4960 if (statusTracker != nullptr) {
4961 if (active) {
4962 statusTracker->markComponentActive(mRequestBufferStatusId);
4963 } else {
4964 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4965 }
4966 }
4967}
4968
4969bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4970 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4971 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004972 return true;
4973 }
4974 return false;
4975}
4976
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004977bool Camera3Device::startRequestBuffer() {
4978 return mRequestBufferSM.startRequestBuffer();
4979}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004980
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004981void Camera3Device::endRequestBuffer() {
4982 mRequestBufferSM.endRequestBuffer();
4983}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004984
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004985nsecs_t Camera3Device::getWaitDuration() {
4986 return kBaseGetBufferWait + getExpectedInFlightDuration();
4987}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004988
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004989void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4990 mInterface->getInflightBufferKeys(out);
4991}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004992
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004993void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4994 mInterface->getInflightRequestBufferKeys(out);
4995}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004996
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004997std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
4998 std::vector<sp<Camera3StreamInterface>> ret;
4999 bool hasInputStream = mInputStream != nullptr;
5000 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5001 if (hasInputStream) {
5002 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005003 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005004 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5005 ret.push_back(mOutputStreams[i]);
5006 }
5007 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5008 ret.push_back(mDeletedStreams[i]);
5009 }
5010 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005011}
5012
Emilian Peevcc0b7952020-01-07 13:54:47 -08005013void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5014 ATRACE_CALL();
5015
5016 if (offlineStreamIds == nullptr) {
5017 return;
5018 }
5019
5020 Mutex::Autolock il(mInterfaceLock);
5021
5022 auto streamIds = mOutputStreams.getStreamIds();
5023 bool hasInputStream = mInputStream != nullptr;
5024 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5025 offlineStreamIds->push_back(mInputStream->getId());
5026 }
5027
5028 for (const auto & streamId : streamIds) {
5029 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5030 // Streams that use the camera buffer manager are currently not supported in
5031 // offline mode
5032 if (stream->getOfflineProcessingSupport() &&
5033 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5034 offlineStreamIds->push_back(streamId);
5035 }
5036 }
5037}
5038
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005039status_t Camera3Device::setRotateAndCropAutoBehavior(
5040 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5041 ATRACE_CALL();
5042 Mutex::Autolock il(mInterfaceLock);
5043 Mutex::Autolock l(mLock);
5044 if (mRequestThread == nullptr) {
5045 return INVALID_OPERATION;
5046 }
5047 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5048}
5049
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005050bool Camera3Device::supportsCameraMute() {
5051 Mutex::Autolock il(mInterfaceLock);
5052 Mutex::Autolock l(mLock);
5053
5054 return mSupportCameraMute;
5055}
5056
5057status_t Camera3Device::setCameraMute(bool enabled) {
5058 ATRACE_CALL();
5059 Mutex::Autolock il(mInterfaceLock);
5060 Mutex::Autolock l(mLock);
5061
5062 if (mRequestThread == nullptr || !mSupportCameraMute) {
5063 return INVALID_OPERATION;
5064 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005065 int32_t muteMode =
5066 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5067 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5068 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5069 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005070}
5071
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005072status_t Camera3Device::injectCamera(const String8& injectedCamId,
5073 sp<CameraProviderManager> manager) {
5074 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5075 ATRACE_CALL();
5076 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005077 // When the camera device is active, injectCamera() and stopInjection() will call
5078 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5079 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5080 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5081 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5082 // waitUntilStateThenRelock().
5083 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005084
5085 status_t res = NO_ERROR;
5086 if (mInjectionMethods->isInjecting()) {
5087 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5088 return OK;
5089 } else {
5090 res = mInjectionMethods->stopInjection();
5091 if (res != OK) {
5092 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5093 __FUNCTION__, res);
5094 return res;
5095 }
5096 }
5097 }
5098
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005099 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005100 if (res != OK) {
5101 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5102 __FUNCTION__, res);
5103 return res;
5104 }
5105
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005106 // When the second display of android is cast to the remote device, and the opened camera is
5107 // also cast to the second display, in this case, because the camera has configured the streams
5108 // at this time, we can directly call injectCamera() to replace the internal camera with
5109 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005110 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5111 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5112
5113 camera3::camera_stream_configuration injectionConfig;
5114 std::vector<uint32_t> injectionBufferSizes;
5115 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5116 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5117 || injectionBufferSizes.size() <= 0) {
5118 ALOGE("Failed to inject camera due to abandoned configuration! "
5119 "mOperatingMode: %d injectionConfig.num_streams: %d "
5120 "injectionBufferSizes.size(): %zu", mOperatingMode,
5121 injectionConfig.num_streams, injectionBufferSizes.size());
5122 return DEAD_OBJECT;
5123 }
5124
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005125 res = mInjectionMethods->injectCamera(
5126 injectionConfig, injectionBufferSizes);
5127 if (res != OK) {
5128 ALOGE("Can't finish inject camera process!");
5129 return res;
5130 }
5131 }
5132
5133 return OK;
5134}
5135
5136status_t Camera3Device::stopInjection() {
5137 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5138 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005139 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005140 return mInjectionMethods->stopInjection();
5141}
5142
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005143}; // namespace android