blob: 07055ec190a7cb97249ae9ed5ada9bb872a85376 [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
Ravneetaeb20dc2022-03-30 05:33:03 +0000231 /** Start watchdog thread */
232 mCameraServiceWatchdog = new CameraServiceWatchdog();
233 mCameraServiceWatchdog->run("CameraServiceWatchdog");
234
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800235 return OK;
236}
237
238status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700239 return disconnectImpl();
240}
241
242status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800243 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700244 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800245
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700246 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700247 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700248 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800249 Mutex::Autolock il(mInterfaceLock);
250 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
251 {
252 Mutex::Autolock l(mLock);
253 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 if (mStatus == STATUS_ACTIVE ||
256 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
257 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700258 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800259 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800261 } else {
262 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
263 if (res != OK) {
264 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
265 maxExpectedDuration);
266 // Continue to close device even in case of error
267 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700269 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatus == STATUS_ERROR) {
272 CLOGE("Shutting down in an error state");
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mStatusTracker != NULL) {
276 mStatusTracker->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 if (mRequestThread != NULL) {
280 mRequestThread->requestExit();
281 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800283 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
284 for (size_t i = 0; i < mOutputStreams.size(); i++) {
285 streams.push_back(mOutputStreams[i]);
286 }
287 if (mInputStream != nullptr) {
288 streams.push_back(mInputStream);
289 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700291 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800292 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
293 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
295 // HAL may be in a bad state, so waiting for request thread
296 // (which may be stuck in the HAL processCaptureRequest call)
297 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800298 // give up mInterfaceLock here and then lock it again. Could this lead
299 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 mRequestThread->join();
301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800303 Mutex::Autolock il(mInterfaceLock);
304 if (mStatusTracker != NULL) {
305 mStatusTracker->join();
306 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800307
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800308 if (mInjectionMethods->isInjecting()) {
309 mInjectionMethods->stopInjection();
310 }
311
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800312 HalInterface* interface;
313 {
314 Mutex::Autolock l(mLock);
315 mRequestThread.clear();
316 Mutex::Autolock stLock(mTrackerLock);
317 mStatusTracker.clear();
318 interface = mInterface.get();
319 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 // Call close without internal mutex held, as the HAL close may need to
322 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000323 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700324
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800325 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800327 {
328 Mutex::Autolock l(mLock);
329 mInterface->clear();
330 mOutputStreams.clear();
331 mInputStream.clear();
332 mDeletedStreams.clear();
333 mBufferManager.clear();
334 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
335 }
336
337 for (auto& weakStream : streams) {
338 sp<Camera3StreamInterface> stream = weakStream.promote();
339 if (stream != nullptr) {
340 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
341 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
342 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700343 }
344 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700345 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000346
347 if (mCameraServiceWatchdog != NULL) {
348 mCameraServiceWatchdog->requestExit();
349 mCameraServiceWatchdog.clear();
350 }
351
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700352 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800353}
354
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700355// For dumping/debugging only -
356// try to acquire a lock a few times, eventually give up to proceed with
357// debug/dump operations
358bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
359 bool gotLock = false;
360 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
361 if (lock.tryLock() == NO_ERROR) {
362 gotLock = true;
363 break;
364 } else {
365 usleep(kDumpSleepDuration);
366 }
367 }
368 return gotLock;
369}
370
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800371nsecs_t Camera3Device::getMonoToBoottimeOffset() {
372 // try three times to get the clock offset, choose the one
373 // with the minimum gap in measurements.
374 const int tries = 3;
375 nsecs_t bestGap, measured;
376 for (int i = 0; i < tries; ++i) {
377 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
378 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
379 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
380 const nsecs_t gap = tmono2 - tmono;
381 if (i == 0 || gap < bestGap) {
382 bestGap = gap;
383 measured = tbase - ((tmono + tmono2) >> 1);
384 }
385 }
386 return measured;
387}
388
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800389ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
390 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700391 // Get max jpeg size (area-wise) for default sensor pixel mode
392 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800393 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700394 /*isUltraHighResolutionSensor*/false);
395 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
396 // not ultra high res sensor
397 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800398 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700399 /*isUltraHighResolution*/true);
400 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800401 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
402 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700403 return BAD_VALUE;
404 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700405 bool useMaxSensorPixelModeThreshold = false;
406 if (uhrMaxJpegResolution.width != 0 &&
407 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
408 // Use the ultra high res max jpeg size and max jpeg buffer size
409 useMaxSensorPixelModeThreshold = true;
410 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700411
Zhijun Hef7da0962014-04-24 13:27:56 -0700412 // Get max jpeg buffer size
413 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800414 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700415 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
417 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700418 return BAD_VALUE;
419 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700421
422 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
423 if (useMaxSensorPixelModeThreshold) {
424 maxJpegBufferSize =
425 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
426 maxDefaultJpegResolution, maxJpegBufferSize);
427 chosenMaxJpegResolution = uhrMaxJpegResolution;
428 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800429 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700430
431 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700433 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800434 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
435 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700436 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800437 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
438 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700439 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700440 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700441 return jpegBufferSize;
442}
443
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800444ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700445 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800446 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700447 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800448 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
449 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700450 return BAD_VALUE;
451 }
452 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
453 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
454 return maxBytesForPointCloud;
455}
456
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800457ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
458 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 const int PER_CONFIGURATION_SIZE = 3;
460 const int WIDTH_OFFSET = 0;
461 const int HEIGHT_OFFSET = 1;
462 const int SIZE_OFFSET = 2;
463 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800464 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800465 camera3::SessionConfigurationUtils::getAppropriateModeTag(
466 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
467 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800468 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800469 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800470 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
471 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800472 return BAD_VALUE;
473 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700474
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800475 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
476 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
477 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
478 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
479 }
480 }
481
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800482 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
483 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800484 return BAD_VALUE;
485}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700486
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800487status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
488 ATRACE_CALL();
489 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700490
491 // Try to lock, but continue in case of failure (to avoid blocking in
492 // deadlocks)
493 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
494 bool gotLock = tryLockSpinRightRound(mLock);
495
496 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800497 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
498 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700499 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
501 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700502
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800503 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700504
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800505 String16 templatesOption("-t");
506 int n = args.size();
507 for (int i = 0; i < n; i++) {
508 if (args[i] == templatesOption) {
509 dumpTemplates = true;
510 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000511 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700512 if (i + 1 < n) {
513 String8 monitorTags = String8(args[i + 1]);
514 if (monitorTags == "off") {
515 mTagMonitor.disableMonitoring();
516 } else {
517 mTagMonitor.parseTagsToMonitor(monitorTags);
518 }
519 } else {
520 mTagMonitor.disableMonitoring();
521 }
522 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800523 }
524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800526
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800527 const char *status =
528 mStatus == STATUS_ERROR ? "ERROR" :
529 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700530 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
531 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800532 mStatus == STATUS_ACTIVE ? "ACTIVE" :
533 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700534
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800535 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700536 if (mStatus == STATUS_ERROR) {
537 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
538 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800539 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800540 const char *mode =
541 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
542 mOperatingMode == static_cast<int>(
543 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
544 "CUSTOM";
545 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800546
547 if (mInputStream != NULL) {
548 write(fd, lines.string(), lines.size());
549 mInputStream->dump(fd, args);
550 } else {
551 lines.appendFormat(" No input stream.\n");
552 write(fd, lines.string(), lines.size());
553 }
554 for (size_t i = 0; i < mOutputStreams.size(); i++) {
555 mOutputStreams[i]->dump(fd,args);
556 }
557
Zhijun He431503c2016-03-07 17:30:16 -0800558 if (mBufferManager != NULL) {
559 lines = String8(" Camera3 Buffer Manager:\n");
560 write(fd, lines.string(), lines.size());
561 mBufferManager->dump(fd, args);
562 }
Zhijun He125684a2015-12-26 15:07:30 -0800563
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700564 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700565 if (mInFlightLock.try_lock()) {
566 if (mInFlightMap.size() == 0) {
567 lines.append(" None\n");
568 } else {
569 for (size_t i = 0; i < mInFlightMap.size(); i++) {
570 InFlightRequest r = mInFlightMap.valueAt(i);
571 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
572 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
573 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
574 r.numBuffersLeft);
575 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700576 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700577 mInFlightLock.unlock();
578 } else {
579 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700580 }
581 write(fd, lines.string(), lines.size());
582
Shuzhen Wang686f6442017-06-20 16:16:04 -0700583 if (mRequestThread != NULL) {
584 mRequestThread->dumpCaptureRequestLatency(fd,
585 " ProcessCaptureRequest latency histogram:");
586 }
587
Igor Murashkin1e479c02013-09-06 16:55:14 -0700588 {
589 lines = String8(" Last request sent:\n");
590 write(fd, lines.string(), lines.size());
591
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700592 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700593 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
594 }
595
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800596 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700597 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800598 "TEMPLATE_PREVIEW",
599 "TEMPLATE_STILL_CAPTURE",
600 "TEMPLATE_VIDEO_RECORD",
601 "TEMPLATE_VIDEO_SNAPSHOT",
602 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800603 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800604 };
605
Emilian Peevf4816702020-04-03 15:44:51 -0700606 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800607 camera_metadata_t *templateRequest = nullptr;
608 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700609 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800611 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 lines.append(" Not supported\n");
613 write(fd, lines.string(), lines.size());
614 } else {
615 write(fd, lines.string(), lines.size());
616 dump_indented_camera_metadata(templateRequest,
617 fd, /*verbosity*/2, /*indentation*/8);
618 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800620 }
621 }
622
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700623 mTagMonitor.dumpMonitoredMetadata(fd);
624
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800626 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800627 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800629 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800630
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700631 if (gotLock) mLock.unlock();
632 if (gotInterfaceLock) mInterfaceLock.unlock();
633
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800634 return OK;
635}
636
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700637status_t Camera3Device::startWatchingTags(const String8 &tags) {
638 mTagMonitor.parseTagsToMonitor(tags);
639 return OK;
640}
641
642status_t Camera3Device::stopWatchingTags() {
643 mTagMonitor.disableMonitoring();
644 return OK;
645}
646
647status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
648 mTagMonitor.getLatestMonitoredTagEvents(out);
649 return OK;
650}
651
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800652const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800653 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
655 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700656 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 mStatus == STATUS_ERROR ?
658 "when in error state" : "before init");
659 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700660 if (physicalId.isEmpty()) {
661 return mDeviceInfo;
662 } else {
663 std::string id(physicalId.c_str());
664 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
665 return mPhysicalDeviceInfoMap.at(id);
666 } else {
667 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
668 return mDeviceInfo;
669 }
670 }
671}
672
673const CameraMetadata& Camera3Device::info() const {
674 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800675 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676}
677
Jianing Wei90e59c92014-03-12 18:29:36 -0700678status_t Camera3Device::checkStatusOkToCaptureLocked() {
679 switch (mStatus) {
680 case STATUS_ERROR:
681 CLOGE("Device has encountered a serious error");
682 return INVALID_OPERATION;
683 case STATUS_UNINITIALIZED:
684 CLOGE("Device not initialized");
685 return INVALID_OPERATION;
686 case STATUS_UNCONFIGURED:
687 case STATUS_CONFIGURED:
688 case STATUS_ACTIVE:
689 // OK
690 break;
691 default:
692 SET_ERR_L("Unexpected status: %d", mStatus);
693 return INVALID_OPERATION;
694 }
695 return OK;
696}
697
698status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700701 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700702 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700703 if (requestList == NULL) {
704 CLOGE("requestList cannot be NULL.");
705 return BAD_VALUE;
706 }
707
Jianing Weicb0652e2014-03-12 18:29:36 -0700708 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000709 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700710 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
711 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
712 ++metadataIt, ++surfaceMapIt) {
713 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700714 if (newRequest == 0) {
715 CLOGE("Can't create capture request");
716 return BAD_VALUE;
717 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700718
Shuzhen Wang9d066012016-09-30 11:30:20 -0700719 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700720 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700721
Jianing Weicb0652e2014-03-12 18:29:36 -0700722 // Setup burst Id and request Id
723 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800724 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
725 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700726 CLOGE("RequestID does not exist in metadata");
727 return BAD_VALUE;
728 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800729 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700730
Jianing Wei90e59c92014-03-12 18:29:36 -0700731 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700732
733 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700734 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700735 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
736 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
737 return BAD_VALUE;
738 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700739
740 // Setup batch size if this is a high speed video recording request.
741 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
742 auto firstRequest = requestList->begin();
743 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
744 if (outputStream->isVideoStream()) {
745 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800746 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700747 break;
748 }
749 }
750 }
751
Jianing Wei90e59c92014-03-12 18:29:36 -0700752 return OK;
753}
754
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800755status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800756 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700759 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000760 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800762 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700763}
764
Emilian Peevaebbe412018-01-15 13:53:24 +0000765void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700766 std::list<const SurfaceMap>& surfaceMaps,
767 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000768 PhysicalCameraSettingsList requestList;
769 requestList.push_back({std::string(getId().string()), request});
770 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700771
772 SurfaceMap surfaceMap;
773 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
774 // With no surface list passed in, stream and surface will have 1-to-1
775 // mapping. So the surface index is 0 for each stream in the surfaceMap.
776 for (size_t i = 0; i < streams.count; i++) {
777 surfaceMap[streams.data.i32[i]].push_back(0);
778 }
779 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800780}
781
Jianing Wei90e59c92014-03-12 18:29:36 -0700782status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000783 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 const std::list<const SurfaceMap> &surfaceMaps,
785 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700786 /*out*/
787 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700788 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700789 nsecs_t requestTimeNs = systemTime();
790
Jianing Wei90e59c92014-03-12 18:29:36 -0700791 Mutex::Autolock il(mInterfaceLock);
792 Mutex::Autolock l(mLock);
793
794 status_t res = checkStatusOkToCaptureLocked();
795 if (res != OK) {
796 // error logged by previous call
797 return res;
798 }
799
800 RequestList requestList;
801
Shuzhen Wang0129d522016-10-30 22:43:41 -0700802 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700803 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700804 if (res != OK) {
805 // error logged by previous call
806 return res;
807 }
808
809 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700810 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 }
814
815 if (res == OK) {
816 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
817 if (res != OK) {
818 SET_ERR_L("Can't transition to active in %f seconds!",
819 kActiveTimeout/1e9);
820 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800821 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700822 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700823 } else {
824 CLOGE("Cannot queue request. Impossible.");
825 return BAD_VALUE;
826 }
827
828 return res;
829}
830
Emilian Peevaebbe412018-01-15 13:53:24 +0000831status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700833 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 ATRACE_CALL();
835
Emilian Peevaebbe412018-01-15 13:53:24 +0000836 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800838
Jianing Weicb0652e2014-03-12 18:29:36 -0700839status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
840 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800841 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800842
Emilian Peevaebbe412018-01-15 13:53:24 +0000843 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700844 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000845 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800849}
850
Emilian Peevaebbe412018-01-15 13:53:24 +0000851status_t Camera3Device::setStreamingRequestList(
852 const List<const PhysicalCameraSettingsList> &requestsList,
853 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700854 ATRACE_CALL();
855
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700857}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800858
859sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 status_t res;
862
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700863 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800864 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
865 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000866 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700867 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700868 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800869 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700870 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800871 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700872 } else if (mStatus == STATUS_UNCONFIGURED) {
873 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700874 CLOGE("No streams configured");
875 return NULL;
876 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800877 }
878
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800880 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800881}
882
Jianing Weicb0652e2014-03-12 18:29:36 -0700883status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800884 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800886 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800887
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800888 switch (mStatus) {
889 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700890 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 return INVALID_OPERATION;
892 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700893 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700895 case STATUS_UNCONFIGURED:
896 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800897 case STATUS_ACTIVE:
898 // OK
899 break;
900 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700901 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 return INVALID_OPERATION;
903 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800904 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700905
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700906 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800907}
908
909status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
910 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700911 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800912
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700913 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800914}
915
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700916status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800917 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700918 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700919 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700920 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700921 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800922 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
923 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700924
925 status_t res;
926 bool wasActive = false;
927
928 switch (mStatus) {
929 case STATUS_ERROR:
930 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
931 return INVALID_OPERATION;
932 case STATUS_UNINITIALIZED:
933 ALOGE("%s: Device not initialized", __FUNCTION__);
934 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700935 case STATUS_UNCONFIGURED:
936 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700937 // OK
938 break;
939 case STATUS_ACTIVE:
940 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700941 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700943 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700944 return res;
945 }
946 wasActive = true;
947 break;
948 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950 return INVALID_OPERATION;
951 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700952 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700953
954 if (mInputStream != 0) {
955 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
956 return INVALID_OPERATION;
957 }
958
959 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
960 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700961 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700962
963 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800964 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700965
966 *id = mNextStreamId++;
967
968 // Continue captures if active at start
969 if (wasActive) {
970 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100971 // Reuse current operating mode and session parameters for new stream config
972 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700973 if (res != OK) {
974 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
975 __FUNCTION__, mNextStreamId, strerror(-res), res);
976 return res;
977 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700978 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979 }
980
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700982 return OK;
983}
984
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700985status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700986 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700987 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800988 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800989 const std::unordered_set<int32_t> &sensorPixelModesUsed,
990 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800991 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800992 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700993 ATRACE_CALL();
994
995 if (consumer == nullptr) {
996 ALOGE("%s: consumer must not be null", __FUNCTION__);
997 return BAD_VALUE;
998 }
999
1000 std::vector<sp<Surface>> consumers;
1001 consumers.push_back(consumer);
1002
1003 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001004 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001005 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001006 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001007}
1008
1009static bool isRawFormat(int format) {
1010 switch (format) {
1011 case HAL_PIXEL_FORMAT_RAW16:
1012 case HAL_PIXEL_FORMAT_RAW12:
1013 case HAL_PIXEL_FORMAT_RAW10:
1014 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1015 return true;
1016 default:
1017 return false;
1018 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001019}
1020
1021status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1022 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001023 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001024 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001025 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001026 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1027 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001028 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001029
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001030 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001031 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001032 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001033 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001034 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001035 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1036 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001037 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001038 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001039 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001040
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001041 status_t res;
1042 bool wasActive = false;
1043
1044 switch (mStatus) {
1045 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001046 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 return INVALID_OPERATION;
1048 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001049 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001051 case STATUS_UNCONFIGURED:
1052 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001053 // OK
1054 break;
1055 case STATUS_ACTIVE:
1056 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001057 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 return res;
1061 }
1062 wasActive = true;
1063 break;
1064 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001065 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066 return INVALID_OPERATION;
1067 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001068 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069
1070 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001071
Shuzhen Wang0129d522016-10-30 22:43:41 -07001072 if (consumers.size() == 0 && !hasDeferredConsumer) {
1073 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1074 return BAD_VALUE;
1075 }
Zhijun He5d677d12016-05-29 16:52:39 -07001076
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001078 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1079 return BAD_VALUE;
1080 }
1081
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001082 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1083 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1084 // be found in only one sensor pixel mode.
1085 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1086 return BAD_VALUE;
1087 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001089 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001090 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001091 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001092 if (blobBufferSize <= 0) {
1093 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1094 return BAD_VALUE;
1095 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001096 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1097 blobBufferSize = width * height;
1098 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001099 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001100 if (blobBufferSize <= 0) {
1101 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1102 return BAD_VALUE;
1103 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001104 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001105 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001106 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001107 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001108 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001109 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001110 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001111 bool maxResolution =
1112 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1113 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001114 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1115 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001116 if (rawOpaqueBufferSize <= 0) {
1117 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1118 return BAD_VALUE;
1119 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001121 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001122 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001123 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001124 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001125 } else if (isShared) {
1126 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1127 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001128 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001129 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001130 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001131 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001132 newStream = new Camera3OutputStream(mNextStreamId,
1133 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001134 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001135 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001136 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001138 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001139 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001140 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001141 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001142 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 }
Emilian Peev40ead602017-09-26 15:46:36 +01001144
1145 size_t consumerCount = consumers.size();
1146 for (size_t i = 0; i < consumerCount; i++) {
1147 int id = newStream->getSurfaceId(consumers[i]);
1148 if (id < 0) {
1149 SET_ERR_L("Invalid surface id");
1150 return BAD_VALUE;
1151 }
1152 if (surfaceIds != nullptr) {
1153 surfaceIds->push_back(id);
1154 }
1155 }
1156
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001157 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158
Emilian Peev08dd2452017-04-06 16:55:14 +01001159 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001160
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001161 newStream->setImageDumpMask(mImageDumpMask);
1162
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163 res = mOutputStreams.add(mNextStreamId, newStream);
1164 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001165 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001166 return res;
1167 }
1168
Shuzhen Wang316781a2020-08-18 18:11:01 -07001169 mSessionStatsBuilder.addStream(mNextStreamId);
1170
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001172 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173
1174 // Continue captures if active at start
1175 if (wasActive) {
1176 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001177 // Reuse current operating mode and session parameters for new stream config
1178 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1181 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182 return res;
1183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001186 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001188}
1189
Emilian Peev710c1422017-08-30 11:19:38 +01001190status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001191 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001192 if (nullptr == streamInfo) {
1193 return BAD_VALUE;
1194 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001197
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 switch (mStatus) {
1199 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 return INVALID_OPERATION;
1202 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001203 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001205 case STATUS_UNCONFIGURED:
1206 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 case STATUS_ACTIVE:
1208 // OK
1209 break;
1210 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001211 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 return INVALID_OPERATION;
1213 }
1214
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001215 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1216 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001217 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001218 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 }
1220
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001221 streamInfo->width = stream->getWidth();
1222 streamInfo->height = stream->getHeight();
1223 streamInfo->format = stream->getFormat();
1224 streamInfo->dataSpace = stream->getDataSpace();
1225 streamInfo->formatOverridden = stream->isFormatOverridden();
1226 streamInfo->originalFormat = stream->getOriginalFormat();
1227 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1228 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001229 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001231}
1232
1233status_t Camera3Device::setStreamTransform(int id,
1234 int transform) {
1235 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 switch (mStatus) {
1240 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001244 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 case STATUS_UNCONFIGURED:
1247 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 case STATUS_ACTIVE:
1249 // OK
1250 break;
1251 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001252 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 return INVALID_OPERATION;
1254 }
1255
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001256 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1257 if (stream == nullptr) {
1258 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return BAD_VALUE;
1260 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001261 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001262}
1263
1264status_t Camera3Device::deleteStream(int id) {
1265 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 Mutex::Autolock l(mLock);
1268 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001269
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001270 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001271
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 // CameraDevice semantics require device to already be idle before
1273 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001275 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001276 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 }
1278
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001279 if (mStatus == STATUS_ERROR) {
1280 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1281 __FUNCTION__, mId.string());
1282 return -EBUSY;
1283 }
1284
Igor Murashkin2fba5842013-04-22 14:03:54 -07001285 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001286 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 if (mInputStream != NULL && id == mInputStream->getId()) {
1288 deletedStream = mInputStream;
1289 mInputStream.clear();
1290 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001291 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001292 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 return BAD_VALUE;
1294 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001295 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001296 }
1297
1298 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001299 if (stream != nullptr) {
1300 deletedStream = stream;
1301 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 }
1303
1304 // Free up the stream endpoint so that it can be used by some other stream
1305 res = deletedStream->disconnect();
1306 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001307 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 // fall through since we want to still list the stream as deleted.
1309 }
1310 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001311 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312
1313 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001314}
1315
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001316status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001317 ATRACE_CALL();
1318 ALOGV("%s: E", __FUNCTION__);
1319
1320 Mutex::Autolock il(mInterfaceLock);
1321 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001322
Emilian Peev811d2952018-05-25 11:08:40 +01001323 // In case the client doesn't include any session parameter, try a
1324 // speculative configuration using the values from the last cached
1325 // default request.
1326 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001327 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001328 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1329 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1330 mLastTemplateId);
1331 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1332 operatingMode);
1333 }
1334
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001335 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1336}
1337
1338status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1339 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001340 //Filter out any incoming session parameters
1341 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001342 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1343 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001344 CameraMetadata filteredParams(availableSessionKeys.count);
1345 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1346 filteredParams.getAndLock());
1347 set_camera_metadata_vendor_id(meta, mVendorTagId);
1348 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001349 if (availableSessionKeys.count > 0) {
1350 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1351 camera_metadata_ro_entry entry = params.find(
1352 availableSessionKeys.data.i32[i]);
1353 if (entry.count > 0) {
1354 filteredParams.update(entry);
1355 }
1356 }
1357 }
1358
1359 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001360}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001361
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001362status_t Camera3Device::getInputBufferProducer(
1363 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001364 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001365 Mutex::Autolock il(mInterfaceLock);
1366 Mutex::Autolock l(mLock);
1367
1368 if (producer == NULL) {
1369 return BAD_VALUE;
1370 } else if (mInputStream == NULL) {
1371 return INVALID_OPERATION;
1372 }
1373
1374 return mInputStream->getInputBufferProducer(producer);
1375}
1376
Emilian Peevf4816702020-04-03 15:44:51 -07001377status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001378 CameraMetadata *request) {
1379 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001380 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001381
Emilian Peevf4816702020-04-03 15:44:51 -07001382 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001383 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001384 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001385 return BAD_VALUE;
1386 }
1387
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001390 {
1391 Mutex::Autolock l(mLock);
1392 switch (mStatus) {
1393 case STATUS_ERROR:
1394 CLOGE("Device has encountered a serious error");
1395 return INVALID_OPERATION;
1396 case STATUS_UNINITIALIZED:
1397 CLOGE("Device is not initialized!");
1398 return INVALID_OPERATION;
1399 case STATUS_UNCONFIGURED:
1400 case STATUS_CONFIGURED:
1401 case STATUS_ACTIVE:
1402 // OK
1403 break;
1404 default:
1405 SET_ERR_L("Unexpected status: %d", mStatus);
1406 return INVALID_OPERATION;
1407 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001408
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001409 if (!mRequestTemplateCache[templateId].isEmpty()) {
1410 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001411 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001412 return OK;
1413 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001414 }
1415
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416 camera_metadata_t *rawRequest;
1417 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001418 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001419
1420 {
1421 Mutex::Autolock l(mLock);
1422 if (res == BAD_VALUE) {
1423 ALOGI("%s: template %d is not supported on this camera device",
1424 __FUNCTION__, templateId);
1425 return res;
1426 } else if (res != OK) {
1427 CLOGE("Unable to construct request template %d: %s (%d)",
1428 templateId, strerror(-res), res);
1429 return res;
1430 }
1431
1432 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1433 mRequestTemplateCache[templateId].acquire(rawRequest);
1434
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001435 // Override the template request with zoomRatioMapper
1436 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1437 &mRequestTemplateCache[templateId]);
1438 if (res != OK) {
1439 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1440 templateId, strerror(-res), res);
1441 return res;
1442 }
1443
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001444 // Fill in JPEG_QUALITY if not available
1445 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1446 static const uint8_t kDefaultJpegQuality = 95;
1447 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1448 &kDefaultJpegQuality, 1);
1449 }
1450
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001451 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001452 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001453 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454 return OK;
1455}
1456
1457status_t Camera3Device::waitUntilDrained() {
1458 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001459 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001460 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001462
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001463 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001464}
1465
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001466status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 switch (mStatus) {
1468 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 ALOGV("%s: Already idle", __FUNCTION__);
1471 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001472 case STATUS_CONFIGURED:
1473 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 case STATUS_ERROR:
1475 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001476 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 break;
1478 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return INVALID_OPERATION;
1481 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001482 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1483 maxExpectedDuration);
1484 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001485 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001486 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001487 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1488 res);
1489 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001490 return res;
1491}
1492
Ruben Brunk183f0562015-08-12 12:55:02 -07001493void Camera3Device::internalUpdateStatusLocked(Status status) {
1494 mStatus = status;
1495 mRecentStatusUpdates.add(mStatus);
1496 mStatusChanged.broadcast();
1497}
1498
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001500status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001501 if (mRequestThread.get() != nullptr) {
1502 mRequestThread->setPaused(true);
1503 } else {
1504 return NO_INIT;
1505 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001507 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1508 maxExpectedDuration);
1509 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001510 if (res != OK) {
1511 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001512 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 }
1514
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 return res;
1516}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001518// Resume after internalPauseAndWaitLocked
1519status_t Camera3Device::internalResumeLocked() {
1520 status_t res;
1521
1522 mRequestThread->setPaused(false);
1523
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001524 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1525 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1527 if (res != OK) {
1528 SET_ERR_L("Can't transition to active in %f seconds!",
1529 kActiveTimeout/1e9);
1530 }
1531 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533}
1534
Ruben Brunk183f0562015-08-12 12:55:02 -07001535status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001537
1538 size_t startIndex = 0;
1539 if (mStatusWaiters == 0) {
1540 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1541 // this status list
1542 mRecentStatusUpdates.clear();
1543 } else {
1544 // If other threads are waiting on updates to this status list, set the position of the
1545 // first element that this list will check rather than clearing the list.
1546 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 }
1548
Ruben Brunk183f0562015-08-12 12:55:02 -07001549 mStatusWaiters++;
1550
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001551 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001552 if (!active && mUseHalBufManager) {
1553 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001554 if (mStatus == STATUS_ACTIVE) {
1555 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001556 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001557 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001558 mRequestBufferSM.onWaitUntilIdle();
1559 }
1560
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 bool stateSeen = false;
1562 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001563 if (active == (mStatus == STATUS_ACTIVE)) {
1564 // Desired state is current
1565 break;
1566 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567
1568 res = mStatusChanged.waitRelative(mLock, timeout);
1569 if (res != OK) break;
1570
Ruben Brunk183f0562015-08-12 12:55:02 -07001571 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1572 // transitions.
1573 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1574 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1575 __FUNCTION__);
1576
1577 // Encountered desired state since we began waiting
1578 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1580 stateSeen = true;
1581 break;
1582 }
1583 }
1584 } while (!stateSeen);
1585
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001586 if (signalPipelineDrain) {
1587 mRequestThread->resetPipelineDrain();
1588 }
1589
Ruben Brunk183f0562015-08-12 12:55:02 -07001590 mStatusWaiters--;
1591
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 return res;
1593}
1594
1595
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001596status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001598 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001600 if (listener != NULL && mListener != NULL) {
1601 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1602 }
1603 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001604 mRequestThread->setNotificationListener(listener);
1605 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001606
1607 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608}
1609
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001610bool Camera3Device::willNotify3A() {
1611 return false;
1612}
1613
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001615 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001616 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001618 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001619 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1620 if (st == std::cv_status::timeout) {
1621 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001622 }
1623 }
1624 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625}
1626
Jianing Weicb0652e2014-03-12 18:29:36 -07001627status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001629 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001631 if (mResultQueue.empty()) {
1632 return NOT_ENOUGH_DATA;
1633 }
1634
Jianing Weicb0652e2014-03-12 18:29:36 -07001635 if (frame == NULL) {
1636 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1637 return BAD_VALUE;
1638 }
1639
1640 CaptureResult &result = *(mResultQueue.begin());
1641 frame->mResultExtras = result.mResultExtras;
1642 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001643 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001644 mResultQueue.erase(mResultQueue.begin());
1645
1646 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647}
1648
1649status_t Camera3Device::triggerAutofocus(uint32_t id) {
1650 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001653 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1654 // Mix-in this trigger into the next request and only the next request.
1655 RequestTrigger trigger[] = {
1656 {
1657 ANDROID_CONTROL_AF_TRIGGER,
1658 ANDROID_CONTROL_AF_TRIGGER_START
1659 },
1660 {
1661 ANDROID_CONTROL_AF_TRIGGER_ID,
1662 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001663 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001664 };
1665
1666 return mRequestThread->queueTrigger(trigger,
1667 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668}
1669
1670status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1671 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001674 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1675 // Mix-in this trigger into the next request and only the next request.
1676 RequestTrigger trigger[] = {
1677 {
1678 ANDROID_CONTROL_AF_TRIGGER,
1679 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1680 },
1681 {
1682 ANDROID_CONTROL_AF_TRIGGER_ID,
1683 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001684 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001685 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 return mRequestThread->queueTrigger(trigger,
1688 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689}
1690
1691status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1692 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001693 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001695 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1696 // Mix-in this trigger into the next request and only the next request.
1697 RequestTrigger trigger[] = {
1698 {
1699 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1700 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1701 },
1702 {
1703 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1704 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001705 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001706 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001708 return mRequestThread->queueTrigger(trigger,
1709 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710}
1711
Jianing Weicb0652e2014-03-12 18:29:36 -07001712status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001713 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001714 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001715 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001716
Zhijun He7ef20392014-04-21 16:04:17 -07001717 {
1718 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001719
1720 // b/116514106 "disconnect()" can get called twice for the same device. The
1721 // camera device will not be initialized during the second run.
1722 if (mStatus == STATUS_UNINITIALIZED) {
1723 return OK;
1724 }
1725
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001726 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001727
1728 // Stop session and stream counter
1729 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001730 }
1731
Ravneetdbd5b242022-03-02 07:22:46 +00001732 // Calculate expected duration for flush with additional buffer time in ms for watchdog
1733 uint64_t maxExpectedDuration = (getExpectedInFlightDuration() + kBaseGetBufferWait) / 1e6;
1734 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1735 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1736
1737 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001738}
1739
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001741 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1742}
1743
1744status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001745 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001746 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001747 Mutex::Autolock il(mInterfaceLock);
1748 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001749
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001750 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1751 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752 CLOGE("Stream %d does not exist", streamId);
1753 return BAD_VALUE;
1754 }
1755
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001756 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001757 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001758 return BAD_VALUE;
1759 }
1760
1761 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001762 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001763 return BAD_VALUE;
1764 }
1765
Ruben Brunkc78ac262015-08-13 17:58:46 -07001766 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001767}
1768
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001769status_t Camera3Device::tearDown(int streamId) {
1770 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001771 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001772 Mutex::Autolock il(mInterfaceLock);
1773 Mutex::Autolock l(mLock);
1774
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001775 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1776 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001777 CLOGE("Stream %d does not exist", streamId);
1778 return BAD_VALUE;
1779 }
1780
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001781 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1782 CLOGE("Stream %d is a target of a in-progress request", streamId);
1783 return BAD_VALUE;
1784 }
1785
1786 return stream->tearDown();
1787}
1788
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001789status_t Camera3Device::addBufferListenerForStream(int streamId,
1790 wp<Camera3StreamBufferListener> listener) {
1791 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001792 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001793 Mutex::Autolock il(mInterfaceLock);
1794 Mutex::Autolock l(mLock);
1795
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001796 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1797 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001798 CLOGE("Stream %d does not exist", streamId);
1799 return BAD_VALUE;
1800 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001801 stream->addBufferListener(listener);
1802
1803 return OK;
1804}
1805
Austin Borger4a870a32022-02-25 01:48:41 +00001806float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1807 camera_metadata_entry minDurations =
1808 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1809 for (size_t i = 0; i < minDurations.count; i += 4) {
1810 if (minDurations.data.i64[i] == stream->getFormat()
1811 && minDurations.data.i64[i+1] == stream->getWidth()
1812 && minDurations.data.i64[i+2] == stream->getHeight()) {
1813 int64_t minFrameDuration = minDurations.data.i64[i+3];
1814 return 1e9f / minFrameDuration;
1815 }
1816 }
1817 return 0.0f;
1818}
1819
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 * Methods called by subclasses
1822 */
1823
1824void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001825 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001826 std::vector<int> streamIds;
1827 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001828 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001829
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001830 {
1831 // Need mLock to safely update state and synchronize to current
1832 // state of methods in flight.
1833 Mutex::Autolock l(mLock);
1834 // We can get various system-idle notices from the status tracker
1835 // while starting up. Only care about them if we've actually sent
1836 // in some requests recently.
1837 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1838 return;
1839 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001840 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1841 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001842 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843
1844 // Skip notifying listener if we're doing some user-transparent
1845 // state changes
1846 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001847
Austin Borger4a870a32022-02-25 01:48:41 +00001848 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1849 auto stream = mOutputStreams[i];
1850 if (stream.get() == nullptr) continue;
1851
1852 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1853 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1854
1855 // Populate stream statistics in case of Idle
1856 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001857 streamIds.push_back(stream->getId());
1858 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1859 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001860 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001861 if (camera3Stream != nullptr) {
1862 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001863 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001864 }
1865 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001866 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001867 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001868 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001869 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001870 }
1871 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001873
1874 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001876 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001877 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001879 status_t res = OK;
1880 if (listener != nullptr) {
1881 if (idle) {
1882 // Get session stats from the builder, and notify the listener.
1883 int64_t requestCount, resultErrorCount;
1884 bool deviceError;
1885 std::map<int, StreamStats> streamStatsMap;
1886 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1887 &deviceError, &streamStatsMap);
1888 for (size_t i = 0; i < streamIds.size(); i++) {
1889 int streamId = streamIds[i];
1890 auto stats = streamStatsMap.find(streamId);
1891 if (stats != streamStatsMap.end()) {
1892 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1893 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1894 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1895 streamStats[i].mHistogramType =
1896 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1897 streamStats[i].mHistogramBins.assign(
1898 stats->second.mCaptureLatencyBins.begin(),
1899 stats->second.mCaptureLatencyBins.end());
1900 streamStats[i].mHistogramCounts.assign(
1901 stats->second.mCaptureLatencyHistogram.begin(),
1902 stats->second.mCaptureLatencyHistogram.end());
1903 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001904 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001905 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1906 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001907 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001908 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001909 }
1910 if (res != OK) {
1911 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1912 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
1914}
1915
Shuzhen Wang758c2152017-01-10 18:26:18 -08001916status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001917 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001918 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001919 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1920 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001921
1922 if (surfaceIds == nullptr) {
1923 return BAD_VALUE;
1924 }
1925
Zhijun He5d677d12016-05-29 16:52:39 -07001926 Mutex::Autolock il(mInterfaceLock);
1927 Mutex::Autolock l(mLock);
1928
Shuzhen Wang758c2152017-01-10 18:26:18 -08001929 if (consumers.size() == 0) {
1930 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001931 return BAD_VALUE;
1932 }
1933
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001934 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1935 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001936 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001937 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001938 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001939
1940 // isConsumerConfigurationDeferred will be off after setConsumers
1941 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001942 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001943 if (res != OK) {
1944 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1945 return res;
1946 }
1947
Emilian Peev40ead602017-09-26 15:46:36 +01001948 for (auto &consumer : consumers) {
1949 int id = stream->getSurfaceId(consumer);
1950 if (id < 0) {
1951 CLOGE("Invalid surface id!");
1952 return BAD_VALUE;
1953 }
1954 surfaceIds->push_back(id);
1955 }
1956
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001957 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001958 if (!stream->isConfiguring()) {
1959 CLOGE("Stream %d was already fully configured.", streamId);
1960 return INVALID_OPERATION;
1961 }
Zhijun He5d677d12016-05-29 16:52:39 -07001962
Shuzhen Wang0129d522016-10-30 22:43:41 -07001963 res = stream->finishConfiguration();
1964 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001965 // If finishConfiguration fails due to abandoned surface, do not set
1966 // device to error state.
1967 bool isSurfaceAbandoned =
1968 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1969 if (!isSurfaceAbandoned) {
1970 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1971 stream->getId(), strerror(-res), res);
1972 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001973 return res;
1974 }
Zhijun He5d677d12016-05-29 16:52:39 -07001975 }
1976
1977 return OK;
1978}
1979
Emilian Peev40ead602017-09-26 15:46:36 +01001980status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1981 const std::vector<OutputStreamInfo> &outputInfo,
1982 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1983 Mutex::Autolock il(mInterfaceLock);
1984 Mutex::Autolock l(mLock);
1985
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001986 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1987 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001988 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001989 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001990 }
1991
1992 for (const auto &it : removedSurfaceIds) {
1993 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1994 CLOGE("Shared surface still part of a pending request!");
1995 return -EBUSY;
1996 }
1997 }
1998
Emilian Peev40ead602017-09-26 15:46:36 +01001999 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2000 if (res != OK) {
2001 CLOGE("Stream %d failed to update stream (error %d %s) ",
2002 streamId, res, strerror(-res));
2003 if (res == UNKNOWN_ERROR) {
2004 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2005 __FUNCTION__);
2006 }
2007 return res;
2008 }
2009
2010 return res;
2011}
2012
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002013status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2014 Mutex::Autolock il(mInterfaceLock);
2015 Mutex::Autolock l(mLock);
2016
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002017 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2018 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002019 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2020 return BAD_VALUE;
2021 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002022
2023 if (dropping) {
2024 mSessionStatsBuilder.stopCounter(streamId);
2025 } else {
2026 mSessionStatsBuilder.startCounter(streamId);
2027 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002028 return stream->dropBuffers(dropping);
2029}
2030
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002032 * Camera3Device private methods
2033 */
2034
2035sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002036 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002038
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002039 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002040 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041
2042 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002043 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002044 if (inputStreams.count > 0) {
2045 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002046 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002047 CLOGE("Request references unknown input stream %d",
2048 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049 return NULL;
2050 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002051
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002053 SET_ERR_L("%s: input stream %d is not configured!",
2054 __FUNCTION__, mInputStream->getId());
2055 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002057 // Check if stream prepare is blocking requests.
2058 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002059 CLOGE("Request references an input stream that's being prepared!");
2060 return NULL;
2061 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062
2063 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002064 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065 }
2066
2067 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002068 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002070 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return NULL;
2072 }
2073
2074 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002075 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2076 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002077 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002078 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 return NULL;
2080 }
Zhijun He5d677d12016-05-29 16:52:39 -07002081 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002082 auto iter = surfaceMap.find(streams.data.i32[i]);
2083 if (iter != surfaceMap.end()) {
2084 const std::vector<size_t>& surfaces = iter->second;
2085 for (const auto& surface : surfaces) {
2086 if (stream->isConsumerConfigurationDeferred(surface)) {
2087 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2088 "due to deferred consumer", stream->getId(), surface);
2089 return NULL;
2090 }
2091 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002092 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002093 }
2094
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002095 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002096 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2097 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002099 // Check if stream prepare is blocking requests.
2100 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101 CLOGE("Request references an output stream that's being prepared!");
2102 return NULL;
2103 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104
2105 newRequest->mOutputStreams.push(stream);
2106 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002107 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002108 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002110 auto rotateAndCropEntry =
2111 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2112 if (rotateAndCropEntry.count > 0 &&
2113 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2114 newRequest->mRotateAndCropAuto = true;
2115 } else {
2116 newRequest->mRotateAndCropAuto = false;
2117 }
2118
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002119 auto zoomRatioEntry =
2120 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2121 if (zoomRatioEntry.count > 0 &&
2122 zoomRatioEntry.data.f[0] == 1.0f) {
2123 newRequest->mZoomRatioIs1x = true;
2124 } else {
2125 newRequest->mZoomRatioIs1x = false;
2126 }
2127
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002128 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002129 for (auto& settings : newRequest->mSettingsList) {
2130 auto testPatternModeEntry =
2131 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2132 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2133 testPatternModeEntry.data.i32[0] :
2134 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002135
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002136 auto testPatternDataEntry =
2137 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2138 if (testPatternDataEntry.count >= 4) {
2139 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2140 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2141 } else {
2142 settings.mOriginalTestPatternData[0] = 0;
2143 settings.mOriginalTestPatternData[1] = 0;
2144 settings.mOriginalTestPatternData[2] = 0;
2145 settings.mOriginalTestPatternData[3] = 0;
2146 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002147 }
2148 }
2149
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002151}
2152
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002153void Camera3Device::cancelStreamsConfigurationLocked() {
2154 int res = OK;
2155 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2156 res = mInputStream->cancelConfiguration();
2157 if (res != OK) {
2158 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2159 mInputStream->getId(), strerror(-res), res);
2160 }
2161 }
2162
2163 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002164 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002165 if (outputStream->isConfiguring()) {
2166 res = outputStream->cancelConfiguration();
2167 if (res != OK) {
2168 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2169 outputStream->getId(), strerror(-res), res);
2170 }
2171 }
2172 }
2173
2174 // Return state to that at start of call, so that future configures
2175 // properly clean things up
2176 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2177 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002178
2179 res = mPreparerThread->resume();
2180 if (res != OK) {
2181 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2182 }
2183}
2184
Emilian Peev0d0191e2020-04-21 17:01:18 -07002185bool Camera3Device::checkAbandonedStreamsLocked() {
2186 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2187 return true;
2188 }
2189
2190 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2191 auto stream = mOutputStreams[i];
2192 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2193 return true;
2194 }
2195 }
2196
2197 return false;
2198}
2199
Emilian Peev3bead5f2020-05-28 17:29:08 -07002200bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002201 ATRACE_CALL();
2202 bool ret = false;
2203
Shuzhen Wang316781a2020-08-18 18:11:01 -07002204 nsecs_t startTime = systemTime();
2205
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002206 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002207 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2208
2209 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002210 if (checkAbandonedStreamsLocked()) {
2211 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2212 __FUNCTION__);
2213 return true;
2214 }
2215
Emilian Peev3bead5f2020-05-28 17:29:08 -07002216 status_t rc = NO_ERROR;
2217 bool markClientActive = false;
2218 if (mStatus == STATUS_ACTIVE) {
2219 markClientActive = true;
2220 mPauseStateNotify = true;
2221 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2222
2223 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2224 }
2225
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002226 if (rc == NO_ERROR) {
2227 mNeedConfig = true;
2228 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2229 if (rc == NO_ERROR) {
2230 ret = true;
2231 mPauseStateNotify = false;
2232 //Moving to active state while holding 'mLock' is important.
2233 //There could be pending calls to 'create-/deleteStream' which
2234 //will trigger another stream configuration while the already
2235 //present streams end up with outstanding buffers that will
2236 //not get drained.
2237 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002238 } else if (rc == DEAD_OBJECT) {
2239 // DEAD_OBJECT can be returned if either the consumer surface is
2240 // abandoned, or the HAL has died.
2241 // - If the HAL has died, configureStreamsLocked call will set
2242 // device to error state,
2243 // - If surface is abandoned, we should not set device to error
2244 // state.
2245 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002246 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002247 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002248 }
2249 } else {
2250 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2251 }
2252
Shuzhen Wang316781a2020-08-18 18:11:01 -07002253 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2254 ns2ms(systemTime() - startTime));
2255
Emilian Peev3bead5f2020-05-28 17:29:08 -07002256 if (markClientActive) {
2257 mStatusTracker->markComponentActive(clientStatusId);
2258 }
2259
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002260 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002261}
2262
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002263status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002264 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 ATRACE_CALL();
2266 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002268 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002269 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270 return INVALID_OPERATION;
2271 }
2272
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002273 if (operatingMode < 0) {
2274 CLOGE("Invalid operating mode: %d", operatingMode);
2275 return BAD_VALUE;
2276 }
2277
2278 bool isConstrainedHighSpeed =
2279 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2280 operatingMode;
2281
2282 if (mOperatingMode != operatingMode) {
2283 mNeedConfig = true;
2284 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2285 mOperatingMode = operatingMode;
2286 }
2287
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002288 // In case called from configureStreams, abort queued input buffers not belonging to
2289 // any pending requests.
2290 if (mInputStream != NULL && notifyRequestThread) {
2291 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002292 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002293 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002294 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002295 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002296 if (res != OK) {
2297 // Exhausted acquiring all input buffers.
2298 break;
2299 }
2300
Emilian Peevf4816702020-04-03 15:44:51 -07002301 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002302 res = mInputStream->returnInputBuffer(inputBuffer);
2303 if (res != OK) {
2304 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2305 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2306 }
2307 }
2308 }
2309
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002310 if (!mNeedConfig) {
2311 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2312 return OK;
2313 }
2314
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002315 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002316 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002317 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2318 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002319 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002320 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002321 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002322 }
2323
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002324 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002325 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002327 mPreparerThread->pause();
2328
Emilian Peevf4816702020-04-03 15:44:51 -07002329 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002330 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002332 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333
Emilian Peevf4816702020-04-03 15:44:51 -07002334 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002335 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002336 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002337
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002338
2339 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002340 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002341 inputStream = mInputStream->startConfiguration();
2342 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002343 CLOGE("Can't start input stream configuration");
2344 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345 return INVALID_OPERATION;
2346 }
2347 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002348
2349 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 }
2351
Shuzhen Wang99080502021-03-07 21:08:20 -08002352 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002353 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002355
2356 // Don't configure bidi streams twice, nor add them twice to the list
2357 if (mOutputStreams[i].get() ==
2358 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2359
2360 config.num_streams--;
2361 continue;
2362 }
2363
Emilian Peevf4816702020-04-03 15:44:51 -07002364 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002365 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002367 CLOGE("Can't start output stream configuration");
2368 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 return INVALID_OPERATION;
2370 }
2371 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002372
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002373 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002374 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2375 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002376 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2377 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002378 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2379 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002380 } else if (outputStream->data_space ==
2381 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2382 bufferSizes[k] = outputStream->width * outputStream->height;
2383 } else {
2384 ALOGW("%s: Blob dataSpace %d not supported",
2385 __FUNCTION__, outputStream->data_space);
2386 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002387 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002388
2389 if (mOutputStreams[i]->isMultiResolution()) {
2390 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2391 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2392 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2393 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002394
2395 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2396 composerSurfacePresent = true;
2397 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 }
2399
2400 config.streams = streams.editArray();
2401
2402 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002403 // max_buffers, usage, and priv fields, as well as data_space and format
2404 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002405
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002406 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002407 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002408 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002410 if (res == BAD_VALUE) {
2411 // HAL rejected this set of streams as unsupported, clean up config
2412 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002413 CLOGE("Set of requested inputs/outputs not supported by HAL");
2414 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002415 return BAD_VALUE;
2416 } else if (res != OK) {
2417 // Some other kind of error from configure_streams - this is not
2418 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002419 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2420 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002421 return res;
2422 }
2423
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002424 // Finish all stream configuration immediately.
2425 // TODO: Try to relax this later back to lazy completion, which should be
2426 // faster
2427
Igor Murashkin073f8572013-05-02 14:59:28 -07002428 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002429 bool streamReConfigured = false;
2430 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002431 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002432 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002433 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002434 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002435 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2436 return DEAD_OBJECT;
2437 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002438 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002439 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002440 if (streamReConfigured) {
2441 mInterface->onStreamReConfigured(mInputStream->getId());
2442 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002443 }
2444
2445 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002446 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002447 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002448 bool streamReConfigured = false;
2449 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002450 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002451 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002452 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002453 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002454 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2455 return DEAD_OBJECT;
2456 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002458 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002459 if (streamReConfigured) {
2460 mInterface->onStreamReConfigured(outputStream->getId());
2461 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002462 }
2463 }
2464
Emilian Peeve23f1d92021-09-20 14:56:01 -07002465 mRequestThread->setComposerSurface(composerSurfacePresent);
2466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467 // Request thread needs to know to avoid using repeat-last-settings protocol
2468 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002469 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002470 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2471 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002472 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002473
Zhijun He90f7c372016-08-16 16:19:43 -07002474 char value[PROPERTY_VALUE_MAX];
2475 property_get("camera.fifo.disable", value, "0");
2476 int32_t disableFifo = atoi(value);
2477 if (disableFifo != 1) {
2478 // Boost priority of request thread to SCHED_FIFO.
2479 pid_t requestThreadTid = mRequestThread->getTid();
2480 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002481 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002482 if (res != OK) {
2483 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2484 strerror(-res), res);
2485 } else {
2486 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2487 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002488 }
2489
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002490 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002491 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2492 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2493 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2494 sessionParams.unlock(newSessionParams);
2495 mSessionParams.unlock(currentSessionParams);
2496 if (updateSessionParams) {
2497 mSessionParams = sessionParams;
2498 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002499
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002500 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002501
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002502 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002503 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002505 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002506
Zhijun He0a210512014-07-24 13:45:15 -07002507 // tear down the deleted streams after configure streams.
2508 mDeletedStreams.clear();
2509
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002510 auto rc = mPreparerThread->resume();
2511 if (rc != OK) {
2512 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2513 return rc;
2514 }
2515
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002516 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002517 mRequestBufferSM.onStreamsConfigured();
2518 }
2519
Cliff Wu3b268182021-07-06 15:44:43 +08002520 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002521 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002522 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002523 // configure the injection streams.
2524 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002525 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002526 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2527 res = mInjectionMethods->injectCamera(config, bufferSizes);
2528 if (res != OK) {
2529 ALOGE("Can't finish inject camera process!");
2530 return res;
2531 }
Cliff Wu3b268182021-07-06 15:44:43 +08002532 } else {
2533 // First run configureStreamsLocked() and then call injectCamera() case:
2534 // If the stream configuration has been completed and camera deive is active, but the
2535 // injection camera has not been injected yet, we need to store the stream configuration of
2536 // the internal camera (because the stream configuration of the injection camera is based
2537 // on the internal camera). When injecting occurs later, this configuration can be used by
2538 // the injection camera.
2539 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2540 " injection camera has not been injected yet.", __FUNCTION__);
2541 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002542 }
2543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002545}
2546
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002547status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548 ATRACE_CALL();
2549 status_t res;
2550
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 if (mFakeStreamId != NO_STREAM) {
2552 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002553 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002554 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002555 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 return INVALID_OPERATION;
2557 }
2558
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002559 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002560
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002561 sp<Camera3OutputStreamInterface> fakeStream =
2562 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002563
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002564 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002565 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002566 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002567 return res;
2568 }
2569
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002570 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002571 mNextStreamId++;
2572
2573 return OK;
2574}
2575
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002576status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002577 ATRACE_CALL();
2578 status_t res;
2579
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002580 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002581 if (mOutputStreams.size() == 1) return OK;
2582
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002583 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002585 // Ok, have a fake stream and there's at least one other output stream,
2586 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002587
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002588 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002590 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002591 return INVALID_OPERATION;
2592 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002593 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002594
2595 // Free up the stream endpoint so that it can be used by some other stream
2596 res = deletedStream->disconnect();
2597 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002598 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002599 // fall through since we want to still list the stream as deleted.
2600 }
2601 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002602 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002603
2604 return res;
2605}
2606
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002607void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002608 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002609 Mutex::Autolock l(mLock);
2610 va_list args;
2611 va_start(args, fmt);
2612
2613 setErrorStateLockedV(fmt, args);
2614
2615 va_end(args);
2616}
2617
2618void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002619 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002620 Mutex::Autolock l(mLock);
2621 setErrorStateLockedV(fmt, args);
2622}
2623
2624void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2625 va_list args;
2626 va_start(args, fmt);
2627
2628 setErrorStateLockedV(fmt, args);
2629
2630 va_end(args);
2631}
2632
2633void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002634 // Print out all error messages to log
2635 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002636 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002637
2638 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002639 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002640
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002641 mErrorCause = errorCause;
2642
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002643 if (mRequestThread != nullptr) {
2644 mRequestThread->setPaused(true);
2645 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002646 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002647
2648 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002649 sp<NotificationListener> listener = mListener.promote();
2650 if (listener != NULL) {
2651 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002652 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002653 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002654 }
2655
2656 // Save stack trace. View by dumping it later.
2657 CameraTraces::saveTrace();
2658 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002659}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
2661/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002662 * In-flight request management
2663 */
2664
Jianing Weicb0652e2014-03-12 18:29:36 -07002665status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002666 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002667 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002668 const std::set<std::set<String8>>& physicalCameraIds,
2669 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2670 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002671 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002672 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002673 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002674
2675 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002676 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002677 hasAppCallback, minExpectedDuration, maxExpectedDuration, physicalCameraIds,
2678 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2679 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002680 if (res < 0) return res;
2681
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002682 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002683 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2684 // avoid a deadlock during reprocess requests.
2685 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002686 if (mStatusTracker != nullptr) {
2687 mStatusTracker->markComponentActive(mInFlightStatusId);
2688 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002689 }
2690
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002691 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002692 return OK;
2693}
2694
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002695void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002696 // Indicate idle inFlightMap to the status tracker
2697 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002698 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002699 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2700 // avoid a deadlock during reprocess requests.
2701 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002702 if (mStatusTracker != nullptr) {
2703 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2704 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002705 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002706 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002707}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002708
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002709void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002710 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002711 // something has likely gone wrong. This might still be legit only if application send in
2712 // a long burst of long exposure requests.
2713 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2714 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2715 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2716 mInFlightMap.size(), mExpectedInflightDuration);
2717 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2718 kInFlightWarnLimitHighSpeed) {
2719 CLOGW("In-flight list too large for high speed configuration: %zu,"
2720 "total inflight duration %" PRIu64,
2721 mInFlightMap.size(), mExpectedInflightDuration);
2722 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002723 }
2724}
2725
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002726void Camera3Device::onInflightMapFlushedLocked() {
2727 mExpectedInflightDuration = 0;
2728}
2729
2730void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002731 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002732 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2733 mInFlightMap.removeItemsAt(idx, 1);
2734
2735 onInflightEntryRemovedLocked(duration);
2736}
2737
2738
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002739void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002740 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002741 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002742 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002743 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002744 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002745 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002746
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002747 FlushInflightReqStates states {
2748 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002749 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002750
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002751 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002752}
2753
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002754CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002755 ALOGV("%s", __FUNCTION__);
2756
Igor Murashkin1e479c02013-09-06 16:55:14 -07002757 CameraMetadata retVal;
2758
2759 if (mRequestThread != NULL) {
2760 retVal = mRequestThread->getLatestRequest();
2761 }
2762
Igor Murashkin1e479c02013-09-06 16:55:14 -07002763 return retVal;
2764}
2765
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002766void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002767 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002768 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002769 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2770 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002771
2772 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002773 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002774}
2775
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002776void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002777 std::vector<native_handle_t*> *handles, bool closeFd) {
2778 if (handles == nullptr) {
2779 return;
2780 }
2781 if (closeFd) {
2782 for (auto& handle : *handles) {
2783 native_handle_close(handle);
2784 }
2785 }
2786 for (auto& handle : *handles) {
2787 native_handle_delete(handle);
2788 }
2789 handles->clear();
2790 return;
2791}
2792
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002793/**
2794 * HalInterface inner class methods
2795 */
2796
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002797void Camera3Device::HalInterface::getInflightBufferKeys(
2798 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002799 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002800 return;
2801}
2802
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002803void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2804 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002805 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002806 return;
2807}
2808
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002809bool Camera3Device::HalInterface::verifyBufferIds(
2810 int32_t streamId, std::vector<uint64_t>& bufIds) {
2811 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002812}
2813
2814status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002815 int32_t frameNumber, int32_t streamId,
2816 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002817 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002818}
2819
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002820status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002821 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002822 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002823}
2824
2825// Find and pop a buffer_handle_t based on bufferId
2826status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002827 uint64_t bufferId,
2828 /*out*/ buffer_handle_t** buffer,
2829 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002830 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002831}
2832
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002833std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2834 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002835 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002836}
2837
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002838uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2839 const native_handle_t* handle) {
2840 return mBufferRecords.removeOneBufferCache(streamId, handle);
2841}
2842
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002843void Camera3Device::HalInterface::onBufferFreed(
2844 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002845 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2846 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2847 if (bufferId != BUFFER_ID_NO_BUFFER) {
2848 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002849 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002850}
2851
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002852void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002853 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2854 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2855 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002856 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2857 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002858}
2859
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002860/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002861 * RequestThread inner class methods
2862 */
2863
2864Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002865 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002866 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002867 bool useHalBufManager,
2868 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002869 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002870 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002871 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002872 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002873 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002874 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002875 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002876 mReconfigured(false),
2877 mDoPause(false),
2878 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002879 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002880 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002881 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002882 mCurrentAfTriggerId(0),
2883 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002884 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002885 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002886 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002887 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002888 mRepeatingLastFrameNumber(
2889 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002890 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002891 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002892 mRequestLatency(kRequestLatencyBinSize),
2893 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002894 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002895 mUseHalBufManager(useHalBufManager),
2896 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002897 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002898}
2899
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002900Camera3Device::RequestThread::~RequestThread() {}
2901
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002902void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002903 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002904 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002905 Mutex::Autolock l(mRequestLock);
2906 mListener = listener;
2907}
2908
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002909void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002910 const CameraMetadata& sessionParams,
2911 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002912 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002913 Mutex::Autolock l(mRequestLock);
2914 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002915 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002916 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002917 // Prepare video stream for high speed recording.
2918 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002919 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002920}
2921
Jianing Wei90e59c92014-03-12 18:29:36 -07002922status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002923 List<sp<CaptureRequest> > &requests,
2924 /*out*/
2925 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002927 Mutex::Autolock l(mRequestLock);
2928 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2929 ++it) {
2930 mRequestQueue.push_back(*it);
2931 }
2932
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002933 if (lastFrameNumber != NULL) {
2934 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2935 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2936 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2937 *lastFrameNumber);
2938 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002939
Jianing Wei90e59c92014-03-12 18:29:36 -07002940 unpauseForNewRequests();
2941
2942 return OK;
2943}
2944
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002945
2946status_t Camera3Device::RequestThread::queueTrigger(
2947 RequestTrigger trigger[],
2948 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002949 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002950 Mutex::Autolock l(mTriggerMutex);
2951 status_t ret;
2952
2953 for (size_t i = 0; i < count; ++i) {
2954 ret = queueTriggerLocked(trigger[i]);
2955
2956 if (ret != OK) {
2957 return ret;
2958 }
2959 }
2960
2961 return OK;
2962}
2963
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002964const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2965 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002966 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002967 if (d != nullptr) return d->mId;
2968 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002969}
2970
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002971status_t Camera3Device::RequestThread::queueTriggerLocked(
2972 RequestTrigger trigger) {
2973
2974 uint32_t tag = trigger.metadataTag;
2975 ssize_t index = mTriggerMap.indexOfKey(tag);
2976
2977 switch (trigger.getTagType()) {
2978 case TYPE_BYTE:
2979 // fall-through
2980 case TYPE_INT32:
2981 break;
2982 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002983 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2984 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002985 return INVALID_OPERATION;
2986 }
2987
2988 /**
2989 * Collect only the latest trigger, since we only have 1 field
2990 * in the request settings per trigger tag, and can't send more than 1
2991 * trigger per request.
2992 */
2993 if (index != NAME_NOT_FOUND) {
2994 mTriggerMap.editValueAt(index) = trigger;
2995 } else {
2996 mTriggerMap.add(tag, trigger);
2997 }
2998
2999 return OK;
3000}
3001
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003002status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003003 const RequestList &requests,
3004 /*out*/
3005 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003006 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003007 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003008 if (lastFrameNumber != NULL) {
3009 *lastFrameNumber = mRepeatingLastFrameNumber;
3010 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003011 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003012 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003013 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3014 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003015
3016 unpauseForNewRequests();
3017
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003018 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003019 return OK;
3020}
3021
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003022bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003023 if (mRepeatingRequests.empty()) {
3024 return false;
3025 }
3026 int32_t requestId = requestIn->mResultExtras.requestId;
3027 const RequestList &repeatRequests = mRepeatingRequests;
3028 // All repeating requests are guaranteed to have same id so only check first quest
3029 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3030 return (firstRequest->mResultExtras.requestId == requestId);
3031}
3032
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003033status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003034 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003035 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003036 return clearRepeatingRequestsLocked(lastFrameNumber);
3037
3038}
3039
3040status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003041 std::vector<int32_t> streamIds;
3042 for (const auto& request : mRepeatingRequests) {
3043 for (const auto& stream : request->mOutputStreams) {
3044 streamIds.push_back(stream->getId());
3045 }
3046 }
3047
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003048 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003049 if (lastFrameNumber != NULL) {
3050 *lastFrameNumber = mRepeatingLastFrameNumber;
3051 }
Emilian Peev2295df72021-11-12 18:14:10 -08003052
3053 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3054
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003056 return OK;
3057}
3058
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003059status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003060 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003061 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003062 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003063 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003064
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003065 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003066
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003067 // Send errors for all requests pending in the request queue, including
3068 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003069 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003070 if (listener != NULL) {
3071 for (RequestList::iterator it = mRequestQueue.begin();
3072 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003073 // Abort the input buffers for reprocess requests.
3074 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003075 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003076 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003077 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003078 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003079 if (res != OK) {
3080 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3081 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3082 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003083 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003084 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3085 if (res != OK) {
3086 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3087 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3088 }
3089 }
3090 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003091 // Set the frame number this request would have had, if it
3092 // had been submitted; this frame number will not be reused.
3093 // The requestId and burstId fields were set when the request was
3094 // submitted originally (in convertMetadataListToRequestListLocked)
3095 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003096 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003097 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003098 }
3099 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003100 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003101
3102 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003103 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003104 if (lastFrameNumber != NULL) {
3105 *lastFrameNumber = mRepeatingLastFrameNumber;
3106 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003107 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003108 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003109 return OK;
3110}
3111
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003112status_t Camera3Device::RequestThread::flush() {
3113 ATRACE_CALL();
3114 Mutex::Autolock l(mFlushLock);
3115
Emilian Peev08dd2452017-04-06 16:55:14 +01003116 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003117}
3118
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003119void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003120 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003121 Mutex::Autolock l(mPauseLock);
3122 mDoPause = paused;
3123 mDoPauseSignal.signal();
3124}
3125
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003126status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3127 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003128 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003129 Mutex::Autolock l(mLatestRequestMutex);
3130 status_t res;
3131 while (mLatestRequestId != requestId) {
3132 nsecs_t startTime = systemTime();
3133
3134 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3135 if (res != OK) return res;
3136
3137 timeout -= (systemTime() - startTime);
3138 }
3139
3140 return OK;
3141}
3142
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003143void Camera3Device::RequestThread::requestExit() {
3144 // Call parent to set up shutdown
3145 Thread::requestExit();
3146 // The exit from any possible waits
3147 mDoPauseSignal.signal();
3148 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003149
3150 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3151 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003152}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003153
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003154void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003155 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003156 bool surfaceAbandoned = false;
3157 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003158 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003159 {
3160 Mutex::Autolock l(mRequestLock);
3161 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3162 // repeating requests.
3163 for (const auto& request : mRepeatingRequests) {
3164 for (const auto& s : request->mOutputStreams) {
3165 if (s->isAbandoned()) {
3166 surfaceAbandoned = true;
3167 clearRepeatingRequestsLocked(&lastFrameNumber);
3168 break;
3169 }
3170 }
3171 if (surfaceAbandoned) {
3172 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003173 }
3174 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003175 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003176 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003177
3178 if (listener != NULL && surfaceAbandoned) {
3179 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003180 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003181}
3182
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003183bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003184 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003185 status_t res;
3186 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003187 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003188 uint32_t numRequestProcessed = 0;
3189 for (size_t i = 0; i < batchSize; i++) {
3190 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003191 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003192 }
3193
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003194 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3195
3196 bool triggerRemoveFailed = false;
3197 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3198 for (size_t i = 0; i < numRequestProcessed; i++) {
3199 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3200 nextRequest.submitted = true;
3201
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003202 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003203
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003204 if (!triggerRemoveFailed) {
3205 // Remove any previously queued triggers (after unlock)
3206 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3207 if (removeTriggerRes != OK) {
3208 triggerRemoveFailed = true;
3209 triggerFailedRequest = nextRequest;
3210 }
3211 }
3212 }
3213
3214 if (triggerRemoveFailed) {
3215 SET_ERR("RequestThread: Unable to remove triggers "
3216 "(capture request %d, HAL device: %s (%d)",
3217 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3218 cleanUpFailedRequests(/*sendRequestError*/ false);
3219 return false;
3220 }
3221
3222 if (res != OK) {
3223 // Should only get a failure here for malformed requests or device-level
3224 // errors, so consider all errors fatal. Bad metadata failures should
3225 // come through notify.
3226 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3227 mNextRequests[numRequestProcessed].halRequest.frame_number,
3228 strerror(-res), res);
3229 cleanUpFailedRequests(/*sendRequestError*/ false);
3230 return false;
3231 }
3232 return true;
3233}
3234
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003235std::pair<nsecs_t, nsecs_t> Camera3Device::RequestThread::calculateExpectedDurationRange(
3236 const camera_metadata_t *request) {
3237 std::pair<nsecs_t, nsecs_t> expectedRange(
3238 InFlightRequest::kDefaultMinExpectedDuration,
3239 InFlightRequest::kDefaultMaxExpectedDuration);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003240 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3241 find_camera_metadata_ro_entry(request,
3242 ANDROID_CONTROL_AE_MODE,
3243 &e);
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003244 if (e.count == 0) return expectedRange;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003245
3246 switch (e.data.u8[0]) {
3247 case ANDROID_CONTROL_AE_MODE_OFF:
3248 find_camera_metadata_ro_entry(request,
3249 ANDROID_SENSOR_EXPOSURE_TIME,
3250 &e);
3251 if (e.count > 0) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003252 expectedRange.first = e.data.i64[0];
3253 expectedRange.second = expectedRange.first;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003254 }
3255 find_camera_metadata_ro_entry(request,
3256 ANDROID_SENSOR_FRAME_DURATION,
3257 &e);
3258 if (e.count > 0) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003259 expectedRange.first = std::max(e.data.i64[0], expectedRange.first);
3260 expectedRange.second = expectedRange.first;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003261 }
3262 break;
3263 default:
3264 find_camera_metadata_ro_entry(request,
3265 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3266 &e);
3267 if (e.count > 1) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003268 expectedRange.first = 1e9 / e.data.i32[1];
3269 expectedRange.second = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003270 }
3271 break;
3272 }
3273
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003274 return expectedRange;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003275}
3276
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003277bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3278 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3279 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3280 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3281 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3282 return true;
3283 }
3284
3285 return false;
3286}
3287
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003288void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3289 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003290 camera_capture_request_t& halRequest = nextRequest.halRequest;
3291 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003292 Mutex::Autolock al(mLatestRequestMutex);
3293
Shuzhen Wang83bff122020-11-20 15:51:39 -08003294 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003295 mLatestRequest.acquire(cloned);
3296
3297 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003298 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3299 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3300 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003301 CameraMetadata(cloned));
3302 }
3303
3304 sp<Camera3Device> parent = mParent.promote();
3305 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003306 int32_t inputStreamId = -1;
3307 if (halRequest.input_buffer != nullptr) {
3308 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3309 }
3310
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003311 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003312 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003313 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3314 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003315 }
3316 }
3317
Shuzhen Wang83bff122020-11-20 15:51:39 -08003318 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003319 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003320 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003321 }
3322
Shuzhen Wang83bff122020-11-20 15:51:39 -08003323 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003324}
3325
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003326bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3327 ATRACE_CALL();
3328 bool updatesDetected = false;
3329
Emilian Peev4ec17882019-01-24 17:16:58 -08003330 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003331 for (auto tag : mSessionParamKeys) {
3332 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003333 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003334
3335 if (entry.count > 0) {
3336 bool isDifferent = false;
3337 if (lastEntry.count > 0) {
3338 // Have a last value, compare to see if changed
3339 if (lastEntry.type == entry.type &&
3340 lastEntry.count == entry.count) {
3341 // Same type and count, compare values
3342 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3343 size_t entryBytes = bytesPerValue * lastEntry.count;
3344 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3345 if (cmp != 0) {
3346 isDifferent = true;
3347 }
3348 } else {
3349 // Count or type has changed
3350 isDifferent = true;
3351 }
3352 } else {
3353 // No last entry, so always consider to be different
3354 isDifferent = true;
3355 }
3356
3357 if (isDifferent) {
3358 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003359 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3360 updatesDetected = true;
3361 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003362 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003363 }
3364 } else if (lastEntry.count > 0) {
3365 // Value has been removed
3366 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003367 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003368 updatesDetected = true;
3369 }
3370 }
3371
Emilian Peev4ec17882019-01-24 17:16:58 -08003372 bool reconfigureRequired;
3373 if (updatesDetected) {
3374 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3375 updatedParams);
3376 mLatestSessionParams = updatedParams;
3377 } else {
3378 reconfigureRequired = false;
3379 }
3380
3381 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003382}
3383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003384bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003385 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003386 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003387 // Any function called from threadLoop() must not hold mInterfaceLock since
3388 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3389 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003390
3391 // Handle paused state.
3392 if (waitIfPaused()) {
3393 return true;
3394 }
3395
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003396 // Wait for the next batch of requests.
3397 waitForNextRequestBatch();
3398 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003399 return true;
3400 }
3401
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003402 // Get the latest request ID, if any
3403 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003404 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003405 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003406 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003407 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003408 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003409 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3410 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003411 }
3412
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003413 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3414 // or a single request from streaming or burst. In either case the first element
3415 // should contain the latest camera settings that we need to check for any session
3416 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003417 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003418 res = OK;
3419
3420 //Input stream buffers are already acquired at this point so an input stream
3421 //will not be able to move to idle state unless we force it.
3422 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3423 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3424 if (res != OK) {
3425 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3426 cleanUpFailedRequests(/*sendRequestError*/ false);
3427 return false;
3428 }
3429 }
3430
3431 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003432 sp<Camera3Device> parent = mParent.promote();
3433 if (parent != nullptr) {
3434 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003435 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003436 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003437
3438 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3439 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3440 if (res != OK) {
3441 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3442 cleanUpFailedRequests(/*sendRequestError*/ false);
3443 return false;
3444 }
3445 }
3446 }
3447 }
3448
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003449 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003450 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003451 if (res == TIMED_OUT) {
3452 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003453 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003454 // Check if any stream is abandoned.
3455 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003456 return true;
3457 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003458 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003459 return false;
3460 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003461
Zhijun Hecc27e112013-10-03 16:12:43 -07003462 // Inform waitUntilRequestProcessed thread of a new request ID
3463 {
3464 Mutex::Autolock al(mLatestRequestMutex);
3465
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003466 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003467 mLatestRequestSignal.signal();
3468 }
3469
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003470 // Submit a batch of requests to HAL.
3471 // Use flush lock only when submitting multilple requests in a batch.
3472 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3473 // which may take a long time to finish so synchronizing flush() and
3474 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3475 // For now, only synchronize for high speed recording and we should figure something out for
3476 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003477 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003478
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003479 if (useFlushLock) {
3480 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003481 }
3482
Zhijun Hef0645c12016-08-02 00:58:11 -07003483 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003484 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003485
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003486 sp<Camera3Device> parent = mParent.promote();
3487 if (parent != nullptr) {
3488 parent->mRequestBufferSM.onSubmittingRequest();
3489 }
3490
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003491 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003492 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003493 submitRequestSuccess = sendRequestsBatch();
3494
Shuzhen Wang686f6442017-06-20 16:16:04 -07003495 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3496 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003497
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003498 if (useFlushLock) {
3499 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003500 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003501
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003502 // Unset as current request
3503 {
3504 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003505 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003506 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003507 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003508
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003509 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003510}
3511
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003512status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3513 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3514 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3515 ANDROID_SCALER_CROP_REGION_SET};
3516 if (request == nullptr) {
3517 ALOGE("%s request metadata nullptr", __FUNCTION__);
3518 return BAD_VALUE;
3519 }
3520 status_t res = OK;
3521 for (const auto &key : kFwkOnlyRegionKeys) {
3522 if (request->exists(key)) {
3523 res = request->erase(key);
3524 if (res != OK) {
3525 return res;
3526 }
3527 }
3528 }
3529 return OK;
3530}
3531
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003532status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003533 ATRACE_CALL();
3534
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003535 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003536 for (size_t i = 0; i < mNextRequests.size(); i++) {
3537 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003538 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003539 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3540 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003541
3542 // Prepare a request to HAL
3543 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3544
3545 // Insert any queued triggers (before metadata is locked)
3546 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003547 if (res < 0) {
3548 SET_ERR("RequestThread: Unable to insert triggers "
3549 "(capture request %d, HAL device: %s (%d)",
3550 halRequest->frame_number, strerror(-res), res);
3551 return INVALID_OPERATION;
3552 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003553
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003554 int triggerCount = res;
3555 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3556 mPrevTriggers = triggerCount;
3557
Emilian Peeve23f1d92021-09-20 14:56:01 -07003558 // Do not override rotate&crop for stream configurations that include
3559 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3560 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3561 bool rotateAndCropChanged = mComposerOutput ? false :
3562 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003563 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003564
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003565 // If the request is the same as last, or we had triggers now or last time or
3566 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003567 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003568 (mPrevRequest != captureRequest || triggersMixedIn ||
3569 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003570 // Request settings are all the same within one batch, so only treat the first
3571 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003572 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003573 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003574 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003575 /**
3576 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003577 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003578 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003579 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003580 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003581 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003582 "(capture request %d, HAL device: %s (%d)",
3583 halRequest->frame_number, strerror(-res), res);
3584 return INVALID_OPERATION;
3585 }
3586
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003587 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003588 sp<Camera3Device> parent = mParent.promote();
3589 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003590 List<PhysicalCameraSettings>::iterator it;
3591 for (it = captureRequest->mSettingsList.begin();
3592 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003593 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3594 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003595 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3596 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3597 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3598 res);
3599 return INVALID_OPERATION;
3600 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003601 continue;
3602 }
3603
3604 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3605 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3606 updateCaptureRequest(&(it->metadata));
3607 if (res != OK) {
3608 SET_ERR("RequestThread: Unable to correct capture requests "
3609 "for scaler crop region and metering regions for request "
3610 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3611 res);
3612 return INVALID_OPERATION;
3613 }
3614 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003615 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3616 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3617 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3618 res);
3619 return INVALID_OPERATION;
3620 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003621 }
3622 }
3623
3624 // Correct metadata regions for distortion correction if enabled
3625 for (it = captureRequest->mSettingsList.begin();
3626 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003627 if (parent->mDistortionMappers.find(it->cameraId) ==
3628 parent->mDistortionMappers.end()) {
3629 continue;
3630 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003631
3632 if (!captureRequest->mDistortionCorrectionUpdated) {
3633 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3634 &(it->metadata));
3635 if (res != OK) {
3636 SET_ERR("RequestThread: Unable to correct capture requests "
3637 "for lens distortion for request %d: %s (%d)",
3638 halRequest->frame_number, strerror(-res), res);
3639 return INVALID_OPERATION;
3640 }
3641 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003642 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003643 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003644
3645 for (it = captureRequest->mSettingsList.begin();
3646 it != captureRequest->mSettingsList.end(); it++) {
3647 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3648 parent->mZoomRatioMappers.end()) {
3649 continue;
3650 }
3651
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003652 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003653 cameraIdsWithZoom.insert(it->cameraId);
3654 }
3655
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003656 if (!captureRequest->mZoomRatioUpdated) {
3657 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3658 &(it->metadata));
3659 if (res != OK) {
3660 SET_ERR("RequestThread: Unable to correct capture requests "
3661 "for zoom ratio for request %d: %s (%d)",
3662 halRequest->frame_number, strerror(-res), res);
3663 return INVALID_OPERATION;
3664 }
3665 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003666 }
3667 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003668 if (captureRequest->mRotateAndCropAuto &&
3669 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003670 for (it = captureRequest->mSettingsList.begin();
3671 it != captureRequest->mSettingsList.end(); it++) {
3672 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3673 if (mapper != parent->mRotateAndCropMappers.end()) {
3674 res = mapper->second.updateCaptureRequest(&(it->metadata));
3675 if (res != OK) {
3676 SET_ERR("RequestThread: Unable to correct capture requests "
3677 "for rotate-and-crop for request %d: %s (%d)",
3678 halRequest->frame_number, strerror(-res), res);
3679 return INVALID_OPERATION;
3680 }
3681 }
3682 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003683 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003684 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003685 }
3686 }
3687
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003688 /**
3689 * The request should be presorted so accesses in HAL
3690 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3691 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003692 captureRequest->mSettingsList.begin()->metadata.sort();
3693 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003694 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003695 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003696 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3697
3698 IF_ALOGV() {
3699 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3700 find_camera_metadata_ro_entry(
3701 halRequest->settings,
3702 ANDROID_CONTROL_AF_TRIGGER,
3703 &e
3704 );
3705 if (e.count > 0) {
3706 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3707 __FUNCTION__,
3708 halRequest->frame_number,
3709 e.data.u8[0]);
3710 }
3711 }
3712 } else {
3713 // leave request.settings NULL to indicate 'reuse latest given'
3714 ALOGVV("%s: Request settings are REUSED",
3715 __FUNCTION__);
3716 }
3717
Emilian Peevaebbe412018-01-15 13:53:24 +00003718 if (captureRequest->mSettingsList.size() > 1) {
3719 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3720 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003721 if (newRequest) {
3722 halRequest->physcam_settings =
3723 new const camera_metadata* [halRequest->num_physcam_settings];
3724 } else {
3725 halRequest->physcam_settings = nullptr;
3726 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003727 auto it = ++captureRequest->mSettingsList.begin();
3728 size_t i = 0;
3729 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3730 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003731 if (newRequest) {
3732 it->metadata.sort();
3733 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3734 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003735 }
3736 }
3737
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003738 uint32_t totalNumBuffers = 0;
3739
3740 // Fill in buffers
3741 if (captureRequest->mInputStream != NULL) {
3742 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003743
3744 halRequest->input_width = captureRequest->mInputBufferSize.width;
3745 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003746 totalNumBuffers += 1;
3747 } else {
3748 halRequest->input_buffer = NULL;
3749 }
3750
Emilian Peevf4816702020-04-03 15:44:51 -07003751 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003752 captureRequest->mOutputStreams.size());
3753 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003754 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003755
3756 sp<Camera3Device> parent = mParent.promote();
3757 if (parent == NULL) {
3758 // Should not happen, and nowhere to send errors to, so just log it
3759 CLOGE("RequestThread: Parent is gone");
3760 return INVALID_OPERATION;
3761 }
3762 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3763
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003764 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003765 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003766 sp<Camera3OutputStreamInterface> outputStream =
3767 captureRequest->mOutputStreams.editItemAt(j);
3768 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003769
3770 // Prepare video buffers for high speed recording on the first video request.
3771 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3772 // Only try to prepare video stream on the first video request.
3773 mPrepareVideoStream = false;
3774
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003775 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3776 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003777 while (res == NOT_ENOUGH_DATA) {
3778 res = outputStream->prepareNextBuffer();
3779 }
3780 if (res != OK) {
3781 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3782 __FUNCTION__, strerror(-res), res);
3783 outputStream->cancelPrepare();
3784 }
3785 }
3786
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003787 std::vector<size_t> uniqueSurfaceIds;
3788 res = outputStream->getUniqueSurfaceIds(
3789 captureRequest->mOutputSurfaces[streamId],
3790 &uniqueSurfaceIds);
3791 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3792 if (res != OK && res != INVALID_OPERATION) {
3793 ALOGE("%s: failed to query stream %d unique surface IDs",
3794 __FUNCTION__, streamId);
3795 return res;
3796 }
3797 if (res == OK) {
3798 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3799 }
3800
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003801 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003802 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003803 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003804 return TIMED_OUT;
3805 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003806 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003807 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003808 buffer.stream = outputStream->asHalStream();
3809 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003810 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003811 buffer.acquire_fence = -1;
3812 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003813 // Mark the output stream as unpreparable to block clients from calling
3814 // 'prepare' after this request reaches CameraHal and before the respective
3815 // buffers are requested.
3816 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003817 } else {
3818 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3819 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003820 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003821 if (res != OK) {
3822 // Can't get output buffer from gralloc queue - this could be due to
3823 // abandoned queue or other consumer misbehavior, so not a fatal
3824 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003825 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003826 " %s (%d)", strerror(-res), res);
3827
3828 return TIMED_OUT;
3829 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003830 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003831
3832 {
3833 sp<Camera3Device> parent = mParent.promote();
3834 if (parent != nullptr) {
3835 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3836 for (const auto& settings : captureRequest->mSettingsList) {
3837 if ((streamCameraId.isEmpty() &&
3838 parent->getId() == settings.cameraId.c_str()) ||
3839 streamCameraId == settings.cameraId.c_str()) {
3840 outputStream->fireBufferRequestForFrameNumber(
3841 captureRequest->mResultExtras.frameNumber,
3842 settings.metadata);
3843 }
3844 }
3845 }
3846 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003847
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003848 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003849 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3850 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3851 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3852 } else if (!physicalCameraId.isEmpty()) {
3853 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003854 }
3855 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003856 }
3857 totalNumBuffers += halRequest->num_output_buffers;
3858
3859 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003860 // If this request list is for constrained high speed recording (not
3861 // preview), and the current request is not the last one in the batch,
3862 // do not send callback to the app.
3863 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003864 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003865 hasCallback = false;
3866 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003867 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003868 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003869 const camera_metadata_t* settings = halRequest->settings;
3870 bool shouldUnlockSettings = false;
3871 if (settings == nullptr) {
3872 shouldUnlockSettings = true;
3873 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3874 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003875 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3876 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003877 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003878 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3879 isStillCapture = true;
3880 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3881 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003882
Emilian Peevaf8416e2021-02-04 17:52:43 -08003883 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003884 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003885 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3886 isZslCapture = true;
3887 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003888 }
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003889 auto expectedDurationRange = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003890 res = parent->registerInFlight(halRequest->frame_number,
3891 totalNumBuffers, captureRequest->mResultExtras,
3892 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003893 hasCallback,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003894 /*min*/expectedDurationRange.first,
3895 /*max*/expectedDurationRange.second,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003896 requestedPhysicalCameras, isStillCapture, isZslCapture,
3897 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003898 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003899 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003900 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3901 ", burstId = %" PRId32 ".",
3902 __FUNCTION__,
3903 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3904 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003905
3906 if (shouldUnlockSettings) {
3907 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3908 }
3909
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003910 if (res != OK) {
3911 SET_ERR("RequestThread: Unable to register new in-flight request:"
3912 " %s (%d)", strerror(-res), res);
3913 return INVALID_OPERATION;
3914 }
3915 }
3916
3917 return OK;
3918}
3919
Igor Murashkin1e479c02013-09-06 16:55:14 -07003920CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003921 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003922 Mutex::Autolock al(mLatestRequestMutex);
3923
3924 ALOGV("RequestThread::%s", __FUNCTION__);
3925
3926 return mLatestRequest;
3927}
3928
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003929bool Camera3Device::RequestThread::isStreamPending(
3930 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003931 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003932 Mutex::Autolock l(mRequestLock);
3933
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003934 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003935 if (!nextRequest.submitted) {
3936 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3937 if (stream == s) return true;
3938 }
3939 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003940 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003941 }
3942
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003943 for (const auto& request : mRequestQueue) {
3944 for (const auto& s : request->mOutputStreams) {
3945 if (stream == s) return true;
3946 }
3947 if (stream == request->mInputStream) return true;
3948 }
3949
3950 for (const auto& request : mRepeatingRequests) {
3951 for (const auto& s : request->mOutputStreams) {
3952 if (stream == s) return true;
3953 }
3954 if (stream == request->mInputStream) return true;
3955 }
3956
3957 return false;
3958}
Jianing Weicb0652e2014-03-12 18:29:36 -07003959
Emilian Peev40ead602017-09-26 15:46:36 +01003960bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3961 ATRACE_CALL();
3962 Mutex::Autolock l(mRequestLock);
3963
3964 for (const auto& nextRequest : mNextRequests) {
3965 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3966 if (s.first == streamId) {
3967 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3968 if (it != s.second.end()) {
3969 return true;
3970 }
3971 }
3972 }
3973 }
3974
3975 for (const auto& request : mRequestQueue) {
3976 for (const auto& s : request->mOutputSurfaces) {
3977 if (s.first == streamId) {
3978 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3979 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003980 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003981 }
3982 }
3983 }
3984 }
3985
3986 for (const auto& request : mRepeatingRequests) {
3987 for (const auto& s : request->mOutputSurfaces) {
3988 if (s.first == streamId) {
3989 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3990 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003991 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003992 }
3993 }
3994 }
3995 }
3996
3997 return false;
3998}
3999
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004000void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4001 if (!mUseHalBufManager) {
4002 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4003 return;
4004 }
4005
4006 Mutex::Autolock pl(mPauseLock);
4007 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004008 mInterface->signalPipelineDrain(streamIds);
4009 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004010 }
4011 // If request thread is still busy, wait until paused then notify HAL
4012 mNotifyPipelineDrain = true;
4013 mStreamIdsToBeDrained = streamIds;
4014}
4015
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004016void Camera3Device::RequestThread::resetPipelineDrain() {
4017 Mutex::Autolock pl(mPauseLock);
4018 mNotifyPipelineDrain = false;
4019 mStreamIdsToBeDrained.clear();
4020}
4021
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004022void Camera3Device::RequestThread::clearPreviousRequest() {
4023 Mutex::Autolock l(mRequestLock);
4024 mPrevRequest.clear();
4025}
4026
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004027status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4028 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4029 ATRACE_CALL();
4030 Mutex::Autolock l(mTriggerMutex);
4031 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4032 return BAD_VALUE;
4033 }
4034 mRotateAndCropOverride = rotateAndCropValue;
4035 return OK;
4036}
4037
Emilian Peeve23f1d92021-09-20 14:56:01 -07004038status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4039 ATRACE_CALL();
4040 Mutex::Autolock l(mTriggerMutex);
4041 mComposerOutput = composerSurfacePresent;
4042 return OK;
4043}
4044
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004045status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004046 ATRACE_CALL();
4047 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004048 if (muteMode != mCameraMute) {
4049 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004050 mCameraMuteChanged = true;
4051 }
4052 return OK;
4053}
4054
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004055nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004056 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004057 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004058 return mExpectedInflightDuration > kMinInflightDuration ?
4059 mExpectedInflightDuration : kMinInflightDuration;
4060}
4061
Emilian Peevaebbe412018-01-15 13:53:24 +00004062void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004063 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004064 if ((request == nullptr) || (halRequest == nullptr)) {
4065 ALOGE("%s: Invalid request!", __FUNCTION__);
4066 return;
4067 }
4068
4069 if (halRequest->num_physcam_settings > 0) {
4070 if (halRequest->physcam_id != nullptr) {
4071 delete [] halRequest->physcam_id;
4072 halRequest->physcam_id = nullptr;
4073 }
4074 if (halRequest->physcam_settings != nullptr) {
4075 auto it = ++(request->mSettingsList.begin());
4076 size_t i = 0;
4077 for (; it != request->mSettingsList.end(); it++, i++) {
4078 it->metadata.unlock(halRequest->physcam_settings[i]);
4079 }
4080 delete [] halRequest->physcam_settings;
4081 halRequest->physcam_settings = nullptr;
4082 }
4083 }
4084}
4085
Ravneetaeb20dc2022-03-30 05:33:03 +00004086status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4087 Mutex::Autolock il(mInterfaceLock);
4088 Mutex::Autolock l(mLock);
4089
4090 if (mCameraServiceWatchdog != NULL) {
4091 mCameraServiceWatchdog->setEnabled(enabled);
4092 }
4093
4094 return OK;
4095}
4096
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004097void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4098 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004099 return;
4100 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004101
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004102 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004103 // Skip the ones that have been submitted successfully.
4104 if (nextRequest.submitted) {
4105 continue;
4106 }
4107
4108 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004109 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4110 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004111
4112 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004113 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004114 }
4115
Emilian Peevaebbe412018-01-15 13:53:24 +00004116 cleanupPhysicalSettings(captureRequest, halRequest);
4117
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004118 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004119 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004120 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4121 }
4122
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004123 // No output buffer can be returned when using HAL buffer manager
4124 if (!mUseHalBufManager) {
4125 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4126 //Buffers that failed processing could still have
4127 //valid acquire fence.
4128 int acquireFence = (*outputBuffers)[i].acquire_fence;
4129 if (0 <= acquireFence) {
4130 close(acquireFence);
4131 outputBuffers->editItemAt(i).acquire_fence = -1;
4132 }
Emilian Peevf4816702020-04-03 15:44:51 -07004133 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004134 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4135 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004136 /*timestampIncreasing*/true, std::vector<size_t> (),
4137 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004138 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004139 }
4140
4141 if (sendRequestError) {
4142 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004143 sp<NotificationListener> listener = mListener.promote();
4144 if (listener != NULL) {
4145 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004146 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004147 captureRequest->mResultExtras);
4148 }
4149 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004150
4151 // Remove yet-to-be submitted inflight request from inflightMap
4152 {
4153 sp<Camera3Device> parent = mParent.promote();
4154 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004155 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004156 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4157 if (idx >= 0) {
4158 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4159 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4160 parent->removeInFlightMapEntryLocked(idx);
4161 }
4162 }
4163 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004165
4166 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004167 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004168}
4169
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004170void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004171 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004172 // Optimized a bit for the simple steady-state case (single repeating
4173 // request), to avoid putting that request in the queue temporarily.
4174 Mutex::Autolock l(mRequestLock);
4175
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004176 assert(mNextRequests.empty());
4177
4178 NextRequest nextRequest;
4179 nextRequest.captureRequest = waitForNextRequestLocked();
4180 if (nextRequest.captureRequest == nullptr) {
4181 return;
4182 }
4183
Emilian Peevf4816702020-04-03 15:44:51 -07004184 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004185 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004186 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004187
4188 // Wait for additional requests
4189 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4190
4191 for (size_t i = 1; i < batchSize; i++) {
4192 NextRequest additionalRequest;
4193 additionalRequest.captureRequest = waitForNextRequestLocked();
4194 if (additionalRequest.captureRequest == nullptr) {
4195 break;
4196 }
4197
Emilian Peevf4816702020-04-03 15:44:51 -07004198 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004199 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004200 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004201 }
4202
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004203 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004204 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004205 mNextRequests.size(), batchSize);
4206 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004207 }
4208
4209 return;
4210}
4211
4212sp<Camera3Device::CaptureRequest>
4213 Camera3Device::RequestThread::waitForNextRequestLocked() {
4214 status_t res;
4215 sp<CaptureRequest> nextRequest;
4216
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217 while (mRequestQueue.empty()) {
4218 if (!mRepeatingRequests.empty()) {
4219 // Always atomically enqueue all requests in a repeating request
4220 // list. Guarantees a complete in-sequence set of captures to
4221 // application.
4222 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004223 if (mFirstRepeating) {
4224 mFirstRepeating = false;
4225 } else {
4226 for (auto& request : requests) {
4227 // For repeating requests, override timestamp request using
4228 // the time a request is inserted into the request queue,
4229 // because the original repeating request will have an old
4230 // fixed timestamp.
4231 request->mRequestTimeNs = systemTime();
4232 }
4233 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234 RequestList::const_iterator firstRequest =
4235 requests.begin();
4236 nextRequest = *firstRequest;
4237 mRequestQueue.insert(mRequestQueue.end(),
4238 ++firstRequest,
4239 requests.end());
4240 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004241
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004242 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004243
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004244 break;
4245 }
4246
4247 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4248
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004249 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4250 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251 Mutex::Autolock pl(mPauseLock);
4252 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004253 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004254 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004255 if (mNotifyPipelineDrain) {
4256 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4257 mNotifyPipelineDrain = false;
4258 mStreamIdsToBeDrained.clear();
4259 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004260 // Let the tracker know
4261 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4262 if (statusTracker != 0) {
4263 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4264 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004265 sp<Camera3Device> parent = mParent.promote();
4266 if (parent != nullptr) {
4267 parent->mRequestBufferSM.onRequestThreadPaused();
4268 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004269 }
4270 // Stop waiting for now and let thread management happen
4271 return NULL;
4272 }
4273 }
4274
4275 if (nextRequest == NULL) {
4276 // Don't have a repeating request already in hand, so queue
4277 // must have an entry now.
4278 RequestList::iterator firstRequest =
4279 mRequestQueue.begin();
4280 nextRequest = *firstRequest;
4281 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004282 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4283 sp<NotificationListener> listener = mListener.promote();
4284 if (listener != NULL) {
4285 listener->notifyRequestQueueEmpty();
4286 }
4287 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004288 }
4289
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004290 // In case we've been unpaused by setPaused clearing mDoPause, need to
4291 // update internal pause state (capture/setRepeatingRequest unpause
4292 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004293 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004294 if (mPaused) {
4295 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4296 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4297 if (statusTracker != 0) {
4298 statusTracker->markComponentActive(mStatusId);
4299 }
4300 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 mPaused = false;
4302
4303 // Check if we've reconfigured since last time, and reset the preview
4304 // request if so. Can't use 'NULL request == repeat' across configure calls.
4305 if (mReconfigured) {
4306 mPrevRequest.clear();
4307 mReconfigured = false;
4308 }
4309
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004310 if (nextRequest != NULL) {
4311 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004312 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4313 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004314
4315 // Since RequestThread::clear() removes buffers from the input stream,
4316 // get the right buffer here before unlocking mRequestLock
4317 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004318 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4319 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004320 if (res != OK) {
4321 // Can't get input buffer from gralloc queue - this could be due to
4322 // disconnected queue or other producer misbehavior, so not a fatal
4323 // error
4324 ALOGE("%s: Can't get input buffer, skipping request:"
4325 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004326
4327 sp<NotificationListener> listener = mListener.promote();
4328 if (listener != NULL) {
4329 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004330 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004331 nextRequest->mResultExtras);
4332 }
4333 return NULL;
4334 }
4335 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004336 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004337
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 return nextRequest;
4339}
4340
4341bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004342 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004343 status_t res;
4344 Mutex::Autolock l(mPauseLock);
4345 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004346 if (mPaused == false) {
4347 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004348 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004349 if (mNotifyPipelineDrain) {
4350 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4351 mNotifyPipelineDrain = false;
4352 mStreamIdsToBeDrained.clear();
4353 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004354 // Let the tracker know
4355 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4356 if (statusTracker != 0) {
4357 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4358 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004359 sp<Camera3Device> parent = mParent.promote();
4360 if (parent != nullptr) {
4361 parent->mRequestBufferSM.onRequestThreadPaused();
4362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004364
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004365 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004366 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367 return true;
4368 }
4369 }
4370 // We don't set mPaused to false here, because waitForNextRequest needs
4371 // to further manage the paused state in case of starvation.
4372 return false;
4373}
4374
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004375void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004376 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004377 // With work to do, mark thread as unpaused.
4378 // If paused by request (setPaused), don't resume, to avoid
4379 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004380 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004381 Mutex::Autolock p(mPauseLock);
4382 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004383 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4384 if (mPaused) {
4385 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4386 if (statusTracker != 0) {
4387 statusTracker->markComponentActive(mStatusId);
4388 }
4389 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004390 mPaused = false;
4391 }
4392}
4393
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004394void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4395 sp<Camera3Device> parent = mParent.promote();
4396 if (parent != NULL) {
4397 va_list args;
4398 va_start(args, fmt);
4399
4400 parent->setErrorStateV(fmt, args);
4401
4402 va_end(args);
4403 }
4404}
4405
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004406status_t Camera3Device::RequestThread::insertTriggers(
4407 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004408 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004409 Mutex::Autolock al(mTriggerMutex);
4410
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004411 sp<Camera3Device> parent = mParent.promote();
4412 if (parent == NULL) {
4413 CLOGE("RequestThread: Parent is gone");
4414 return DEAD_OBJECT;
4415 }
4416
Emilian Peevaebbe412018-01-15 13:53:24 +00004417 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004418 size_t count = mTriggerMap.size();
4419
4420 for (size_t i = 0; i < count; ++i) {
4421 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004422 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004423
4424 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4425 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4426 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004427 if (isAeTrigger) {
4428 request->mResultExtras.precaptureTriggerId = triggerId;
4429 mCurrentPreCaptureTriggerId = triggerId;
4430 } else {
4431 request->mResultExtras.afTriggerId = triggerId;
4432 mCurrentAfTriggerId = triggerId;
4433 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004434 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004435 }
4436
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004437 camera_metadata_entry entry = metadata.find(tag);
4438
4439 if (entry.count > 0) {
4440 /**
4441 * Already has an entry for this trigger in the request.
4442 * Rewrite it with our requested trigger value.
4443 */
4444 RequestTrigger oldTrigger = trigger;
4445
4446 oldTrigger.entryValue = entry.data.u8[0];
4447
4448 mTriggerReplacedMap.add(tag, oldTrigger);
4449 } else {
4450 /**
4451 * More typical, no trigger entry, so we just add it
4452 */
4453 mTriggerRemovedMap.add(tag, trigger);
4454 }
4455
4456 status_t res;
4457
4458 switch (trigger.getTagType()) {
4459 case TYPE_BYTE: {
4460 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4461 res = metadata.update(tag,
4462 &entryValue,
4463 /*count*/1);
4464 break;
4465 }
4466 case TYPE_INT32:
4467 res = metadata.update(tag,
4468 &trigger.entryValue,
4469 /*count*/1);
4470 break;
4471 default:
4472 ALOGE("%s: Type not supported: 0x%x",
4473 __FUNCTION__,
4474 trigger.getTagType());
4475 return INVALID_OPERATION;
4476 }
4477
4478 if (res != OK) {
4479 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4480 ", value %d", __FUNCTION__, trigger.getTagName(),
4481 trigger.entryValue);
4482 return res;
4483 }
4484
4485 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4486 trigger.getTagName(),
4487 trigger.entryValue);
4488 }
4489
4490 mTriggerMap.clear();
4491
4492 return count;
4493}
4494
4495status_t Camera3Device::RequestThread::removeTriggers(
4496 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004497 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004498 Mutex::Autolock al(mTriggerMutex);
4499
Emilian Peevaebbe412018-01-15 13:53:24 +00004500 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004501
4502 /**
4503 * Replace all old entries with their old values.
4504 */
4505 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4506 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4507
4508 status_t res;
4509
4510 uint32_t tag = trigger.metadataTag;
4511 switch (trigger.getTagType()) {
4512 case TYPE_BYTE: {
4513 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4514 res = metadata.update(tag,
4515 &entryValue,
4516 /*count*/1);
4517 break;
4518 }
4519 case TYPE_INT32:
4520 res = metadata.update(tag,
4521 &trigger.entryValue,
4522 /*count*/1);
4523 break;
4524 default:
4525 ALOGE("%s: Type not supported: 0x%x",
4526 __FUNCTION__,
4527 trigger.getTagType());
4528 return INVALID_OPERATION;
4529 }
4530
4531 if (res != OK) {
4532 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4533 ", trigger value %d", __FUNCTION__,
4534 trigger.getTagName(), trigger.entryValue);
4535 return res;
4536 }
4537 }
4538 mTriggerReplacedMap.clear();
4539
4540 /**
4541 * Remove all new entries.
4542 */
4543 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4544 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4545 status_t res = metadata.erase(trigger.metadataTag);
4546
4547 if (res != OK) {
4548 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4549 ", trigger value %d", __FUNCTION__,
4550 trigger.getTagName(), trigger.entryValue);
4551 return res;
4552 }
4553 }
4554 mTriggerRemovedMap.clear();
4555
4556 return OK;
4557}
4558
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004559status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004560 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004561 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004562 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004563 status_t res;
4564
Emilian Peevaebbe412018-01-15 13:53:24 +00004565 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004566
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004567 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004568 // exists
4569 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4570 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4571 if (afTrigger.count > 0 &&
4572 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4573 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004574 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004575 if (res != OK) return res;
4576 }
4577
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004578 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004579 // if none already exists
4580 camera_metadata_entry pcTrigger =
4581 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4582 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4583 if (pcTrigger.count > 0 &&
4584 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4585 pcId.count == 0) {
4586 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004587 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004588 if (res != OK) return res;
4589 }
4590
4591 return OK;
4592}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004593
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004594bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4595 const sp<CaptureRequest> &request) {
4596 ATRACE_CALL();
4597
4598 if (request->mRotateAndCropAuto) {
4599 Mutex::Autolock l(mTriggerMutex);
4600 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4601
4602 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4603 if (rotateAndCropEntry.count > 0) {
4604 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4605 return false;
4606 } else {
4607 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4608 return true;
4609 }
4610 } else {
4611 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4612 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4613 &rotateAndCrop_u8, 1);
4614 return true;
4615 }
4616 }
4617 return false;
4618}
4619
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004620bool Camera3Device::RequestThread::overrideTestPattern(
4621 const sp<CaptureRequest> &request) {
4622 ATRACE_CALL();
4623
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004624 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004625
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004626 Mutex::Autolock l(mTriggerMutex);
4627
4628 bool changed = false;
4629
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004630 // For a multi-camera, the physical cameras support the same set of
4631 // test pattern modes as the logical camera.
4632 for (auto& settings : request->mSettingsList) {
4633 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004634
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004635 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4636 int32_t testPatternData[4] = {
4637 settings.mOriginalTestPatternData[0],
4638 settings.mOriginalTestPatternData[1],
4639 settings.mOriginalTestPatternData[2],
4640 settings.mOriginalTestPatternData[3]
4641 };
4642 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4643 testPatternMode = mCameraMute;
4644 testPatternData[0] = 0;
4645 testPatternData[1] = 0;
4646 testPatternData[2] = 0;
4647 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004648 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004649
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004650 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4651 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4652 if (testPatternEntry.count > 0) {
4653 if (testPatternEntry.data.i32[0] != testPatternMode) {
4654 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004655 changed = true;
4656 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004657 } else if (supportTestPatternModeKey) {
4658 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4659 &testPatternMode, 1);
4660 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004661 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004662
4663 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4664 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4665 if (testPatternColor.count >= 4) {
4666 for (size_t i = 0; i < 4; i++) {
4667 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4668 testPatternColor.data.i32[i] = testPatternData[i];
4669 changed = true;
4670 }
4671 }
4672 } else if (supportTestPatternDataKey) {
4673 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4674 testPatternData, 4);
4675 changed = true;
4676 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004677 }
4678
4679 return changed;
4680}
4681
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004682status_t Camera3Device::RequestThread::setHalInterface(
4683 sp<HalInterface> newHalInterface) {
4684 if (newHalInterface.get() == nullptr) {
4685 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4686 return DEAD_OBJECT;
4687 }
4688
4689 mInterface = newHalInterface;
4690
4691 return OK;
4692}
4693
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004694/**
4695 * PreparerThread inner class methods
4696 */
4697
4698Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004699 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004700 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004701}
4702
4703Camera3Device::PreparerThread::~PreparerThread() {
4704 Thread::requestExitAndWait();
4705 if (mCurrentStream != nullptr) {
4706 mCurrentStream->cancelPrepare();
4707 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4708 mCurrentStream.clear();
4709 }
4710 clear();
4711}
4712
Ruben Brunkc78ac262015-08-13 17:58:46 -07004713status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004714 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004715 status_t res;
4716
4717 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004718 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004719
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004720 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004721 if (res == OK) {
4722 // No preparation needed, fire listener right off
4723 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004724 if (listener != NULL) {
4725 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004726 }
4727 return OK;
4728 } else if (res != NOT_ENOUGH_DATA) {
4729 return res;
4730 }
4731
4732 // Need to prepare, start up thread if necessary
4733 if (!mActive) {
4734 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4735 // isn't running
4736 Thread::requestExitAndWait();
4737 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4738 if (res != OK) {
4739 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004740 if (listener != NULL) {
4741 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004742 }
4743 return res;
4744 }
4745 mCancelNow = false;
4746 mActive = true;
4747 ALOGV("%s: Preparer stream started", __FUNCTION__);
4748 }
4749
4750 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004751 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004752 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4753
4754 return OK;
4755}
4756
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004757void Camera3Device::PreparerThread::pause() {
4758 ATRACE_CALL();
4759
4760 Mutex::Autolock l(mLock);
4761
4762 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4763 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4764 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4765 int currentMaxCount = mCurrentMaxCount;
4766 mPendingStreams.clear();
4767 mCancelNow = true;
4768 while (mActive) {
4769 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4770 if (res == TIMED_OUT) {
4771 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4772 return;
4773 } else if (res != OK) {
4774 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4775 return;
4776 }
4777 }
4778
4779 //Check whether the prepare thread was able to complete the current
4780 //stream. In case work is still pending emplace it along with the rest
4781 //of the streams in the pending list.
4782 if (currentStream != nullptr) {
4783 if (!mCurrentPrepareComplete) {
4784 pendingStreams.emplace(currentMaxCount, currentStream);
4785 }
4786 }
4787
4788 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4789 for (const auto& it : mPendingStreams) {
4790 it.second->cancelPrepare();
4791 }
4792}
4793
4794status_t Camera3Device::PreparerThread::resume() {
4795 ATRACE_CALL();
4796 status_t res;
4797
4798 Mutex::Autolock l(mLock);
4799 sp<NotificationListener> listener = mListener.promote();
4800
4801 if (mActive) {
4802 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4803 return NO_INIT;
4804 }
4805
4806 auto it = mPendingStreams.begin();
4807 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004808 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004809 if (res == OK) {
4810 if (listener != NULL) {
4811 listener->notifyPrepared(it->second->getId());
4812 }
4813 it = mPendingStreams.erase(it);
4814 } else if (res != NOT_ENOUGH_DATA) {
4815 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4816 res, strerror(-res));
4817 it = mPendingStreams.erase(it);
4818 } else {
4819 it++;
4820 }
4821 }
4822
4823 if (mPendingStreams.empty()) {
4824 return OK;
4825 }
4826
4827 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4828 if (res != OK) {
4829 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4830 __FUNCTION__, res, strerror(-res));
4831 return res;
4832 }
4833 mCancelNow = false;
4834 mActive = true;
4835 ALOGV("%s: Preparer stream started", __FUNCTION__);
4836
4837 return OK;
4838}
4839
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004840status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004841 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004842 Mutex::Autolock l(mLock);
4843
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004844 for (const auto& it : mPendingStreams) {
4845 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004846 }
4847 mPendingStreams.clear();
4848 mCancelNow = true;
4849
4850 return OK;
4851}
4852
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004853void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004854 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004855 Mutex::Autolock l(mLock);
4856 mListener = listener;
4857}
4858
4859bool Camera3Device::PreparerThread::threadLoop() {
4860 status_t res;
4861 {
4862 Mutex::Autolock l(mLock);
4863 if (mCurrentStream == nullptr) {
4864 // End thread if done with work
4865 if (mPendingStreams.empty()) {
4866 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4867 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4868 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4869 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004870 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 return false;
4872 }
4873
4874 // Get next stream to prepare
4875 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004876 mCurrentStream = it->second;
4877 mCurrentMaxCount = it->first;
4878 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004879 mPendingStreams.erase(it);
4880 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4881 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4882 } else if (mCancelNow) {
4883 mCurrentStream->cancelPrepare();
4884 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4885 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4886 mCurrentStream.clear();
4887 mCancelNow = false;
4888 return true;
4889 }
4890 }
4891
4892 res = mCurrentStream->prepareNextBuffer();
4893 if (res == NOT_ENOUGH_DATA) return true;
4894 if (res != OK) {
4895 // Something bad happened; try to recover by cancelling prepare and
4896 // signalling listener anyway
4897 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4898 mCurrentStream->getId(), res, strerror(-res));
4899 mCurrentStream->cancelPrepare();
4900 }
4901
4902 // This stream has finished, notify listener
4903 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004904 sp<NotificationListener> listener = mListener.promote();
4905 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004906 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4907 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004908 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004909 }
4910
4911 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4912 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004913 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004914
4915 return true;
4916}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004917
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004918status_t Camera3Device::RequestBufferStateMachine::initialize(
4919 sp<camera3::StatusTracker> statusTracker) {
4920 if (statusTracker == nullptr) {
4921 ALOGE("%s: statusTracker is null", __FUNCTION__);
4922 return BAD_VALUE;
4923 }
4924
4925 std::lock_guard<std::mutex> lock(mLock);
4926 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004927 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004928 return OK;
4929}
4930
4931bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4932 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004933 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004934 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004935 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004936 return true;
4937 }
4938 return false;
4939}
4940
4941void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4942 std::lock_guard<std::mutex> lock(mLock);
4943 if (!mRequestBufferOngoing) {
4944 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4945 return;
4946 }
4947 mRequestBufferOngoing = false;
4948 if (mStatus == RB_STATUS_PENDING_STOP) {
4949 checkSwitchToStopLocked();
4950 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004951 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004952}
4953
4954void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4955 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004956 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004957 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004958 return;
4959}
4960
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004961void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004962 std::lock_guard<std::mutex> lock(mLock);
4963 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004964 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4965 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004966 mInflightMapEmpty = false;
4967 if (mStatus == RB_STATUS_STOPPED) {
4968 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004969 }
4970 return;
4971}
4972
4973void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4974 std::lock_guard<std::mutex> lock(mLock);
4975 mRequestThreadPaused = true;
4976 if (mStatus == RB_STATUS_PENDING_STOP) {
4977 checkSwitchToStopLocked();
4978 }
4979 return;
4980}
4981
4982void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4983 std::lock_guard<std::mutex> lock(mLock);
4984 mInflightMapEmpty = true;
4985 if (mStatus == RB_STATUS_PENDING_STOP) {
4986 checkSwitchToStopLocked();
4987 }
4988 return;
4989}
4990
4991void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4992 std::lock_guard<std::mutex> lock(mLock);
4993 if (!checkSwitchToStopLocked()) {
4994 mStatus = RB_STATUS_PENDING_STOP;
4995 }
4996 return;
4997}
4998
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004999bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5000 std::lock_guard<std::mutex> lock(mLock);
5001 if (mRequestBufferOngoing) {
5002 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5003 __FUNCTION__);
5004 return false;
5005 }
5006 mSwitchedToOffline = true;
5007 mInflightMapEmpty = true;
5008 mRequestThreadPaused = true;
5009 mStatus = RB_STATUS_STOPPED;
5010 return true;
5011}
5012
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005013void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5014 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5015 if (statusTracker != nullptr) {
5016 if (active) {
5017 statusTracker->markComponentActive(mRequestBufferStatusId);
5018 } else {
5019 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5020 }
5021 }
5022}
5023
5024bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5025 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5026 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005027 return true;
5028 }
5029 return false;
5030}
5031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005032bool Camera3Device::startRequestBuffer() {
5033 return mRequestBufferSM.startRequestBuffer();
5034}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005035
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005036void Camera3Device::endRequestBuffer() {
5037 mRequestBufferSM.endRequestBuffer();
5038}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005039
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005040nsecs_t Camera3Device::getWaitDuration() {
5041 return kBaseGetBufferWait + getExpectedInFlightDuration();
5042}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005043
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005044void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5045 mInterface->getInflightBufferKeys(out);
5046}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005047
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005048void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5049 mInterface->getInflightRequestBufferKeys(out);
5050}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005051
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005052std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5053 std::vector<sp<Camera3StreamInterface>> ret;
5054 bool hasInputStream = mInputStream != nullptr;
5055 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5056 if (hasInputStream) {
5057 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005058 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005059 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5060 ret.push_back(mOutputStreams[i]);
5061 }
5062 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5063 ret.push_back(mDeletedStreams[i]);
5064 }
5065 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005066}
5067
Emilian Peevcc0b7952020-01-07 13:54:47 -08005068void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5069 ATRACE_CALL();
5070
5071 if (offlineStreamIds == nullptr) {
5072 return;
5073 }
5074
5075 Mutex::Autolock il(mInterfaceLock);
5076
5077 auto streamIds = mOutputStreams.getStreamIds();
5078 bool hasInputStream = mInputStream != nullptr;
5079 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5080 offlineStreamIds->push_back(mInputStream->getId());
5081 }
5082
5083 for (const auto & streamId : streamIds) {
5084 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5085 // Streams that use the camera buffer manager are currently not supported in
5086 // offline mode
5087 if (stream->getOfflineProcessingSupport() &&
5088 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5089 offlineStreamIds->push_back(streamId);
5090 }
5091 }
5092}
5093
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005094status_t Camera3Device::setRotateAndCropAutoBehavior(
5095 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5096 ATRACE_CALL();
5097 Mutex::Autolock il(mInterfaceLock);
5098 Mutex::Autolock l(mLock);
5099 if (mRequestThread == nullptr) {
5100 return INVALID_OPERATION;
5101 }
5102 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5103}
5104
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005105bool Camera3Device::supportsCameraMute() {
5106 Mutex::Autolock il(mInterfaceLock);
5107 Mutex::Autolock l(mLock);
5108
5109 return mSupportCameraMute;
5110}
5111
5112status_t Camera3Device::setCameraMute(bool enabled) {
5113 ATRACE_CALL();
5114 Mutex::Autolock il(mInterfaceLock);
5115 Mutex::Autolock l(mLock);
5116
5117 if (mRequestThread == nullptr || !mSupportCameraMute) {
5118 return INVALID_OPERATION;
5119 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005120 int32_t muteMode =
5121 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5122 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5123 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5124 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005125}
5126
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005127status_t Camera3Device::injectCamera(const String8& injectedCamId,
5128 sp<CameraProviderManager> manager) {
5129 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5130 ATRACE_CALL();
5131 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005132 // When the camera device is active, injectCamera() and stopInjection() will call
5133 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5134 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5135 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5136 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5137 // waitUntilStateThenRelock().
5138 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005139
5140 status_t res = NO_ERROR;
5141 if (mInjectionMethods->isInjecting()) {
5142 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5143 return OK;
5144 } else {
5145 res = mInjectionMethods->stopInjection();
5146 if (res != OK) {
5147 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5148 __FUNCTION__, res);
5149 return res;
5150 }
5151 }
5152 }
5153
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005154 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005155 if (res != OK) {
5156 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5157 __FUNCTION__, res);
5158 return res;
5159 }
5160
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005161 // When the second display of android is cast to the remote device, and the opened camera is
5162 // also cast to the second display, in this case, because the camera has configured the streams
5163 // at this time, we can directly call injectCamera() to replace the internal camera with
5164 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005165 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5166 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5167
5168 camera3::camera_stream_configuration injectionConfig;
5169 std::vector<uint32_t> injectionBufferSizes;
5170 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5171 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5172 || injectionBufferSizes.size() <= 0) {
5173 ALOGE("Failed to inject camera due to abandoned configuration! "
5174 "mOperatingMode: %d injectionConfig.num_streams: %d "
5175 "injectionBufferSizes.size(): %zu", mOperatingMode,
5176 injectionConfig.num_streams, injectionBufferSizes.size());
5177 return DEAD_OBJECT;
5178 }
5179
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005180 res = mInjectionMethods->injectCamera(
5181 injectionConfig, injectionBufferSizes);
5182 if (res != OK) {
5183 ALOGE("Can't finish inject camera process!");
5184 return res;
5185 }
5186 }
5187
5188 return OK;
5189}
5190
5191status_t Camera3Device::stopInjection() {
5192 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5193 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005194 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005195 return mInjectionMethods->stopInjection();
5196}
5197
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005198}; // namespace android