blob: 37e41221e9d9627f5b9c197484a7ca5c6ac2a3ad [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080087 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080088 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070090 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070093 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000095 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010096 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070097 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070098 mNeedFixupMonochromeTags(false),
99 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
105Camera3Device::~Camera3Device()
106{
107 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700109 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800113 return mId;
114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116status_t Camera3Device::initializeCommonLocked() {
117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700118 /** Start up status tracker thread */
119 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700121 if (res != OK) {
122 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
123 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 mStatusTracker.clear();
126 return res;
127 }
128
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700129 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700130 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700132 if (mUseHalBufManager) {
133 res = mRequestBufferSM.initialize(mStatusTracker);
134 if (res != OK) {
135 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
136 strerror(-res), res);
137 mInterface->close();
138 mStatusTracker.clear();
139 return res;
140 }
141 }
142
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800143 /** Create buffer manager */
144 mBufferManager = new Camera3BufferManager();
145
146 Vector<int32_t> sessionParamKeys;
147 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
148 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
149 if (sessionKeysEntry.count > 0) {
150 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
151 }
152
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700153 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
154 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
155 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
156 if (availableTestPatternModes.data.i32[i] ==
157 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
158 mSupportCameraMute = true;
159 mSupportTestPatternSolidColor = true;
160 break;
161 } else if (availableTestPatternModes.data.i32[i] ==
162 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
163 mSupportCameraMute = true;
164 mSupportTestPatternSolidColor = false;
165 }
166 }
167
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700168 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800169 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700170 this, mStatusTracker, mInterface, sessionParamKeys,
171 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800173 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700174 SET_ERR_L("Unable to start request queue thread: %s (%d)",
175 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800177 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800178 return res;
179 }
180
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700181 mPreparerThread = new PreparerThread();
182
Ruben Brunk183f0562015-08-12 12:55:02 -0700183 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800184 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400185 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700186 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700187 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800188 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800190 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800191 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 camera_metadata_entry timestampSource =
193 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
194 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
195 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800196 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 }
198
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700199 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100200 camera_metadata_entry partialResultsCount =
201 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
202 if (partialResultsCount.count > 0) {
203 mNumPartialResults = partialResultsCount.data.i32[0];
204 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700205 }
206
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800207 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
208 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700209 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700210 if (res != OK) {
211 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
212 return res;
213 }
214 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800216 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700219 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
220 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
221 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
222 }
223
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800224 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
225 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
226 }
227
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800228 // Hidl/AidlCamera3DeviceInjectionMethods
229 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800230
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 return OK;
232}
233
234status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700235 return disconnectImpl();
236}
237
238status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700240 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800241
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700242 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700243 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800245 Mutex::Autolock il(mInterfaceLock);
246 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
247 {
248 Mutex::Autolock l(mLock);
249 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700250
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800251 if (mStatus == STATUS_ACTIVE ||
252 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
253 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 } else {
258 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
259 if (res != OK) {
260 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
261 maxExpectedDuration);
262 // Continue to close device even in case of error
263 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800266
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 if (mStatus == STATUS_ERROR) {
268 CLOGE("Shutting down in an error state");
269 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatusTracker != NULL) {
272 mStatusTracker->requestExit();
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mRequestThread != NULL) {
276 mRequestThread->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
280 for (size_t i = 0; i < mOutputStreams.size(); i++) {
281 streams.push_back(mOutputStreams[i]);
282 }
283 if (mInputStream != nullptr) {
284 streams.push_back(mInputStream);
285 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
289 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
291 // HAL may be in a bad state, so waiting for request thread
292 // (which may be stuck in the HAL processCaptureRequest call)
293 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 // give up mInterfaceLock here and then lock it again. Could this lead
295 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 mRequestThread->join();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 Mutex::Autolock il(mInterfaceLock);
300 if (mStatusTracker != NULL) {
301 mStatusTracker->join();
302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800304 if (mInjectionMethods->isInjecting()) {
305 mInjectionMethods->stopInjection();
306 }
307
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 HalInterface* interface;
309 {
310 Mutex::Autolock l(mLock);
311 mRequestThread.clear();
312 Mutex::Autolock stLock(mTrackerLock);
313 mStatusTracker.clear();
314 interface = mInterface.get();
315 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700316
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 // Call close without internal mutex held, as the HAL close may need to
318 // wait on assorted callbacks,etc, to complete before it can return.
319 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 {
324 Mutex::Autolock l(mLock);
325 mInterface->clear();
326 mOutputStreams.clear();
327 mInputStream.clear();
328 mDeletedStreams.clear();
329 mBufferManager.clear();
330 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
331 }
332
333 for (auto& weakStream : streams) {
334 sp<Camera3StreamInterface> stream = weakStream.promote();
335 if (stream != nullptr) {
336 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
337 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
338 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 }
340 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343}
344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345// For dumping/debugging only -
346// try to acquire a lock a few times, eventually give up to proceed with
347// debug/dump operations
348bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
349 bool gotLock = false;
350 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
351 if (lock.tryLock() == NO_ERROR) {
352 gotLock = true;
353 break;
354 } else {
355 usleep(kDumpSleepDuration);
356 }
357 }
358 return gotLock;
359}
360
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800361nsecs_t Camera3Device::getMonoToBoottimeOffset() {
362 // try three times to get the clock offset, choose the one
363 // with the minimum gap in measurements.
364 const int tries = 3;
365 nsecs_t bestGap, measured;
366 for (int i = 0; i < tries; ++i) {
367 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
369 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t gap = tmono2 - tmono;
371 if (i == 0 || gap < bestGap) {
372 bestGap = gap;
373 measured = tbase - ((tmono + tmono2) >> 1);
374 }
375 }
376 return measured;
377}
378
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800379ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
380 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700381 // Get max jpeg size (area-wise) for default sensor pixel mode
382 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800383 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700384 /*isUltraHighResolutionSensor*/false);
385 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
386 // not ultra high res sensor
387 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800388 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700389 /*isUltraHighResolution*/true);
390 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
392 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700393 return BAD_VALUE;
394 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700395 bool useMaxSensorPixelModeThreshold = false;
396 if (uhrMaxJpegResolution.width != 0 &&
397 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
398 // Use the ultra high res max jpeg size and max jpeg buffer size
399 useMaxSensorPixelModeThreshold = true;
400 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700401
Zhijun Hef7da0962014-04-24 13:27:56 -0700402 // Get max jpeg buffer size
403 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
407 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700408 return BAD_VALUE;
409 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700410 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411
412 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
413 if (useMaxSensorPixelModeThreshold) {
414 maxJpegBufferSize =
415 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
416 maxDefaultJpegResolution, maxJpegBufferSize);
417 chosenMaxJpegResolution = uhrMaxJpegResolution;
418 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800419 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700420
421 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700422 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800424 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
425 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700426 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800427 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
428 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 return jpegBufferSize;
432}
433
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700435 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800436 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700437 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800438 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
439 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700440 return BAD_VALUE;
441 }
442 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
443 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
444 return maxBytesForPointCloud;
445}
446
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800447ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
448 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800449 const int PER_CONFIGURATION_SIZE = 3;
450 const int WIDTH_OFFSET = 0;
451 const int HEIGHT_OFFSET = 1;
452 const int SIZE_OFFSET = 2;
453 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800454 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800455 camera3::SessionConfigurationUtils::getAppropriateModeTag(
456 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
457 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800458 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800460 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
461 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800462 return BAD_VALUE;
463 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800465 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
466 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
467 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
468 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
469 }
470 }
471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800472 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
473 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 return BAD_VALUE;
475}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700476
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800477status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
478 ATRACE_CALL();
479 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700480
481 // Try to lock, but continue in case of failure (to avoid blocking in
482 // deadlocks)
483 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
484 bool gotLock = tryLockSpinRightRound(mLock);
485
486 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
488 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700489 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
491 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700492
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800493 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700494
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800495 String16 templatesOption("-t");
496 int n = args.size();
497 for (int i = 0; i < n; i++) {
498 if (args[i] == templatesOption) {
499 dumpTemplates = true;
500 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000501 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700502 if (i + 1 < n) {
503 String8 monitorTags = String8(args[i + 1]);
504 if (monitorTags == "off") {
505 mTagMonitor.disableMonitoring();
506 } else {
507 mTagMonitor.parseTagsToMonitor(monitorTags);
508 }
509 } else {
510 mTagMonitor.disableMonitoring();
511 }
512 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800513 }
514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800515 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800517 const char *status =
518 mStatus == STATUS_ERROR ? "ERROR" :
519 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700520 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
521 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800522 mStatus == STATUS_ACTIVE ? "ACTIVE" :
523 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700526 if (mStatus == STATUS_ERROR) {
527 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800529 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800530 const char *mode =
531 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
532 mOperatingMode == static_cast<int>(
533 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
534 "CUSTOM";
535 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800536
537 if (mInputStream != NULL) {
538 write(fd, lines.string(), lines.size());
539 mInputStream->dump(fd, args);
540 } else {
541 lines.appendFormat(" No input stream.\n");
542 write(fd, lines.string(), lines.size());
543 }
544 for (size_t i = 0; i < mOutputStreams.size(); i++) {
545 mOutputStreams[i]->dump(fd,args);
546 }
547
Zhijun He431503c2016-03-07 17:30:16 -0800548 if (mBufferManager != NULL) {
549 lines = String8(" Camera3 Buffer Manager:\n");
550 write(fd, lines.string(), lines.size());
551 mBufferManager->dump(fd, args);
552 }
Zhijun He125684a2015-12-26 15:07:30 -0800553
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700554 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700555 if (mInFlightLock.try_lock()) {
556 if (mInFlightMap.size() == 0) {
557 lines.append(" None\n");
558 } else {
559 for (size_t i = 0; i < mInFlightMap.size(); i++) {
560 InFlightRequest r = mInFlightMap.valueAt(i);
561 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
562 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
563 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
564 r.numBuffersLeft);
565 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700566 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700567 mInFlightLock.unlock();
568 } else {
569 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700570 }
571 write(fd, lines.string(), lines.size());
572
Shuzhen Wang686f6442017-06-20 16:16:04 -0700573 if (mRequestThread != NULL) {
574 mRequestThread->dumpCaptureRequestLatency(fd,
575 " ProcessCaptureRequest latency histogram:");
576 }
577
Igor Murashkin1e479c02013-09-06 16:55:14 -0700578 {
579 lines = String8(" Last request sent:\n");
580 write(fd, lines.string(), lines.size());
581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700582 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700583 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
584 }
585
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700587 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800588 "TEMPLATE_PREVIEW",
589 "TEMPLATE_STILL_CAPTURE",
590 "TEMPLATE_VIDEO_RECORD",
591 "TEMPLATE_VIDEO_SNAPSHOT",
592 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800593 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800594 };
595
Emilian Peevf4816702020-04-03 15:44:51 -0700596 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 camera_metadata_t *templateRequest = nullptr;
598 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700599 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800601 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 lines.append(" Not supported\n");
603 write(fd, lines.string(), lines.size());
604 } else {
605 write(fd, lines.string(), lines.size());
606 dump_indented_camera_metadata(templateRequest,
607 fd, /*verbosity*/2, /*indentation*/8);
608 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 }
611 }
612
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700613 mTagMonitor.dumpMonitoredMetadata(fd);
614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800616 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800620
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700621 if (gotLock) mLock.unlock();
622 if (gotInterfaceLock) mInterfaceLock.unlock();
623
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800624 return OK;
625}
626
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700627status_t Camera3Device::startWatchingTags(const String8 &tags) {
628 mTagMonitor.parseTagsToMonitor(tags);
629 return OK;
630}
631
632status_t Camera3Device::stopWatchingTags() {
633 mTagMonitor.disableMonitoring();
634 return OK;
635}
636
637status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
638 mTagMonitor.getLatestMonitoredTagEvents(out);
639 return OK;
640}
641
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800642const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
645 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700646 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 mStatus == STATUS_ERROR ?
648 "when in error state" : "before init");
649 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700650 if (physicalId.isEmpty()) {
651 return mDeviceInfo;
652 } else {
653 std::string id(physicalId.c_str());
654 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
655 return mPhysicalDeviceInfoMap.at(id);
656 } else {
657 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
658 return mDeviceInfo;
659 }
660 }
661}
662
663const CameraMetadata& Camera3Device::info() const {
664 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666}
667
Jianing Wei90e59c92014-03-12 18:29:36 -0700668status_t Camera3Device::checkStatusOkToCaptureLocked() {
669 switch (mStatus) {
670 case STATUS_ERROR:
671 CLOGE("Device has encountered a serious error");
672 return INVALID_OPERATION;
673 case STATUS_UNINITIALIZED:
674 CLOGE("Device not initialized");
675 return INVALID_OPERATION;
676 case STATUS_UNCONFIGURED:
677 case STATUS_CONFIGURED:
678 case STATUS_ACTIVE:
679 // OK
680 break;
681 default:
682 SET_ERR_L("Unexpected status: %d", mStatus);
683 return INVALID_OPERATION;
684 }
685 return OK;
686}
687
688status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000689 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700690 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700691 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700692 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700693 if (requestList == NULL) {
694 CLOGE("requestList cannot be NULL.");
695 return BAD_VALUE;
696 }
697
Jianing Weicb0652e2014-03-12 18:29:36 -0700698 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
701 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
702 ++metadataIt, ++surfaceMapIt) {
703 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700704 if (newRequest == 0) {
705 CLOGE("Can't create capture request");
706 return BAD_VALUE;
707 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700708
Shuzhen Wang9d066012016-09-30 11:30:20 -0700709 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700710 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700711
Jianing Weicb0652e2014-03-12 18:29:36 -0700712 // Setup burst Id and request Id
713 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800714 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
715 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700716 CLOGE("RequestID does not exist in metadata");
717 return BAD_VALUE;
718 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800719 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700720
Jianing Wei90e59c92014-03-12 18:29:36 -0700721 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700722
723 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700724 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700725 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
726 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
727 return BAD_VALUE;
728 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700729
730 // Setup batch size if this is a high speed video recording request.
731 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
732 auto firstRequest = requestList->begin();
733 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
734 if (outputStream->isVideoStream()) {
735 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800736 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700737 break;
738 }
739 }
740 }
741
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 return OK;
743}
744
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800745status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800746 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800747
Emilian Peevaebbe412018-01-15 13:53:24 +0000748 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000750 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800752 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753}
754
Emilian Peevaebbe412018-01-15 13:53:24 +0000755void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 std::list<const SurfaceMap>& surfaceMaps,
757 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 PhysicalCameraSettingsList requestList;
759 requestList.push_back({std::string(getId().string()), request});
760 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
762 SurfaceMap surfaceMap;
763 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
764 // With no surface list passed in, stream and surface will have 1-to-1
765 // mapping. So the surface index is 0 for each stream in the surfaceMap.
766 for (size_t i = 0; i < streams.count; i++) {
767 surfaceMap[streams.data.i32[i]].push_back(0);
768 }
769 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770}
771
Jianing Wei90e59c92014-03-12 18:29:36 -0700772status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 const std::list<const SurfaceMap> &surfaceMaps,
775 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700776 /*out*/
777 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700779 nsecs_t requestTimeNs = systemTime();
780
Jianing Wei90e59c92014-03-12 18:29:36 -0700781 Mutex::Autolock il(mInterfaceLock);
782 Mutex::Autolock l(mLock);
783
784 status_t res = checkStatusOkToCaptureLocked();
785 if (res != OK) {
786 // error logged by previous call
787 return res;
788 }
789
790 RequestList requestList;
791
Shuzhen Wang0129d522016-10-30 22:43:41 -0700792 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700793 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700794 if (res != OK) {
795 // error logged by previous call
796 return res;
797 }
798
799 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700802 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 }
804
805 if (res == OK) {
806 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
807 if (res != OK) {
808 SET_ERR_L("Can't transition to active in %f seconds!",
809 kActiveTimeout/1e9);
810 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 } else {
814 CLOGE("Cannot queue request. Impossible.");
815 return BAD_VALUE;
816 }
817
818 return res;
819}
820
Emilian Peevaebbe412018-01-15 13:53:24 +0000821status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700823 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 ATRACE_CALL();
825
Emilian Peevaebbe412018-01-15 13:53:24 +0000826 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828
Jianing Weicb0652e2014-03-12 18:29:36 -0700829status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
830 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836
Emilian Peevaebbe412018-01-15 13:53:24 +0000837 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700838 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839}
840
Emilian Peevaebbe412018-01-15 13:53:24 +0000841status_t Camera3Device::setStreamingRequestList(
842 const List<const PhysicalCameraSettingsList> &requestsList,
843 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 ATRACE_CALL();
845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700847}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800848
849sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 status_t res;
852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700853 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800854 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
855 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700857 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700858 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700862 } else if (mStatus == STATUS_UNCONFIGURED) {
863 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700864 CLOGE("No streams configured");
865 return NULL;
866 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800867 }
868
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800870 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800871}
872
Jianing Weicb0652e2014-03-12 18:29:36 -0700873status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700875 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 switch (mStatus) {
879 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700880 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700883 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700891 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 return INVALID_OPERATION;
893 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700895
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897}
898
899status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
900 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700901 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700903 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904}
905
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700906status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800907 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700908 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700910 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700911 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800912 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
913 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700914
915 status_t res;
916 bool wasActive = false;
917
918 switch (mStatus) {
919 case STATUS_ERROR:
920 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
921 return INVALID_OPERATION;
922 case STATUS_UNINITIALIZED:
923 ALOGE("%s: Device not initialized", __FUNCTION__);
924 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 case STATUS_UNCONFIGURED:
926 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700927 // OK
928 break;
929 case STATUS_ACTIVE:
930 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700931 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 return res;
935 }
936 wasActive = true;
937 break;
938 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700940 return INVALID_OPERATION;
941 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700942 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700943
944 if (mInputStream != 0) {
945 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
946 return INVALID_OPERATION;
947 }
948
949 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
950 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700951 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952
953 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800954 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955
956 *id = mNextStreamId++;
957
958 // Continue captures if active at start
959 if (wasActive) {
960 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100961 // Reuse current operating mode and session parameters for new stream config
962 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 if (res != OK) {
964 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
965 __FUNCTION__, mNextStreamId, strerror(-res), res);
966 return res;
967 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700968 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700969 }
970
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700972 return OK;
973}
974
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700975status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700976 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700977 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800978 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800979 const std::unordered_set<int32_t> &sensorPixelModesUsed,
980 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800981 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800982 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 ATRACE_CALL();
984
985 if (consumer == nullptr) {
986 ALOGE("%s: consumer must not be null", __FUNCTION__);
987 return BAD_VALUE;
988 }
989
990 std::vector<sp<Surface>> consumers;
991 consumers.push_back(consumer);
992
993 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800994 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800995 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800996 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800997}
998
999static bool isRawFormat(int format) {
1000 switch (format) {
1001 case HAL_PIXEL_FORMAT_RAW16:
1002 case HAL_PIXEL_FORMAT_RAW12:
1003 case HAL_PIXEL_FORMAT_RAW10:
1004 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1005 return true;
1006 default:
1007 return false;
1008 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001009}
1010
1011status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1012 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001013 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001014 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001015 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001016 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1017 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001018 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001019
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001020 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001021 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001022 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001024 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001025 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1026 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001027 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001028 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001029 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001030
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001031 status_t res;
1032 bool wasActive = false;
1033
1034 switch (mStatus) {
1035 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001036 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001037 return INVALID_OPERATION;
1038 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001039 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001040 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001041 case STATUS_UNCONFIGURED:
1042 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001043 // OK
1044 break;
1045 case STATUS_ACTIVE:
1046 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001047 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001048 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001049 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 return res;
1051 }
1052 wasActive = true;
1053 break;
1054 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001055 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001056 return INVALID_OPERATION;
1057 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001058 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001059
1060 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001061
Shuzhen Wang0129d522016-10-30 22:43:41 -07001062 if (consumers.size() == 0 && !hasDeferredConsumer) {
1063 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1064 return BAD_VALUE;
1065 }
Zhijun He5d677d12016-05-29 16:52:39 -07001066
Shuzhen Wang0129d522016-10-30 22:43:41 -07001067 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001068 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1069 return BAD_VALUE;
1070 }
1071
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001072 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1073 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1074 // be found in only one sensor pixel mode.
1075 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1076 return BAD_VALUE;
1077 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001078 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001079 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001080 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001081 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001082 if (blobBufferSize <= 0) {
1083 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1084 return BAD_VALUE;
1085 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001086 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1087 blobBufferSize = width * height;
1088 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001089 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001090 if (blobBufferSize <= 0) {
1091 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1092 return BAD_VALUE;
1093 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001094 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001095 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001096 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001097 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001098 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001099 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001100 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001101 bool maxResolution =
1102 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1103 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001104 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1105 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001106 if (rawOpaqueBufferSize <= 0) {
1107 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1108 return BAD_VALUE;
1109 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001110 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001111 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001112 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001113 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001114 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001115 } else if (isShared) {
1116 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1117 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001118 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001119 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001120 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001121 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001122 newStream = new Camera3OutputStream(mNextStreamId,
1123 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001124 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001125 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001126 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001127 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001128 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001129 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001130 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001131 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001132 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001133 }
Emilian Peev40ead602017-09-26 15:46:36 +01001134
1135 size_t consumerCount = consumers.size();
1136 for (size_t i = 0; i < consumerCount; i++) {
1137 int id = newStream->getSurfaceId(consumers[i]);
1138 if (id < 0) {
1139 SET_ERR_L("Invalid surface id");
1140 return BAD_VALUE;
1141 }
1142 if (surfaceIds != nullptr) {
1143 surfaceIds->push_back(id);
1144 }
1145 }
1146
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001147 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148
Emilian Peev08dd2452017-04-06 16:55:14 +01001149 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001150
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001151 newStream->setImageDumpMask(mImageDumpMask);
1152
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153 res = mOutputStreams.add(mNextStreamId, newStream);
1154 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001155 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001156 return res;
1157 }
1158
Shuzhen Wang316781a2020-08-18 18:11:01 -07001159 mSessionStatsBuilder.addStream(mNextStreamId);
1160
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001161 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001162 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163
1164 // Continue captures if active at start
1165 if (wasActive) {
1166 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001167 // Reuse current operating mode and session parameters for new stream config
1168 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001169 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001170 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1171 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001172 return res;
1173 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001176 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001178}
1179
Emilian Peev710c1422017-08-30 11:19:38 +01001180status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001182 if (nullptr == streamInfo) {
1183 return BAD_VALUE;
1184 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001187
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188 switch (mStatus) {
1189 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001190 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 return INVALID_OPERATION;
1192 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001193 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001194 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 case STATUS_UNCONFIGURED:
1196 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 case STATUS_ACTIVE:
1198 // OK
1199 break;
1200 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001201 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return INVALID_OPERATION;
1203 }
1204
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001205 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1206 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001207 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001208 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 }
1210
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001211 streamInfo->width = stream->getWidth();
1212 streamInfo->height = stream->getHeight();
1213 streamInfo->format = stream->getFormat();
1214 streamInfo->dataSpace = stream->getDataSpace();
1215 streamInfo->formatOverridden = stream->isFormatOverridden();
1216 streamInfo->originalFormat = stream->getOriginalFormat();
1217 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1218 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001219 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221}
1222
1223status_t Camera3Device::setStreamTransform(int id,
1224 int transform) {
1225 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001228
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 switch (mStatus) {
1230 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
1233 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001234 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 case STATUS_UNCONFIGURED:
1237 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 case STATUS_ACTIVE:
1239 // OK
1240 break;
1241 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001242 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return INVALID_OPERATION;
1244 }
1245
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001246 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1247 if (stream == nullptr) {
1248 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 return BAD_VALUE;
1250 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001251 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252}
1253
1254status_t Camera3Device::deleteStream(int id) {
1255 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001256 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 Mutex::Autolock l(mLock);
1258 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001259
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001260 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001261
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 // CameraDevice semantics require device to already be idle before
1263 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001264 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001265 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001266 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 }
1268
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001269 if (mStatus == STATUS_ERROR) {
1270 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1271 __FUNCTION__, mId.string());
1272 return -EBUSY;
1273 }
1274
Igor Murashkin2fba5842013-04-22 14:03:54 -07001275 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001276 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 if (mInputStream != NULL && id == mInputStream->getId()) {
1278 deletedStream = mInputStream;
1279 mInputStream.clear();
1280 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001281 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001282 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 return BAD_VALUE;
1284 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001285 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001286 }
1287
1288 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001289 if (stream != nullptr) {
1290 deletedStream = stream;
1291 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 }
1293
1294 // Free up the stream endpoint so that it can be used by some other stream
1295 res = deletedStream->disconnect();
1296 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 // fall through since we want to still list the stream as deleted.
1299 }
1300 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001301 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302
1303 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001304}
1305
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001306status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001307 ATRACE_CALL();
1308 ALOGV("%s: E", __FUNCTION__);
1309
1310 Mutex::Autolock il(mInterfaceLock);
1311 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001312
Emilian Peev811d2952018-05-25 11:08:40 +01001313 // In case the client doesn't include any session parameter, try a
1314 // speculative configuration using the values from the last cached
1315 // default request.
1316 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001317 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001318 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1319 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1320 mLastTemplateId);
1321 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1322 operatingMode);
1323 }
1324
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001325 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1326}
1327
1328status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1329 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001330 //Filter out any incoming session parameters
1331 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001332 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1333 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001334 CameraMetadata filteredParams(availableSessionKeys.count);
1335 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1336 filteredParams.getAndLock());
1337 set_camera_metadata_vendor_id(meta, mVendorTagId);
1338 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001339 if (availableSessionKeys.count > 0) {
1340 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1341 camera_metadata_ro_entry entry = params.find(
1342 availableSessionKeys.data.i32[i]);
1343 if (entry.count > 0) {
1344 filteredParams.update(entry);
1345 }
1346 }
1347 }
1348
1349 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001350}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001351
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001352status_t Camera3Device::getInputBufferProducer(
1353 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001354 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001355 Mutex::Autolock il(mInterfaceLock);
1356 Mutex::Autolock l(mLock);
1357
1358 if (producer == NULL) {
1359 return BAD_VALUE;
1360 } else if (mInputStream == NULL) {
1361 return INVALID_OPERATION;
1362 }
1363
1364 return mInputStream->getInputBufferProducer(producer);
1365}
1366
Emilian Peevf4816702020-04-03 15:44:51 -07001367status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001368 CameraMetadata *request) {
1369 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001370 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001371
Emilian Peevf4816702020-04-03 15:44:51 -07001372 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001373 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001374 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001375 return BAD_VALUE;
1376 }
1377
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001380 {
1381 Mutex::Autolock l(mLock);
1382 switch (mStatus) {
1383 case STATUS_ERROR:
1384 CLOGE("Device has encountered a serious error");
1385 return INVALID_OPERATION;
1386 case STATUS_UNINITIALIZED:
1387 CLOGE("Device is not initialized!");
1388 return INVALID_OPERATION;
1389 case STATUS_UNCONFIGURED:
1390 case STATUS_CONFIGURED:
1391 case STATUS_ACTIVE:
1392 // OK
1393 break;
1394 default:
1395 SET_ERR_L("Unexpected status: %d", mStatus);
1396 return INVALID_OPERATION;
1397 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001398
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399 if (!mRequestTemplateCache[templateId].isEmpty()) {
1400 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001401 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001402 return OK;
1403 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001404 }
1405
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001406 camera_metadata_t *rawRequest;
1407 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001408 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001409
1410 {
1411 Mutex::Autolock l(mLock);
1412 if (res == BAD_VALUE) {
1413 ALOGI("%s: template %d is not supported on this camera device",
1414 __FUNCTION__, templateId);
1415 return res;
1416 } else if (res != OK) {
1417 CLOGE("Unable to construct request template %d: %s (%d)",
1418 templateId, strerror(-res), res);
1419 return res;
1420 }
1421
1422 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1423 mRequestTemplateCache[templateId].acquire(rawRequest);
1424
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001425 // Override the template request with zoomRatioMapper
1426 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1427 &mRequestTemplateCache[templateId]);
1428 if (res != OK) {
1429 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1430 templateId, strerror(-res), res);
1431 return res;
1432 }
1433
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001434 // Fill in JPEG_QUALITY if not available
1435 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1436 static const uint8_t kDefaultJpegQuality = 95;
1437 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1438 &kDefaultJpegQuality, 1);
1439 }
1440
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001441 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001442 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001443 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001444 return OK;
1445}
1446
1447status_t Camera3Device::waitUntilDrained() {
1448 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001450 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001452
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001453 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001454}
1455
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001456status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 switch (mStatus) {
1458 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001459 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 ALOGV("%s: Already idle", __FUNCTION__);
1461 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001462 case STATUS_CONFIGURED:
1463 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 case STATUS_ERROR:
1465 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001466 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 break;
1468 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001469 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 return INVALID_OPERATION;
1471 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001472 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1473 maxExpectedDuration);
1474 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001475 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001476 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001477 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1478 res);
1479 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001480 return res;
1481}
1482
Ruben Brunk183f0562015-08-12 12:55:02 -07001483void Camera3Device::internalUpdateStatusLocked(Status status) {
1484 mStatus = status;
1485 mRecentStatusUpdates.add(mStatus);
1486 mStatusChanged.broadcast();
1487}
1488
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001489// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001490status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001491 if (mRequestThread.get() != nullptr) {
1492 mRequestThread->setPaused(true);
1493 } else {
1494 return NO_INIT;
1495 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001497 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1498 maxExpectedDuration);
1499 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 if (res != OK) {
1501 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001502 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 }
1504
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 return res;
1506}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001508// Resume after internalPauseAndWaitLocked
1509status_t Camera3Device::internalResumeLocked() {
1510 status_t res;
1511
1512 mRequestThread->setPaused(false);
1513
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001514 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1515 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1517 if (res != OK) {
1518 SET_ERR_L("Can't transition to active in %f seconds!",
1519 kActiveTimeout/1e9);
1520 }
1521 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523}
1524
Ruben Brunk183f0562015-08-12 12:55:02 -07001525status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001527
1528 size_t startIndex = 0;
1529 if (mStatusWaiters == 0) {
1530 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1531 // this status list
1532 mRecentStatusUpdates.clear();
1533 } else {
1534 // If other threads are waiting on updates to this status list, set the position of the
1535 // first element that this list will check rather than clearing the list.
1536 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001537 }
1538
Ruben Brunk183f0562015-08-12 12:55:02 -07001539 mStatusWaiters++;
1540
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001541 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001542 if (!active && mUseHalBufManager) {
1543 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001544 if (mStatus == STATUS_ACTIVE) {
1545 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001546 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001547 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001548 mRequestBufferSM.onWaitUntilIdle();
1549 }
1550
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 bool stateSeen = false;
1552 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001553 if (active == (mStatus == STATUS_ACTIVE)) {
1554 // Desired state is current
1555 break;
1556 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001557
1558 res = mStatusChanged.waitRelative(mLock, timeout);
1559 if (res != OK) break;
1560
Ruben Brunk183f0562015-08-12 12:55:02 -07001561 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1562 // transitions.
1563 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1564 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1565 __FUNCTION__);
1566
1567 // Encountered desired state since we began waiting
1568 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1570 stateSeen = true;
1571 break;
1572 }
1573 }
1574 } while (!stateSeen);
1575
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001576 if (signalPipelineDrain) {
1577 mRequestThread->resetPipelineDrain();
1578 }
1579
Ruben Brunk183f0562015-08-12 12:55:02 -07001580 mStatusWaiters--;
1581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 return res;
1583}
1584
1585
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001586status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001588 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001589
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001590 if (listener != NULL && mListener != NULL) {
1591 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1592 }
1593 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001594 mRequestThread->setNotificationListener(listener);
1595 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001596
1597 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001598}
1599
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001600bool Camera3Device::willNotify3A() {
1601 return false;
1602}
1603
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001604status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001605 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001606 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001608 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001609 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1610 if (st == std::cv_status::timeout) {
1611 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001612 }
1613 }
1614 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001615}
1616
Jianing Weicb0652e2014-03-12 18:29:36 -07001617status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001618 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001619 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001620
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001621 if (mResultQueue.empty()) {
1622 return NOT_ENOUGH_DATA;
1623 }
1624
Jianing Weicb0652e2014-03-12 18:29:36 -07001625 if (frame == NULL) {
1626 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1627 return BAD_VALUE;
1628 }
1629
1630 CaptureResult &result = *(mResultQueue.begin());
1631 frame->mResultExtras = result.mResultExtras;
1632 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001633 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001634 mResultQueue.erase(mResultQueue.begin());
1635
1636 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001637}
1638
1639status_t Camera3Device::triggerAutofocus(uint32_t id) {
1640 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001643 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1644 // Mix-in this trigger into the next request and only the next request.
1645 RequestTrigger trigger[] = {
1646 {
1647 ANDROID_CONTROL_AF_TRIGGER,
1648 ANDROID_CONTROL_AF_TRIGGER_START
1649 },
1650 {
1651 ANDROID_CONTROL_AF_TRIGGER_ID,
1652 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001653 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001654 };
1655
1656 return mRequestThread->queueTrigger(trigger,
1657 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658}
1659
1660status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1661 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001662 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001663
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001664 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1665 // Mix-in this trigger into the next request and only the next request.
1666 RequestTrigger trigger[] = {
1667 {
1668 ANDROID_CONTROL_AF_TRIGGER,
1669 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1670 },
1671 {
1672 ANDROID_CONTROL_AF_TRIGGER_ID,
1673 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001674 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001675 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001677 return mRequestThread->queueTrigger(trigger,
1678 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001679}
1680
1681status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1682 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001684
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001685 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1686 // Mix-in this trigger into the next request and only the next request.
1687 RequestTrigger trigger[] = {
1688 {
1689 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1690 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1691 },
1692 {
1693 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1694 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001695 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001696 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001698 return mRequestThread->queueTrigger(trigger,
1699 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700}
1701
Jianing Weicb0652e2014-03-12 18:29:36 -07001702status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001703 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001704 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001705 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001706
Zhijun He7ef20392014-04-21 16:04:17 -07001707 {
1708 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001709
1710 // b/116514106 "disconnect()" can get called twice for the same device. The
1711 // camera device will not be initialized during the second run.
1712 if (mStatus == STATUS_UNINITIALIZED) {
1713 return OK;
1714 }
1715
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001716 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001717
1718 // Stop session and stream counter
1719 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001720 }
1721
Emilian Peev08dd2452017-04-06 16:55:14 +01001722 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001723}
1724
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001725status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001726 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1727}
1728
1729status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001730 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001731 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001732 Mutex::Autolock il(mInterfaceLock);
1733 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001734
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001735 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1736 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001737 CLOGE("Stream %d does not exist", streamId);
1738 return BAD_VALUE;
1739 }
1740
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001741 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001742 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001743 return BAD_VALUE;
1744 }
1745
1746 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001747 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001748 return BAD_VALUE;
1749 }
1750
Ruben Brunkc78ac262015-08-13 17:58:46 -07001751 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752}
1753
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001754status_t Camera3Device::tearDown(int streamId) {
1755 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001756 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001757 Mutex::Autolock il(mInterfaceLock);
1758 Mutex::Autolock l(mLock);
1759
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001760 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1761 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001762 CLOGE("Stream %d does not exist", streamId);
1763 return BAD_VALUE;
1764 }
1765
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001766 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1767 CLOGE("Stream %d is a target of a in-progress request", streamId);
1768 return BAD_VALUE;
1769 }
1770
1771 return stream->tearDown();
1772}
1773
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001774status_t Camera3Device::addBufferListenerForStream(int streamId,
1775 wp<Camera3StreamBufferListener> listener) {
1776 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001777 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001778 Mutex::Autolock il(mInterfaceLock);
1779 Mutex::Autolock l(mLock);
1780
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001781 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1782 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001783 CLOGE("Stream %d does not exist", streamId);
1784 return BAD_VALUE;
1785 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001786 stream->addBufferListener(listener);
1787
1788 return OK;
1789}
1790
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001792 * Methods called by subclasses
1793 */
1794
1795void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001796 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001797 std::vector<int> streamIds;
1798 std::vector<hardware::CameraStreamStats> streamStats;
1799
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 {
1801 // Need mLock to safely update state and synchronize to current
1802 // state of methods in flight.
1803 Mutex::Autolock l(mLock);
1804 // We can get various system-idle notices from the status tracker
1805 // while starting up. Only care about them if we've actually sent
1806 // in some requests recently.
1807 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1808 return;
1809 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001810 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1811 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001812 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813
1814 // Skip notifying listener if we're doing some user-transparent
1815 // state changes
1816 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001817
1818 // Populate stream statistics in case of Idle
1819 if (idle) {
1820 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1821 auto stream = mOutputStreams[i];
1822 if (stream.get() == nullptr) continue;
1823 streamIds.push_back(stream->getId());
1824 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1825 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001826 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001827 if (camera3Stream != nullptr) {
1828 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001829 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001830 }
1831 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1832 stream->getFormat(), stream->getDataSpace(), usage,
1833 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001834 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001835 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001836 }
1837 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001838 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001839
1840 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001841 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001842 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001843 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001845 status_t res = OK;
1846 if (listener != nullptr) {
1847 if (idle) {
1848 // Get session stats from the builder, and notify the listener.
1849 int64_t requestCount, resultErrorCount;
1850 bool deviceError;
1851 std::map<int, StreamStats> streamStatsMap;
1852 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1853 &deviceError, &streamStatsMap);
1854 for (size_t i = 0; i < streamIds.size(); i++) {
1855 int streamId = streamIds[i];
1856 auto stats = streamStatsMap.find(streamId);
1857 if (stats != streamStatsMap.end()) {
1858 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1859 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1860 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1861 streamStats[i].mHistogramType =
1862 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1863 streamStats[i].mHistogramBins.assign(
1864 stats->second.mCaptureLatencyBins.begin(),
1865 stats->second.mCaptureLatencyBins.end());
1866 streamStats[i].mHistogramCounts.assign(
1867 stats->second.mCaptureLatencyHistogram.begin(),
1868 stats->second.mCaptureLatencyHistogram.end());
1869 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001870 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001871 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1872 } else {
1873 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001874 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001875 }
1876 if (res != OK) {
1877 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1878 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001879 }
1880}
1881
Shuzhen Wang758c2152017-01-10 18:26:18 -08001882status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001883 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001884 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001885 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1886 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001887
1888 if (surfaceIds == nullptr) {
1889 return BAD_VALUE;
1890 }
1891
Zhijun He5d677d12016-05-29 16:52:39 -07001892 Mutex::Autolock il(mInterfaceLock);
1893 Mutex::Autolock l(mLock);
1894
Shuzhen Wang758c2152017-01-10 18:26:18 -08001895 if (consumers.size() == 0) {
1896 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001897 return BAD_VALUE;
1898 }
1899
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001900 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1901 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001902 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001903 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001904 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001905
1906 // isConsumerConfigurationDeferred will be off after setConsumers
1907 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001908 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001909 if (res != OK) {
1910 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1911 return res;
1912 }
1913
Emilian Peev40ead602017-09-26 15:46:36 +01001914 for (auto &consumer : consumers) {
1915 int id = stream->getSurfaceId(consumer);
1916 if (id < 0) {
1917 CLOGE("Invalid surface id!");
1918 return BAD_VALUE;
1919 }
1920 surfaceIds->push_back(id);
1921 }
1922
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001923 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001924 if (!stream->isConfiguring()) {
1925 CLOGE("Stream %d was already fully configured.", streamId);
1926 return INVALID_OPERATION;
1927 }
Zhijun He5d677d12016-05-29 16:52:39 -07001928
Shuzhen Wang0129d522016-10-30 22:43:41 -07001929 res = stream->finishConfiguration();
1930 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001931 // If finishConfiguration fails due to abandoned surface, do not set
1932 // device to error state.
1933 bool isSurfaceAbandoned =
1934 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1935 if (!isSurfaceAbandoned) {
1936 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1937 stream->getId(), strerror(-res), res);
1938 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001939 return res;
1940 }
Zhijun He5d677d12016-05-29 16:52:39 -07001941 }
1942
1943 return OK;
1944}
1945
Emilian Peev40ead602017-09-26 15:46:36 +01001946status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1947 const std::vector<OutputStreamInfo> &outputInfo,
1948 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1949 Mutex::Autolock il(mInterfaceLock);
1950 Mutex::Autolock l(mLock);
1951
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001952 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1953 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001954 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001955 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001956 }
1957
1958 for (const auto &it : removedSurfaceIds) {
1959 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1960 CLOGE("Shared surface still part of a pending request!");
1961 return -EBUSY;
1962 }
1963 }
1964
Emilian Peev40ead602017-09-26 15:46:36 +01001965 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1966 if (res != OK) {
1967 CLOGE("Stream %d failed to update stream (error %d %s) ",
1968 streamId, res, strerror(-res));
1969 if (res == UNKNOWN_ERROR) {
1970 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1971 __FUNCTION__);
1972 }
1973 return res;
1974 }
1975
1976 return res;
1977}
1978
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001979status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1980 Mutex::Autolock il(mInterfaceLock);
1981 Mutex::Autolock l(mLock);
1982
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001983 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1984 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001985 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1986 return BAD_VALUE;
1987 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001988
1989 if (dropping) {
1990 mSessionStatsBuilder.stopCounter(streamId);
1991 } else {
1992 mSessionStatsBuilder.startCounter(streamId);
1993 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001994 return stream->dropBuffers(dropping);
1995}
1996
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001997/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998 * Camera3Device private methods
1999 */
2000
2001sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002002 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002003 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002004
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002005 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002006 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002007
2008 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002009 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002010 if (inputStreams.count > 0) {
2011 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002012 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002013 CLOGE("Request references unknown input stream %d",
2014 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002015 return NULL;
2016 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002017
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002018 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002019 SET_ERR_L("%s: input stream %d is not configured!",
2020 __FUNCTION__, mInputStream->getId());
2021 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002023 // Check if stream prepare is blocking requests.
2024 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002025 CLOGE("Request references an input stream that's being prepared!");
2026 return NULL;
2027 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002028
2029 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002030 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002031 }
2032
2033 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002034 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002036 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037 return NULL;
2038 }
2039
2040 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002041 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2042 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002043 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002044 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002045 return NULL;
2046 }
Zhijun He5d677d12016-05-29 16:52:39 -07002047 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002048 auto iter = surfaceMap.find(streams.data.i32[i]);
2049 if (iter != surfaceMap.end()) {
2050 const std::vector<size_t>& surfaces = iter->second;
2051 for (const auto& surface : surfaces) {
2052 if (stream->isConsumerConfigurationDeferred(surface)) {
2053 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2054 "due to deferred consumer", stream->getId(), surface);
2055 return NULL;
2056 }
2057 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002058 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002059 }
2060
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002062 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2063 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002065 // Check if stream prepare is blocking requests.
2066 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002067 CLOGE("Request references an output stream that's being prepared!");
2068 return NULL;
2069 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002070
2071 newRequest->mOutputStreams.push(stream);
2072 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002073 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002074 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002076 auto rotateAndCropEntry =
2077 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2078 if (rotateAndCropEntry.count > 0 &&
2079 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2080 newRequest->mRotateAndCropAuto = true;
2081 } else {
2082 newRequest->mRotateAndCropAuto = false;
2083 }
2084
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002085 auto zoomRatioEntry =
2086 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2087 if (zoomRatioEntry.count > 0 &&
2088 zoomRatioEntry.data.f[0] == 1.0f) {
2089 newRequest->mZoomRatioIs1x = true;
2090 } else {
2091 newRequest->mZoomRatioIs1x = false;
2092 }
2093
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002094 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002095 for (auto& settings : newRequest->mSettingsList) {
2096 auto testPatternModeEntry =
2097 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2098 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2099 testPatternModeEntry.data.i32[0] :
2100 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002101
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002102 auto testPatternDataEntry =
2103 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2104 if (testPatternDataEntry.count >= 4) {
2105 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2106 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2107 } else {
2108 settings.mOriginalTestPatternData[0] = 0;
2109 settings.mOriginalTestPatternData[1] = 0;
2110 settings.mOriginalTestPatternData[2] = 0;
2111 settings.mOriginalTestPatternData[3] = 0;
2112 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002113 }
2114 }
2115
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002117}
2118
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002119void Camera3Device::cancelStreamsConfigurationLocked() {
2120 int res = OK;
2121 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2122 res = mInputStream->cancelConfiguration();
2123 if (res != OK) {
2124 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2125 mInputStream->getId(), strerror(-res), res);
2126 }
2127 }
2128
2129 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002130 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002131 if (outputStream->isConfiguring()) {
2132 res = outputStream->cancelConfiguration();
2133 if (res != OK) {
2134 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2135 outputStream->getId(), strerror(-res), res);
2136 }
2137 }
2138 }
2139
2140 // Return state to that at start of call, so that future configures
2141 // properly clean things up
2142 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2143 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002144
2145 res = mPreparerThread->resume();
2146 if (res != OK) {
2147 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2148 }
2149}
2150
Emilian Peev0d0191e2020-04-21 17:01:18 -07002151bool Camera3Device::checkAbandonedStreamsLocked() {
2152 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2153 return true;
2154 }
2155
2156 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2157 auto stream = mOutputStreams[i];
2158 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2159 return true;
2160 }
2161 }
2162
2163 return false;
2164}
2165
Emilian Peev3bead5f2020-05-28 17:29:08 -07002166bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002167 ATRACE_CALL();
2168 bool ret = false;
2169
Shuzhen Wang316781a2020-08-18 18:11:01 -07002170 nsecs_t startTime = systemTime();
2171
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002172 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002173 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2174
2175 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002176 if (checkAbandonedStreamsLocked()) {
2177 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2178 __FUNCTION__);
2179 return true;
2180 }
2181
Emilian Peev3bead5f2020-05-28 17:29:08 -07002182 status_t rc = NO_ERROR;
2183 bool markClientActive = false;
2184 if (mStatus == STATUS_ACTIVE) {
2185 markClientActive = true;
2186 mPauseStateNotify = true;
2187 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2188
2189 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2190 }
2191
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002192 if (rc == NO_ERROR) {
2193 mNeedConfig = true;
2194 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2195 if (rc == NO_ERROR) {
2196 ret = true;
2197 mPauseStateNotify = false;
2198 //Moving to active state while holding 'mLock' is important.
2199 //There could be pending calls to 'create-/deleteStream' which
2200 //will trigger another stream configuration while the already
2201 //present streams end up with outstanding buffers that will
2202 //not get drained.
2203 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002204 } else if (rc == DEAD_OBJECT) {
2205 // DEAD_OBJECT can be returned if either the consumer surface is
2206 // abandoned, or the HAL has died.
2207 // - If the HAL has died, configureStreamsLocked call will set
2208 // device to error state,
2209 // - If surface is abandoned, we should not set device to error
2210 // state.
2211 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002212 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002213 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002214 }
2215 } else {
2216 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2217 }
2218
Shuzhen Wang316781a2020-08-18 18:11:01 -07002219 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2220 ns2ms(systemTime() - startTime));
2221
Emilian Peev3bead5f2020-05-28 17:29:08 -07002222 if (markClientActive) {
2223 mStatusTracker->markComponentActive(clientStatusId);
2224 }
2225
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002226 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002227}
2228
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002229status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002230 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231 ATRACE_CALL();
2232 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002233
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002234 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002235 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002236 return INVALID_OPERATION;
2237 }
2238
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002239 if (operatingMode < 0) {
2240 CLOGE("Invalid operating mode: %d", operatingMode);
2241 return BAD_VALUE;
2242 }
2243
2244 bool isConstrainedHighSpeed =
2245 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2246 operatingMode;
2247
2248 if (mOperatingMode != operatingMode) {
2249 mNeedConfig = true;
2250 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2251 mOperatingMode = operatingMode;
2252 }
2253
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002254 // In case called from configureStreams, abort queued input buffers not belonging to
2255 // any pending requests.
2256 if (mInputStream != NULL && notifyRequestThread) {
2257 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002258 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002259 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002260 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002261 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002262 if (res != OK) {
2263 // Exhausted acquiring all input buffers.
2264 break;
2265 }
2266
Emilian Peevf4816702020-04-03 15:44:51 -07002267 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002268 res = mInputStream->returnInputBuffer(inputBuffer);
2269 if (res != OK) {
2270 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2271 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2272 }
2273 }
2274 }
2275
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002276 if (!mNeedConfig) {
2277 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2278 return OK;
2279 }
2280
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002281 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002282 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002283 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2284 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002285 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002286 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002287 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002288 }
2289
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002291 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002293 mPreparerThread->pause();
2294
Emilian Peevf4816702020-04-03 15:44:51 -07002295 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002296 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002298 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299
Emilian Peevf4816702020-04-03 15:44:51 -07002300 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002302 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304
2305 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002306 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 inputStream = mInputStream->startConfiguration();
2308 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002309 CLOGE("Can't start input stream configuration");
2310 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311 return INVALID_OPERATION;
2312 }
2313 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002314
2315 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 }
2317
Shuzhen Wang99080502021-03-07 21:08:20 -08002318 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002319 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002320 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002321
2322 // Don't configure bidi streams twice, nor add them twice to the list
2323 if (mOutputStreams[i].get() ==
2324 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2325
2326 config.num_streams--;
2327 continue;
2328 }
2329
Emilian Peevf4816702020-04-03 15:44:51 -07002330 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002331 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002332 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002333 CLOGE("Can't start output stream configuration");
2334 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002335 return INVALID_OPERATION;
2336 }
2337 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002338
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002339 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002340 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2341 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002342 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2343 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002344 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2345 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002346 } else if (outputStream->data_space ==
2347 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2348 bufferSizes[k] = outputStream->width * outputStream->height;
2349 } else {
2350 ALOGW("%s: Blob dataSpace %d not supported",
2351 __FUNCTION__, outputStream->data_space);
2352 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002353 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002354
2355 if (mOutputStreams[i]->isMultiResolution()) {
2356 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2357 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2358 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2359 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002360
2361 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2362 composerSurfacePresent = true;
2363 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364 }
2365
2366 config.streams = streams.editArray();
2367
2368 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002369 // max_buffers, usage, and priv fields, as well as data_space and format
2370 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002371
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002372 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002373 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002374 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002375
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002376 if (res == BAD_VALUE) {
2377 // HAL rejected this set of streams as unsupported, clean up config
2378 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002379 CLOGE("Set of requested inputs/outputs not supported by HAL");
2380 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002381 return BAD_VALUE;
2382 } else if (res != OK) {
2383 // Some other kind of error from configure_streams - this is not
2384 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002385 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2386 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002387 return res;
2388 }
2389
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002390 // Finish all stream configuration immediately.
2391 // TODO: Try to relax this later back to lazy completion, which should be
2392 // faster
2393
Igor Murashkin073f8572013-05-02 14:59:28 -07002394 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002395 bool streamReConfigured = false;
2396 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002397 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002398 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002399 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002400 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002401 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2402 return DEAD_OBJECT;
2403 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002404 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002405 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002406 if (streamReConfigured) {
2407 mInterface->onStreamReConfigured(mInputStream->getId());
2408 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002409 }
2410
2411 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002412 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002413 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002414 bool streamReConfigured = false;
2415 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002416 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002417 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002418 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002419 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002420 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2421 return DEAD_OBJECT;
2422 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002423 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002424 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002425 if (streamReConfigured) {
2426 mInterface->onStreamReConfigured(outputStream->getId());
2427 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002428 }
2429 }
2430
Emilian Peeve23f1d92021-09-20 14:56:01 -07002431 mRequestThread->setComposerSurface(composerSurfacePresent);
2432
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002433 // Request thread needs to know to avoid using repeat-last-settings protocol
2434 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002435 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002436 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2437 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002438 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002439
Zhijun He90f7c372016-08-16 16:19:43 -07002440 char value[PROPERTY_VALUE_MAX];
2441 property_get("camera.fifo.disable", value, "0");
2442 int32_t disableFifo = atoi(value);
2443 if (disableFifo != 1) {
2444 // Boost priority of request thread to SCHED_FIFO.
2445 pid_t requestThreadTid = mRequestThread->getTid();
2446 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002447 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002448 if (res != OK) {
2449 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2450 strerror(-res), res);
2451 } else {
2452 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2453 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002454 }
2455
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002456 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002457 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2458 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2459 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2460 sessionParams.unlock(newSessionParams);
2461 mSessionParams.unlock(currentSessionParams);
2462 if (updateSessionParams) {
2463 mSessionParams = sessionParams;
2464 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002465
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002466 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002468 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002469 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002470
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002471 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002472
Zhijun He0a210512014-07-24 13:45:15 -07002473 // tear down the deleted streams after configure streams.
2474 mDeletedStreams.clear();
2475
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002476 auto rc = mPreparerThread->resume();
2477 if (rc != OK) {
2478 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2479 return rc;
2480 }
2481
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002482 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002483 mRequestBufferSM.onStreamsConfigured();
2484 }
2485
Cliff Wu3b268182021-07-06 15:44:43 +08002486 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002487 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002488 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002489 // configure the injection streams.
2490 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002491 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002492 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2493 res = mInjectionMethods->injectCamera(config, bufferSizes);
2494 if (res != OK) {
2495 ALOGE("Can't finish inject camera process!");
2496 return res;
2497 }
Cliff Wu3b268182021-07-06 15:44:43 +08002498 } else {
2499 // First run configureStreamsLocked() and then call injectCamera() case:
2500 // If the stream configuration has been completed and camera deive is active, but the
2501 // injection camera has not been injected yet, we need to store the stream configuration of
2502 // the internal camera (because the stream configuration of the injection camera is based
2503 // on the internal camera). When injecting occurs later, this configuration can be used by
2504 // the injection camera.
2505 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2506 " injection camera has not been injected yet.", __FUNCTION__);
2507 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002508 }
2509
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002510 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002511}
2512
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002513status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002514 ATRACE_CALL();
2515 status_t res;
2516
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002517 if (mFakeStreamId != NO_STREAM) {
2518 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002519 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002520 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002521 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002522 return INVALID_OPERATION;
2523 }
2524
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002525 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002526
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002527 sp<Camera3OutputStreamInterface> fakeStream =
2528 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002529
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002530 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002531 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002532 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002533 return res;
2534 }
2535
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002536 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002537 mNextStreamId++;
2538
2539 return OK;
2540}
2541
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002542status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002543 ATRACE_CALL();
2544 status_t res;
2545
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002546 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002547 if (mOutputStreams.size() == 1) return OK;
2548
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002549 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002550
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 // Ok, have a fake stream and there's at least one other output stream,
2552 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002553
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002554 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002555 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002556 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002557 return INVALID_OPERATION;
2558 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002559 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002560
2561 // Free up the stream endpoint so that it can be used by some other stream
2562 res = deletedStream->disconnect();
2563 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002564 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002565 // fall through since we want to still list the stream as deleted.
2566 }
2567 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002568 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002569
2570 return res;
2571}
2572
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002573void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002574 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002575 Mutex::Autolock l(mLock);
2576 va_list args;
2577 va_start(args, fmt);
2578
2579 setErrorStateLockedV(fmt, args);
2580
2581 va_end(args);
2582}
2583
2584void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002585 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002586 Mutex::Autolock l(mLock);
2587 setErrorStateLockedV(fmt, args);
2588}
2589
2590void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2591 va_list args;
2592 va_start(args, fmt);
2593
2594 setErrorStateLockedV(fmt, args);
2595
2596 va_end(args);
2597}
2598
2599void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002600 // Print out all error messages to log
2601 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002602 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002603
2604 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002605 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002606
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002607 mErrorCause = errorCause;
2608
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002609 if (mRequestThread != nullptr) {
2610 mRequestThread->setPaused(true);
2611 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002612 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002613
2614 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002615 sp<NotificationListener> listener = mListener.promote();
2616 if (listener != NULL) {
2617 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002618 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002619 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002620 }
2621
2622 // Save stack trace. View by dumping it later.
2623 CameraTraces::saveTrace();
2624 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002625}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626
2627/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002628 * In-flight request management
2629 */
2630
Jianing Weicb0652e2014-03-12 18:29:36 -07002631status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002632 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002633 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002634 const std::set<std::set<String8>>& physicalCameraIds,
2635 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2636 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002637 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002638 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002639 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002640
2641 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002642 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002643 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002644 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002645 if (res < 0) return res;
2646
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002647 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002648 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2649 // avoid a deadlock during reprocess requests.
2650 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002651 if (mStatusTracker != nullptr) {
2652 mStatusTracker->markComponentActive(mInFlightStatusId);
2653 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002654 }
2655
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002656 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002657 return OK;
2658}
2659
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002660void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002661 // Indicate idle inFlightMap to the status tracker
2662 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002663 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002664 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2665 // avoid a deadlock during reprocess requests.
2666 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002667 if (mStatusTracker != nullptr) {
2668 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2669 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002670 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002671 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002672}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002673
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002674void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002675 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002676 // something has likely gone wrong. This might still be legit only if application send in
2677 // a long burst of long exposure requests.
2678 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2679 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2680 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2681 mInFlightMap.size(), mExpectedInflightDuration);
2682 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2683 kInFlightWarnLimitHighSpeed) {
2684 CLOGW("In-flight list too large for high speed configuration: %zu,"
2685 "total inflight duration %" PRIu64,
2686 mInFlightMap.size(), mExpectedInflightDuration);
2687 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002688 }
2689}
2690
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002691void Camera3Device::onInflightMapFlushedLocked() {
2692 mExpectedInflightDuration = 0;
2693}
2694
2695void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002696 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002697 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2698 mInFlightMap.removeItemsAt(idx, 1);
2699
2700 onInflightEntryRemovedLocked(duration);
2701}
2702
2703
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002704void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002705 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002706 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002707 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002708 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002709 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002710 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002711
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002712 FlushInflightReqStates states {
2713 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002714 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002715
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002716 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002717}
2718
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002719CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002720 ALOGV("%s", __FUNCTION__);
2721
Igor Murashkin1e479c02013-09-06 16:55:14 -07002722 CameraMetadata retVal;
2723
2724 if (mRequestThread != NULL) {
2725 retVal = mRequestThread->getLatestRequest();
2726 }
2727
Igor Murashkin1e479c02013-09-06 16:55:14 -07002728 return retVal;
2729}
2730
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002731void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002732 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002733 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002734 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2735 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002736
2737 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002738 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002739}
2740
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002741void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002742 std::vector<native_handle_t*> *handles, bool closeFd) {
2743 if (handles == nullptr) {
2744 return;
2745 }
2746 if (closeFd) {
2747 for (auto& handle : *handles) {
2748 native_handle_close(handle);
2749 }
2750 }
2751 for (auto& handle : *handles) {
2752 native_handle_delete(handle);
2753 }
2754 handles->clear();
2755 return;
2756}
2757
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002758/**
2759 * HalInterface inner class methods
2760 */
2761
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002762void Camera3Device::HalInterface::getInflightBufferKeys(
2763 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002764 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002765 return;
2766}
2767
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002768void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2769 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002770 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002771 return;
2772}
2773
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002774bool Camera3Device::HalInterface::verifyBufferIds(
2775 int32_t streamId, std::vector<uint64_t>& bufIds) {
2776 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002777}
2778
2779status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002780 int32_t frameNumber, int32_t streamId,
2781 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002782 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002783}
2784
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002785status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002786 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002787 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002788}
2789
2790// Find and pop a buffer_handle_t based on bufferId
2791status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002792 uint64_t bufferId,
2793 /*out*/ buffer_handle_t** buffer,
2794 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002795 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002796}
2797
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002798std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2799 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002801}
2802
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002803uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2804 const native_handle_t* handle) {
2805 return mBufferRecords.removeOneBufferCache(streamId, handle);
2806}
2807
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002808void Camera3Device::HalInterface::onBufferFreed(
2809 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002810 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2811 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2812 if (bufferId != BUFFER_ID_NO_BUFFER) {
2813 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002814 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002815}
2816
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002817void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002818 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2819 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2820 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002821 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2822 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002823}
2824
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002825/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002826 * RequestThread inner class methods
2827 */
2828
2829Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002830 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002831 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002832 bool useHalBufManager,
2833 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002834 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002835 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002836 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002837 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002838 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002839 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002840 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002841 mReconfigured(false),
2842 mDoPause(false),
2843 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002844 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002845 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002846 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002847 mCurrentAfTriggerId(0),
2848 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002849 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002850 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002851 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002852 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002853 mRepeatingLastFrameNumber(
2854 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002855 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002856 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002857 mRequestLatency(kRequestLatencyBinSize),
2858 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002859 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002860 mUseHalBufManager(useHalBufManager),
2861 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002862 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863}
2864
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002865Camera3Device::RequestThread::~RequestThread() {}
2866
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002867void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002868 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002869 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002870 Mutex::Autolock l(mRequestLock);
2871 mListener = listener;
2872}
2873
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002874void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002875 const CameraMetadata& sessionParams,
2876 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002877 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002878 Mutex::Autolock l(mRequestLock);
2879 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002880 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002881 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002882 // Prepare video stream for high speed recording.
2883 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002884 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002885}
2886
Jianing Wei90e59c92014-03-12 18:29:36 -07002887status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002888 List<sp<CaptureRequest> > &requests,
2889 /*out*/
2890 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002891 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002892 Mutex::Autolock l(mRequestLock);
2893 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2894 ++it) {
2895 mRequestQueue.push_back(*it);
2896 }
2897
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002898 if (lastFrameNumber != NULL) {
2899 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2900 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2901 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2902 *lastFrameNumber);
2903 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002904
Jianing Wei90e59c92014-03-12 18:29:36 -07002905 unpauseForNewRequests();
2906
2907 return OK;
2908}
2909
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002910
2911status_t Camera3Device::RequestThread::queueTrigger(
2912 RequestTrigger trigger[],
2913 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002914 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002915 Mutex::Autolock l(mTriggerMutex);
2916 status_t ret;
2917
2918 for (size_t i = 0; i < count; ++i) {
2919 ret = queueTriggerLocked(trigger[i]);
2920
2921 if (ret != OK) {
2922 return ret;
2923 }
2924 }
2925
2926 return OK;
2927}
2928
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002929const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2930 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002931 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002932 if (d != nullptr) return d->mId;
2933 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002934}
2935
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002936status_t Camera3Device::RequestThread::queueTriggerLocked(
2937 RequestTrigger trigger) {
2938
2939 uint32_t tag = trigger.metadataTag;
2940 ssize_t index = mTriggerMap.indexOfKey(tag);
2941
2942 switch (trigger.getTagType()) {
2943 case TYPE_BYTE:
2944 // fall-through
2945 case TYPE_INT32:
2946 break;
2947 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002948 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2949 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002950 return INVALID_OPERATION;
2951 }
2952
2953 /**
2954 * Collect only the latest trigger, since we only have 1 field
2955 * in the request settings per trigger tag, and can't send more than 1
2956 * trigger per request.
2957 */
2958 if (index != NAME_NOT_FOUND) {
2959 mTriggerMap.editValueAt(index) = trigger;
2960 } else {
2961 mTriggerMap.add(tag, trigger);
2962 }
2963
2964 return OK;
2965}
2966
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002967status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002968 const RequestList &requests,
2969 /*out*/
2970 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002971 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002972 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002973 if (lastFrameNumber != NULL) {
2974 *lastFrameNumber = mRepeatingLastFrameNumber;
2975 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002976 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002977 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2979 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002980
2981 unpauseForNewRequests();
2982
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002983 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002984 return OK;
2985}
2986
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002987bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002988 if (mRepeatingRequests.empty()) {
2989 return false;
2990 }
2991 int32_t requestId = requestIn->mResultExtras.requestId;
2992 const RequestList &repeatRequests = mRepeatingRequests;
2993 // All repeating requests are guaranteed to have same id so only check first quest
2994 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2995 return (firstRequest->mResultExtras.requestId == requestId);
2996}
2997
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002998status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002999 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003000 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003001 return clearRepeatingRequestsLocked(lastFrameNumber);
3002
3003}
3004
3005status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003006 std::vector<int32_t> streamIds;
3007 for (const auto& request : mRepeatingRequests) {
3008 for (const auto& stream : request->mOutputStreams) {
3009 streamIds.push_back(stream->getId());
3010 }
3011 }
3012
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003013 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003014 if (lastFrameNumber != NULL) {
3015 *lastFrameNumber = mRepeatingLastFrameNumber;
3016 }
Emilian Peev2295df72021-11-12 18:14:10 -08003017
3018 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3019
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003020 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003021 return OK;
3022}
3023
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003024status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003025 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003026 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003027 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003028 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003029
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003030 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003031
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003032 // Send errors for all requests pending in the request queue, including
3033 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003034 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003035 if (listener != NULL) {
3036 for (RequestList::iterator it = mRequestQueue.begin();
3037 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003038 // Abort the input buffers for reprocess requests.
3039 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003040 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003041 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003042 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003043 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003044 if (res != OK) {
3045 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3046 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3047 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003048 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003049 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3050 if (res != OK) {
3051 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3052 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3053 }
3054 }
3055 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003056 // Set the frame number this request would have had, if it
3057 // had been submitted; this frame number will not be reused.
3058 // The requestId and burstId fields were set when the request was
3059 // submitted originally (in convertMetadataListToRequestListLocked)
3060 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003061 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003062 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003063 }
3064 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003065 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003066
3067 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003068 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003069 if (lastFrameNumber != NULL) {
3070 *lastFrameNumber = mRepeatingLastFrameNumber;
3071 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003073 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003074 return OK;
3075}
3076
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003077status_t Camera3Device::RequestThread::flush() {
3078 ATRACE_CALL();
3079 Mutex::Autolock l(mFlushLock);
3080
Emilian Peev08dd2452017-04-06 16:55:14 +01003081 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003082}
3083
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003084void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003085 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003086 Mutex::Autolock l(mPauseLock);
3087 mDoPause = paused;
3088 mDoPauseSignal.signal();
3089}
3090
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003091status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3092 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003093 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003094 Mutex::Autolock l(mLatestRequestMutex);
3095 status_t res;
3096 while (mLatestRequestId != requestId) {
3097 nsecs_t startTime = systemTime();
3098
3099 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3100 if (res != OK) return res;
3101
3102 timeout -= (systemTime() - startTime);
3103 }
3104
3105 return OK;
3106}
3107
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003108void Camera3Device::RequestThread::requestExit() {
3109 // Call parent to set up shutdown
3110 Thread::requestExit();
3111 // The exit from any possible waits
3112 mDoPauseSignal.signal();
3113 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003114
3115 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3116 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003117}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003118
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003119void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003120 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003121 bool surfaceAbandoned = false;
3122 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003123 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003124 {
3125 Mutex::Autolock l(mRequestLock);
3126 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3127 // repeating requests.
3128 for (const auto& request : mRepeatingRequests) {
3129 for (const auto& s : request->mOutputStreams) {
3130 if (s->isAbandoned()) {
3131 surfaceAbandoned = true;
3132 clearRepeatingRequestsLocked(&lastFrameNumber);
3133 break;
3134 }
3135 }
3136 if (surfaceAbandoned) {
3137 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003138 }
3139 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003140 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003141 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003142
3143 if (listener != NULL && surfaceAbandoned) {
3144 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003145 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003146}
3147
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003148bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003149 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003150 status_t res;
3151 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003152 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003153 uint32_t numRequestProcessed = 0;
3154 for (size_t i = 0; i < batchSize; i++) {
3155 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003156 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003157 }
3158
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003159 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3160
3161 bool triggerRemoveFailed = false;
3162 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3163 for (size_t i = 0; i < numRequestProcessed; i++) {
3164 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3165 nextRequest.submitted = true;
3166
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003167 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003168
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003169 if (!triggerRemoveFailed) {
3170 // Remove any previously queued triggers (after unlock)
3171 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3172 if (removeTriggerRes != OK) {
3173 triggerRemoveFailed = true;
3174 triggerFailedRequest = nextRequest;
3175 }
3176 }
3177 }
3178
3179 if (triggerRemoveFailed) {
3180 SET_ERR("RequestThread: Unable to remove triggers "
3181 "(capture request %d, HAL device: %s (%d)",
3182 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3183 cleanUpFailedRequests(/*sendRequestError*/ false);
3184 return false;
3185 }
3186
3187 if (res != OK) {
3188 // Should only get a failure here for malformed requests or device-level
3189 // errors, so consider all errors fatal. Bad metadata failures should
3190 // come through notify.
3191 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3192 mNextRequests[numRequestProcessed].halRequest.frame_number,
3193 strerror(-res), res);
3194 cleanUpFailedRequests(/*sendRequestError*/ false);
3195 return false;
3196 }
3197 return true;
3198}
3199
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003200nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3201 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3202 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3203 find_camera_metadata_ro_entry(request,
3204 ANDROID_CONTROL_AE_MODE,
3205 &e);
3206 if (e.count == 0) return maxExpectedDuration;
3207
3208 switch (e.data.u8[0]) {
3209 case ANDROID_CONTROL_AE_MODE_OFF:
3210 find_camera_metadata_ro_entry(request,
3211 ANDROID_SENSOR_EXPOSURE_TIME,
3212 &e);
3213 if (e.count > 0) {
3214 maxExpectedDuration = e.data.i64[0];
3215 }
3216 find_camera_metadata_ro_entry(request,
3217 ANDROID_SENSOR_FRAME_DURATION,
3218 &e);
3219 if (e.count > 0) {
3220 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3221 }
3222 break;
3223 default:
3224 find_camera_metadata_ro_entry(request,
3225 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3226 &e);
3227 if (e.count > 1) {
3228 maxExpectedDuration = 1e9 / e.data.u8[0];
3229 }
3230 break;
3231 }
3232
3233 return maxExpectedDuration;
3234}
3235
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003236bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3237 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3238 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3239 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3240 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3241 return true;
3242 }
3243
3244 return false;
3245}
3246
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003247void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3248 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003249 camera_capture_request_t& halRequest = nextRequest.halRequest;
3250 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003251 Mutex::Autolock al(mLatestRequestMutex);
3252
Shuzhen Wang83bff122020-11-20 15:51:39 -08003253 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003254 mLatestRequest.acquire(cloned);
3255
3256 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003257 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3258 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3259 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003260 CameraMetadata(cloned));
3261 }
3262
3263 sp<Camera3Device> parent = mParent.promote();
3264 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003265 int32_t inputStreamId = -1;
3266 if (halRequest.input_buffer != nullptr) {
3267 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3268 }
3269
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003270 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003271 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003272 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3273 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003274 }
3275 }
3276
Shuzhen Wang83bff122020-11-20 15:51:39 -08003277 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003278 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003279 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003280 }
3281
Shuzhen Wang83bff122020-11-20 15:51:39 -08003282 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003283}
3284
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003285bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3286 ATRACE_CALL();
3287 bool updatesDetected = false;
3288
Emilian Peev4ec17882019-01-24 17:16:58 -08003289 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003290 for (auto tag : mSessionParamKeys) {
3291 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003292 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003293
3294 if (entry.count > 0) {
3295 bool isDifferent = false;
3296 if (lastEntry.count > 0) {
3297 // Have a last value, compare to see if changed
3298 if (lastEntry.type == entry.type &&
3299 lastEntry.count == entry.count) {
3300 // Same type and count, compare values
3301 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3302 size_t entryBytes = bytesPerValue * lastEntry.count;
3303 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3304 if (cmp != 0) {
3305 isDifferent = true;
3306 }
3307 } else {
3308 // Count or type has changed
3309 isDifferent = true;
3310 }
3311 } else {
3312 // No last entry, so always consider to be different
3313 isDifferent = true;
3314 }
3315
3316 if (isDifferent) {
3317 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003318 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3319 updatesDetected = true;
3320 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003321 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003322 }
3323 } else if (lastEntry.count > 0) {
3324 // Value has been removed
3325 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003326 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003327 updatesDetected = true;
3328 }
3329 }
3330
Emilian Peev4ec17882019-01-24 17:16:58 -08003331 bool reconfigureRequired;
3332 if (updatesDetected) {
3333 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3334 updatedParams);
3335 mLatestSessionParams = updatedParams;
3336 } else {
3337 reconfigureRequired = false;
3338 }
3339
3340 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003341}
3342
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003343bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003344 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003345 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003346 // Any function called from threadLoop() must not hold mInterfaceLock since
3347 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3348 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003349
3350 // Handle paused state.
3351 if (waitIfPaused()) {
3352 return true;
3353 }
3354
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003355 // Wait for the next batch of requests.
3356 waitForNextRequestBatch();
3357 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003358 return true;
3359 }
3360
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003361 // Get the latest request ID, if any
3362 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003363 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003364 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003365 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003366 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003367 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003368 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3369 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003370 }
3371
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003372 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3373 // or a single request from streaming or burst. In either case the first element
3374 // should contain the latest camera settings that we need to check for any session
3375 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003376 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003377 res = OK;
3378
3379 //Input stream buffers are already acquired at this point so an input stream
3380 //will not be able to move to idle state unless we force it.
3381 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3382 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3383 if (res != OK) {
3384 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3385 cleanUpFailedRequests(/*sendRequestError*/ false);
3386 return false;
3387 }
3388 }
3389
3390 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003391 sp<Camera3Device> parent = mParent.promote();
3392 if (parent != nullptr) {
3393 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003394 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003395 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003396
3397 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3398 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3399 if (res != OK) {
3400 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3401 cleanUpFailedRequests(/*sendRequestError*/ false);
3402 return false;
3403 }
3404 }
3405 }
3406 }
3407
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003408 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003409 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003410 if (res == TIMED_OUT) {
3411 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003412 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003413 // Check if any stream is abandoned.
3414 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003415 return true;
3416 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003417 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003418 return false;
3419 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003420
Zhijun Hecc27e112013-10-03 16:12:43 -07003421 // Inform waitUntilRequestProcessed thread of a new request ID
3422 {
3423 Mutex::Autolock al(mLatestRequestMutex);
3424
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003425 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003426 mLatestRequestSignal.signal();
3427 }
3428
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003429 // Submit a batch of requests to HAL.
3430 // Use flush lock only when submitting multilple requests in a batch.
3431 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3432 // which may take a long time to finish so synchronizing flush() and
3433 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3434 // For now, only synchronize for high speed recording and we should figure something out for
3435 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003436 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003437
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003438 if (useFlushLock) {
3439 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003440 }
3441
Zhijun Hef0645c12016-08-02 00:58:11 -07003442 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003443 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003444
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003445 sp<Camera3Device> parent = mParent.promote();
3446 if (parent != nullptr) {
3447 parent->mRequestBufferSM.onSubmittingRequest();
3448 }
3449
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003450 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003451 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003452 submitRequestSuccess = sendRequestsBatch();
3453
Shuzhen Wang686f6442017-06-20 16:16:04 -07003454 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3455 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003456
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003457 if (useFlushLock) {
3458 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003459 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003460
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003461 // Unset as current request
3462 {
3463 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003464 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003465 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003466 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003467
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003468 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003469}
3470
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003471status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3472 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3473 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3474 ANDROID_SCALER_CROP_REGION_SET};
3475 if (request == nullptr) {
3476 ALOGE("%s request metadata nullptr", __FUNCTION__);
3477 return BAD_VALUE;
3478 }
3479 status_t res = OK;
3480 for (const auto &key : kFwkOnlyRegionKeys) {
3481 if (request->exists(key)) {
3482 res = request->erase(key);
3483 if (res != OK) {
3484 return res;
3485 }
3486 }
3487 }
3488 return OK;
3489}
3490
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003491status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003492 ATRACE_CALL();
3493
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003494 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003495 for (size_t i = 0; i < mNextRequests.size(); i++) {
3496 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003497 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003498 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3499 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003500
3501 // Prepare a request to HAL
3502 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3503
3504 // Insert any queued triggers (before metadata is locked)
3505 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003506 if (res < 0) {
3507 SET_ERR("RequestThread: Unable to insert triggers "
3508 "(capture request %d, HAL device: %s (%d)",
3509 halRequest->frame_number, strerror(-res), res);
3510 return INVALID_OPERATION;
3511 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003513 int triggerCount = res;
3514 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3515 mPrevTriggers = triggerCount;
3516
Emilian Peeve23f1d92021-09-20 14:56:01 -07003517 // Do not override rotate&crop for stream configurations that include
3518 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3519 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3520 bool rotateAndCropChanged = mComposerOutput ? false :
3521 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003522 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003523
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003524 // If the request is the same as last, or we had triggers now or last time or
3525 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003526 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003527 (mPrevRequest != captureRequest || triggersMixedIn ||
3528 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003529 // Request settings are all the same within one batch, so only treat the first
3530 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003531 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003532 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003533 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003534 /**
3535 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003536 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003537 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003538 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003539 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003540 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003541 "(capture request %d, HAL device: %s (%d)",
3542 halRequest->frame_number, strerror(-res), res);
3543 return INVALID_OPERATION;
3544 }
3545
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003546 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003547 sp<Camera3Device> parent = mParent.promote();
3548 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003549 List<PhysicalCameraSettings>::iterator it;
3550 for (it = captureRequest->mSettingsList.begin();
3551 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003552 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3553 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003554 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3555 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3556 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3557 res);
3558 return INVALID_OPERATION;
3559 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003560 continue;
3561 }
3562
3563 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3564 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3565 updateCaptureRequest(&(it->metadata));
3566 if (res != OK) {
3567 SET_ERR("RequestThread: Unable to correct capture requests "
3568 "for scaler crop region and metering regions for request "
3569 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3570 res);
3571 return INVALID_OPERATION;
3572 }
3573 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003574 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3575 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3576 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3577 res);
3578 return INVALID_OPERATION;
3579 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003580 }
3581 }
3582
3583 // Correct metadata regions for distortion correction if enabled
3584 for (it = captureRequest->mSettingsList.begin();
3585 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003586 if (parent->mDistortionMappers.find(it->cameraId) ==
3587 parent->mDistortionMappers.end()) {
3588 continue;
3589 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003590
3591 if (!captureRequest->mDistortionCorrectionUpdated) {
3592 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3593 &(it->metadata));
3594 if (res != OK) {
3595 SET_ERR("RequestThread: Unable to correct capture requests "
3596 "for lens distortion for request %d: %s (%d)",
3597 halRequest->frame_number, strerror(-res), res);
3598 return INVALID_OPERATION;
3599 }
3600 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003601 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003602 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003603
3604 for (it = captureRequest->mSettingsList.begin();
3605 it != captureRequest->mSettingsList.end(); it++) {
3606 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3607 parent->mZoomRatioMappers.end()) {
3608 continue;
3609 }
3610
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003611 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003612 cameraIdsWithZoom.insert(it->cameraId);
3613 }
3614
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003615 if (!captureRequest->mZoomRatioUpdated) {
3616 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3617 &(it->metadata));
3618 if (res != OK) {
3619 SET_ERR("RequestThread: Unable to correct capture requests "
3620 "for zoom ratio for request %d: %s (%d)",
3621 halRequest->frame_number, strerror(-res), res);
3622 return INVALID_OPERATION;
3623 }
3624 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003625 }
3626 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003627 if (captureRequest->mRotateAndCropAuto &&
3628 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003629 for (it = captureRequest->mSettingsList.begin();
3630 it != captureRequest->mSettingsList.end(); it++) {
3631 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3632 if (mapper != parent->mRotateAndCropMappers.end()) {
3633 res = mapper->second.updateCaptureRequest(&(it->metadata));
3634 if (res != OK) {
3635 SET_ERR("RequestThread: Unable to correct capture requests "
3636 "for rotate-and-crop for request %d: %s (%d)",
3637 halRequest->frame_number, strerror(-res), res);
3638 return INVALID_OPERATION;
3639 }
3640 }
3641 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003642 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003643 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003644 }
3645 }
3646
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003647 /**
3648 * The request should be presorted so accesses in HAL
3649 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3650 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003651 captureRequest->mSettingsList.begin()->metadata.sort();
3652 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003653 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003654 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003655 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3656
3657 IF_ALOGV() {
3658 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3659 find_camera_metadata_ro_entry(
3660 halRequest->settings,
3661 ANDROID_CONTROL_AF_TRIGGER,
3662 &e
3663 );
3664 if (e.count > 0) {
3665 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3666 __FUNCTION__,
3667 halRequest->frame_number,
3668 e.data.u8[0]);
3669 }
3670 }
3671 } else {
3672 // leave request.settings NULL to indicate 'reuse latest given'
3673 ALOGVV("%s: Request settings are REUSED",
3674 __FUNCTION__);
3675 }
3676
Emilian Peevaebbe412018-01-15 13:53:24 +00003677 if (captureRequest->mSettingsList.size() > 1) {
3678 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3679 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003680 if (newRequest) {
3681 halRequest->physcam_settings =
3682 new const camera_metadata* [halRequest->num_physcam_settings];
3683 } else {
3684 halRequest->physcam_settings = nullptr;
3685 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003686 auto it = ++captureRequest->mSettingsList.begin();
3687 size_t i = 0;
3688 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3689 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003690 if (newRequest) {
3691 it->metadata.sort();
3692 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3693 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003694 }
3695 }
3696
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003697 uint32_t totalNumBuffers = 0;
3698
3699 // Fill in buffers
3700 if (captureRequest->mInputStream != NULL) {
3701 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003702
3703 halRequest->input_width = captureRequest->mInputBufferSize.width;
3704 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003705 totalNumBuffers += 1;
3706 } else {
3707 halRequest->input_buffer = NULL;
3708 }
3709
Emilian Peevf4816702020-04-03 15:44:51 -07003710 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003711 captureRequest->mOutputStreams.size());
3712 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003713 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003714
3715 sp<Camera3Device> parent = mParent.promote();
3716 if (parent == NULL) {
3717 // Should not happen, and nowhere to send errors to, so just log it
3718 CLOGE("RequestThread: Parent is gone");
3719 return INVALID_OPERATION;
3720 }
3721 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3722
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003723 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003724 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003725 sp<Camera3OutputStreamInterface> outputStream =
3726 captureRequest->mOutputStreams.editItemAt(j);
3727 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003728
3729 // Prepare video buffers for high speed recording on the first video request.
3730 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3731 // Only try to prepare video stream on the first video request.
3732 mPrepareVideoStream = false;
3733
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003734 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3735 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003736 while (res == NOT_ENOUGH_DATA) {
3737 res = outputStream->prepareNextBuffer();
3738 }
3739 if (res != OK) {
3740 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3741 __FUNCTION__, strerror(-res), res);
3742 outputStream->cancelPrepare();
3743 }
3744 }
3745
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003746 std::vector<size_t> uniqueSurfaceIds;
3747 res = outputStream->getUniqueSurfaceIds(
3748 captureRequest->mOutputSurfaces[streamId],
3749 &uniqueSurfaceIds);
3750 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3751 if (res != OK && res != INVALID_OPERATION) {
3752 ALOGE("%s: failed to query stream %d unique surface IDs",
3753 __FUNCTION__, streamId);
3754 return res;
3755 }
3756 if (res == OK) {
3757 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3758 }
3759
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003760 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003761 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003762 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003763 return TIMED_OUT;
3764 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003765 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003766 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003767 buffer.stream = outputStream->asHalStream();
3768 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003769 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003770 buffer.acquire_fence = -1;
3771 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003772 // Mark the output stream as unpreparable to block clients from calling
3773 // 'prepare' after this request reaches CameraHal and before the respective
3774 // buffers are requested.
3775 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003776 } else {
3777 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3778 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003779 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003780 if (res != OK) {
3781 // Can't get output buffer from gralloc queue - this could be due to
3782 // abandoned queue or other consumer misbehavior, so not a fatal
3783 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003784 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003785 " %s (%d)", strerror(-res), res);
3786
3787 return TIMED_OUT;
3788 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003789 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003790
3791 {
3792 sp<Camera3Device> parent = mParent.promote();
3793 if (parent != nullptr) {
3794 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3795 for (const auto& settings : captureRequest->mSettingsList) {
3796 if ((streamCameraId.isEmpty() &&
3797 parent->getId() == settings.cameraId.c_str()) ||
3798 streamCameraId == settings.cameraId.c_str()) {
3799 outputStream->fireBufferRequestForFrameNumber(
3800 captureRequest->mResultExtras.frameNumber,
3801 settings.metadata);
3802 }
3803 }
3804 }
3805 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003806
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003807 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003808 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3809 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3810 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3811 } else if (!physicalCameraId.isEmpty()) {
3812 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003813 }
3814 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003815 }
3816 totalNumBuffers += halRequest->num_output_buffers;
3817
3818 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003819 // If this request list is for constrained high speed recording (not
3820 // preview), and the current request is not the last one in the batch,
3821 // do not send callback to the app.
3822 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003823 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003824 hasCallback = false;
3825 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003826 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003827 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003828 const camera_metadata_t* settings = halRequest->settings;
3829 bool shouldUnlockSettings = false;
3830 if (settings == nullptr) {
3831 shouldUnlockSettings = true;
3832 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3833 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003834 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3835 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003836 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003837 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3838 isStillCapture = true;
3839 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3840 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003841
Emilian Peevaf8416e2021-02-04 17:52:43 -08003842 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003843 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003844 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3845 isZslCapture = true;
3846 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003847 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003848 res = parent->registerInFlight(halRequest->frame_number,
3849 totalNumBuffers, captureRequest->mResultExtras,
3850 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003851 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003852 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003853 requestedPhysicalCameras, isStillCapture, isZslCapture,
3854 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003855 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003856 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003857 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3858 ", burstId = %" PRId32 ".",
3859 __FUNCTION__,
3860 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3861 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003862
3863 if (shouldUnlockSettings) {
3864 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3865 }
3866
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003867 if (res != OK) {
3868 SET_ERR("RequestThread: Unable to register new in-flight request:"
3869 " %s (%d)", strerror(-res), res);
3870 return INVALID_OPERATION;
3871 }
3872 }
3873
3874 return OK;
3875}
3876
Igor Murashkin1e479c02013-09-06 16:55:14 -07003877CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003878 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003879 Mutex::Autolock al(mLatestRequestMutex);
3880
3881 ALOGV("RequestThread::%s", __FUNCTION__);
3882
3883 return mLatestRequest;
3884}
3885
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003886bool Camera3Device::RequestThread::isStreamPending(
3887 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003888 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003889 Mutex::Autolock l(mRequestLock);
3890
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003892 if (!nextRequest.submitted) {
3893 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3894 if (stream == s) return true;
3895 }
3896 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003897 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003898 }
3899
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003900 for (const auto& request : mRequestQueue) {
3901 for (const auto& s : request->mOutputStreams) {
3902 if (stream == s) return true;
3903 }
3904 if (stream == request->mInputStream) return true;
3905 }
3906
3907 for (const auto& request : mRepeatingRequests) {
3908 for (const auto& s : request->mOutputStreams) {
3909 if (stream == s) return true;
3910 }
3911 if (stream == request->mInputStream) return true;
3912 }
3913
3914 return false;
3915}
Jianing Weicb0652e2014-03-12 18:29:36 -07003916
Emilian Peev40ead602017-09-26 15:46:36 +01003917bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3918 ATRACE_CALL();
3919 Mutex::Autolock l(mRequestLock);
3920
3921 for (const auto& nextRequest : mNextRequests) {
3922 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3923 if (s.first == streamId) {
3924 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3925 if (it != s.second.end()) {
3926 return true;
3927 }
3928 }
3929 }
3930 }
3931
3932 for (const auto& request : mRequestQueue) {
3933 for (const auto& s : request->mOutputSurfaces) {
3934 if (s.first == streamId) {
3935 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3936 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003937 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003938 }
3939 }
3940 }
3941 }
3942
3943 for (const auto& request : mRepeatingRequests) {
3944 for (const auto& s : request->mOutputSurfaces) {
3945 if (s.first == streamId) {
3946 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3947 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003948 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003949 }
3950 }
3951 }
3952 }
3953
3954 return false;
3955}
3956
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003957void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3958 if (!mUseHalBufManager) {
3959 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3960 return;
3961 }
3962
3963 Mutex::Autolock pl(mPauseLock);
3964 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003965 mInterface->signalPipelineDrain(streamIds);
3966 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003967 }
3968 // If request thread is still busy, wait until paused then notify HAL
3969 mNotifyPipelineDrain = true;
3970 mStreamIdsToBeDrained = streamIds;
3971}
3972
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003973void Camera3Device::RequestThread::resetPipelineDrain() {
3974 Mutex::Autolock pl(mPauseLock);
3975 mNotifyPipelineDrain = false;
3976 mStreamIdsToBeDrained.clear();
3977}
3978
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003979void Camera3Device::RequestThread::clearPreviousRequest() {
3980 Mutex::Autolock l(mRequestLock);
3981 mPrevRequest.clear();
3982}
3983
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003984status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3985 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3986 ATRACE_CALL();
3987 Mutex::Autolock l(mTriggerMutex);
3988 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3989 return BAD_VALUE;
3990 }
3991 mRotateAndCropOverride = rotateAndCropValue;
3992 return OK;
3993}
3994
Emilian Peeve23f1d92021-09-20 14:56:01 -07003995status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3996 ATRACE_CALL();
3997 Mutex::Autolock l(mTriggerMutex);
3998 mComposerOutput = composerSurfacePresent;
3999 return OK;
4000}
4001
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004002status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004003 ATRACE_CALL();
4004 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004005 if (muteMode != mCameraMute) {
4006 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004007 mCameraMuteChanged = true;
4008 }
4009 return OK;
4010}
4011
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004012nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004013 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004014 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004015 return mExpectedInflightDuration > kMinInflightDuration ?
4016 mExpectedInflightDuration : kMinInflightDuration;
4017}
4018
Emilian Peevaebbe412018-01-15 13:53:24 +00004019void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004020 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004021 if ((request == nullptr) || (halRequest == nullptr)) {
4022 ALOGE("%s: Invalid request!", __FUNCTION__);
4023 return;
4024 }
4025
4026 if (halRequest->num_physcam_settings > 0) {
4027 if (halRequest->physcam_id != nullptr) {
4028 delete [] halRequest->physcam_id;
4029 halRequest->physcam_id = nullptr;
4030 }
4031 if (halRequest->physcam_settings != nullptr) {
4032 auto it = ++(request->mSettingsList.begin());
4033 size_t i = 0;
4034 for (; it != request->mSettingsList.end(); it++, i++) {
4035 it->metadata.unlock(halRequest->physcam_settings[i]);
4036 }
4037 delete [] halRequest->physcam_settings;
4038 halRequest->physcam_settings = nullptr;
4039 }
4040 }
4041}
4042
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004043void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4044 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004045 return;
4046 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004047
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004048 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004049 // Skip the ones that have been submitted successfully.
4050 if (nextRequest.submitted) {
4051 continue;
4052 }
4053
4054 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004055 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4056 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004057
4058 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004059 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004060 }
4061
Emilian Peevaebbe412018-01-15 13:53:24 +00004062 cleanupPhysicalSettings(captureRequest, halRequest);
4063
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004064 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004065 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004066 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4067 }
4068
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004069 // No output buffer can be returned when using HAL buffer manager
4070 if (!mUseHalBufManager) {
4071 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4072 //Buffers that failed processing could still have
4073 //valid acquire fence.
4074 int acquireFence = (*outputBuffers)[i].acquire_fence;
4075 if (0 <= acquireFence) {
4076 close(acquireFence);
4077 outputBuffers->editItemAt(i).acquire_fence = -1;
4078 }
Emilian Peevf4816702020-04-03 15:44:51 -07004079 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004080 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4081 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004082 /*timestampIncreasing*/true, std::vector<size_t> (),
4083 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004084 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004085 }
4086
4087 if (sendRequestError) {
4088 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004089 sp<NotificationListener> listener = mListener.promote();
4090 if (listener != NULL) {
4091 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004092 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004093 captureRequest->mResultExtras);
4094 }
4095 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004096
4097 // Remove yet-to-be submitted inflight request from inflightMap
4098 {
4099 sp<Camera3Device> parent = mParent.promote();
4100 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004101 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004102 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4103 if (idx >= 0) {
4104 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4105 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4106 parent->removeInFlightMapEntryLocked(idx);
4107 }
4108 }
4109 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004110 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004111
4112 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004113 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004114}
4115
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004116void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004117 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004118 // Optimized a bit for the simple steady-state case (single repeating
4119 // request), to avoid putting that request in the queue temporarily.
4120 Mutex::Autolock l(mRequestLock);
4121
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004122 assert(mNextRequests.empty());
4123
4124 NextRequest nextRequest;
4125 nextRequest.captureRequest = waitForNextRequestLocked();
4126 if (nextRequest.captureRequest == nullptr) {
4127 return;
4128 }
4129
Emilian Peevf4816702020-04-03 15:44:51 -07004130 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004132 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004133
4134 // Wait for additional requests
4135 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4136
4137 for (size_t i = 1; i < batchSize; i++) {
4138 NextRequest additionalRequest;
4139 additionalRequest.captureRequest = waitForNextRequestLocked();
4140 if (additionalRequest.captureRequest == nullptr) {
4141 break;
4142 }
4143
Emilian Peevf4816702020-04-03 15:44:51 -07004144 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004145 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004146 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004147 }
4148
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004149 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004150 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004151 mNextRequests.size(), batchSize);
4152 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004153 }
4154
4155 return;
4156}
4157
4158sp<Camera3Device::CaptureRequest>
4159 Camera3Device::RequestThread::waitForNextRequestLocked() {
4160 status_t res;
4161 sp<CaptureRequest> nextRequest;
4162
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004163 while (mRequestQueue.empty()) {
4164 if (!mRepeatingRequests.empty()) {
4165 // Always atomically enqueue all requests in a repeating request
4166 // list. Guarantees a complete in-sequence set of captures to
4167 // application.
4168 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004169 if (mFirstRepeating) {
4170 mFirstRepeating = false;
4171 } else {
4172 for (auto& request : requests) {
4173 // For repeating requests, override timestamp request using
4174 // the time a request is inserted into the request queue,
4175 // because the original repeating request will have an old
4176 // fixed timestamp.
4177 request->mRequestTimeNs = systemTime();
4178 }
4179 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 RequestList::const_iterator firstRequest =
4181 requests.begin();
4182 nextRequest = *firstRequest;
4183 mRequestQueue.insert(mRequestQueue.end(),
4184 ++firstRequest,
4185 requests.end());
4186 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004187
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004188 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004189
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004190 break;
4191 }
4192
4193 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004195 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4196 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 Mutex::Autolock pl(mPauseLock);
4198 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004199 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004200 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004201 if (mNotifyPipelineDrain) {
4202 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4203 mNotifyPipelineDrain = false;
4204 mStreamIdsToBeDrained.clear();
4205 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004206 // Let the tracker know
4207 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4208 if (statusTracker != 0) {
4209 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4210 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004211 sp<Camera3Device> parent = mParent.promote();
4212 if (parent != nullptr) {
4213 parent->mRequestBufferSM.onRequestThreadPaused();
4214 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004215 }
4216 // Stop waiting for now and let thread management happen
4217 return NULL;
4218 }
4219 }
4220
4221 if (nextRequest == NULL) {
4222 // Don't have a repeating request already in hand, so queue
4223 // must have an entry now.
4224 RequestList::iterator firstRequest =
4225 mRequestQueue.begin();
4226 nextRequest = *firstRequest;
4227 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004228 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4229 sp<NotificationListener> listener = mListener.promote();
4230 if (listener != NULL) {
4231 listener->notifyRequestQueueEmpty();
4232 }
4233 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234 }
4235
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004236 // In case we've been unpaused by setPaused clearing mDoPause, need to
4237 // update internal pause state (capture/setRepeatingRequest unpause
4238 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004239 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004240 if (mPaused) {
4241 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4242 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4243 if (statusTracker != 0) {
4244 statusTracker->markComponentActive(mStatusId);
4245 }
4246 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004247 mPaused = false;
4248
4249 // Check if we've reconfigured since last time, and reset the preview
4250 // request if so. Can't use 'NULL request == repeat' across configure calls.
4251 if (mReconfigured) {
4252 mPrevRequest.clear();
4253 mReconfigured = false;
4254 }
4255
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004256 if (nextRequest != NULL) {
4257 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004258 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4259 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004260
4261 // Since RequestThread::clear() removes buffers from the input stream,
4262 // get the right buffer here before unlocking mRequestLock
4263 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004264 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4265 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004266 if (res != OK) {
4267 // Can't get input buffer from gralloc queue - this could be due to
4268 // disconnected queue or other producer misbehavior, so not a fatal
4269 // error
4270 ALOGE("%s: Can't get input buffer, skipping request:"
4271 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004272
4273 sp<NotificationListener> listener = mListener.promote();
4274 if (listener != NULL) {
4275 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004276 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004277 nextRequest->mResultExtras);
4278 }
4279 return NULL;
4280 }
4281 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004282 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004283
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004284 return nextRequest;
4285}
4286
4287bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004288 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004289 status_t res;
4290 Mutex::Autolock l(mPauseLock);
4291 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004292 if (mPaused == false) {
4293 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004294 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004295 if (mNotifyPipelineDrain) {
4296 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4297 mNotifyPipelineDrain = false;
4298 mStreamIdsToBeDrained.clear();
4299 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004300 // Let the tracker know
4301 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4302 if (statusTracker != 0) {
4303 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4304 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004305 sp<Camera3Device> parent = mParent.promote();
4306 if (parent != nullptr) {
4307 parent->mRequestBufferSM.onRequestThreadPaused();
4308 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004309 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004310
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004311 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004312 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004313 return true;
4314 }
4315 }
4316 // We don't set mPaused to false here, because waitForNextRequest needs
4317 // to further manage the paused state in case of starvation.
4318 return false;
4319}
4320
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004321void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004322 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004323 // With work to do, mark thread as unpaused.
4324 // If paused by request (setPaused), don't resume, to avoid
4325 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004326 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004327 Mutex::Autolock p(mPauseLock);
4328 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004329 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4330 if (mPaused) {
4331 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4332 if (statusTracker != 0) {
4333 statusTracker->markComponentActive(mStatusId);
4334 }
4335 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004336 mPaused = false;
4337 }
4338}
4339
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004340void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4341 sp<Camera3Device> parent = mParent.promote();
4342 if (parent != NULL) {
4343 va_list args;
4344 va_start(args, fmt);
4345
4346 parent->setErrorStateV(fmt, args);
4347
4348 va_end(args);
4349 }
4350}
4351
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004352status_t Camera3Device::RequestThread::insertTriggers(
4353 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004354 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004355 Mutex::Autolock al(mTriggerMutex);
4356
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004357 sp<Camera3Device> parent = mParent.promote();
4358 if (parent == NULL) {
4359 CLOGE("RequestThread: Parent is gone");
4360 return DEAD_OBJECT;
4361 }
4362
Emilian Peevaebbe412018-01-15 13:53:24 +00004363 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004364 size_t count = mTriggerMap.size();
4365
4366 for (size_t i = 0; i < count; ++i) {
4367 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004368 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004369
4370 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4371 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4372 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004373 if (isAeTrigger) {
4374 request->mResultExtras.precaptureTriggerId = triggerId;
4375 mCurrentPreCaptureTriggerId = triggerId;
4376 } else {
4377 request->mResultExtras.afTriggerId = triggerId;
4378 mCurrentAfTriggerId = triggerId;
4379 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004380 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004381 }
4382
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004383 camera_metadata_entry entry = metadata.find(tag);
4384
4385 if (entry.count > 0) {
4386 /**
4387 * Already has an entry for this trigger in the request.
4388 * Rewrite it with our requested trigger value.
4389 */
4390 RequestTrigger oldTrigger = trigger;
4391
4392 oldTrigger.entryValue = entry.data.u8[0];
4393
4394 mTriggerReplacedMap.add(tag, oldTrigger);
4395 } else {
4396 /**
4397 * More typical, no trigger entry, so we just add it
4398 */
4399 mTriggerRemovedMap.add(tag, trigger);
4400 }
4401
4402 status_t res;
4403
4404 switch (trigger.getTagType()) {
4405 case TYPE_BYTE: {
4406 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4407 res = metadata.update(tag,
4408 &entryValue,
4409 /*count*/1);
4410 break;
4411 }
4412 case TYPE_INT32:
4413 res = metadata.update(tag,
4414 &trigger.entryValue,
4415 /*count*/1);
4416 break;
4417 default:
4418 ALOGE("%s: Type not supported: 0x%x",
4419 __FUNCTION__,
4420 trigger.getTagType());
4421 return INVALID_OPERATION;
4422 }
4423
4424 if (res != OK) {
4425 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4426 ", value %d", __FUNCTION__, trigger.getTagName(),
4427 trigger.entryValue);
4428 return res;
4429 }
4430
4431 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4432 trigger.getTagName(),
4433 trigger.entryValue);
4434 }
4435
4436 mTriggerMap.clear();
4437
4438 return count;
4439}
4440
4441status_t Camera3Device::RequestThread::removeTriggers(
4442 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004443 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004444 Mutex::Autolock al(mTriggerMutex);
4445
Emilian Peevaebbe412018-01-15 13:53:24 +00004446 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004447
4448 /**
4449 * Replace all old entries with their old values.
4450 */
4451 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4452 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4453
4454 status_t res;
4455
4456 uint32_t tag = trigger.metadataTag;
4457 switch (trigger.getTagType()) {
4458 case TYPE_BYTE: {
4459 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4460 res = metadata.update(tag,
4461 &entryValue,
4462 /*count*/1);
4463 break;
4464 }
4465 case TYPE_INT32:
4466 res = metadata.update(tag,
4467 &trigger.entryValue,
4468 /*count*/1);
4469 break;
4470 default:
4471 ALOGE("%s: Type not supported: 0x%x",
4472 __FUNCTION__,
4473 trigger.getTagType());
4474 return INVALID_OPERATION;
4475 }
4476
4477 if (res != OK) {
4478 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4479 ", trigger value %d", __FUNCTION__,
4480 trigger.getTagName(), trigger.entryValue);
4481 return res;
4482 }
4483 }
4484 mTriggerReplacedMap.clear();
4485
4486 /**
4487 * Remove all new entries.
4488 */
4489 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4490 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4491 status_t res = metadata.erase(trigger.metadataTag);
4492
4493 if (res != OK) {
4494 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4495 ", trigger value %d", __FUNCTION__,
4496 trigger.getTagName(), trigger.entryValue);
4497 return res;
4498 }
4499 }
4500 mTriggerRemovedMap.clear();
4501
4502 return OK;
4503}
4504
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004505status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004506 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004507 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004508 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004509 status_t res;
4510
Emilian Peevaebbe412018-01-15 13:53:24 +00004511 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004512
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004513 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004514 // exists
4515 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4516 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4517 if (afTrigger.count > 0 &&
4518 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4519 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004520 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004521 if (res != OK) return res;
4522 }
4523
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004524 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004525 // if none already exists
4526 camera_metadata_entry pcTrigger =
4527 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4528 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4529 if (pcTrigger.count > 0 &&
4530 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4531 pcId.count == 0) {
4532 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004533 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004534 if (res != OK) return res;
4535 }
4536
4537 return OK;
4538}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004539
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004540bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4541 const sp<CaptureRequest> &request) {
4542 ATRACE_CALL();
4543
4544 if (request->mRotateAndCropAuto) {
4545 Mutex::Autolock l(mTriggerMutex);
4546 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4547
4548 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4549 if (rotateAndCropEntry.count > 0) {
4550 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4551 return false;
4552 } else {
4553 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4554 return true;
4555 }
4556 } else {
4557 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4558 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4559 &rotateAndCrop_u8, 1);
4560 return true;
4561 }
4562 }
4563 return false;
4564}
4565
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004566bool Camera3Device::RequestThread::overrideTestPattern(
4567 const sp<CaptureRequest> &request) {
4568 ATRACE_CALL();
4569
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004570 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004571
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004572 Mutex::Autolock l(mTriggerMutex);
4573
4574 bool changed = false;
4575
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004576 // For a multi-camera, the physical cameras support the same set of
4577 // test pattern modes as the logical camera.
4578 for (auto& settings : request->mSettingsList) {
4579 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004580
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004581 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4582 int32_t testPatternData[4] = {
4583 settings.mOriginalTestPatternData[0],
4584 settings.mOriginalTestPatternData[1],
4585 settings.mOriginalTestPatternData[2],
4586 settings.mOriginalTestPatternData[3]
4587 };
4588 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4589 testPatternMode = mCameraMute;
4590 testPatternData[0] = 0;
4591 testPatternData[1] = 0;
4592 testPatternData[2] = 0;
4593 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004594 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004595
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004596 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4597 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4598 if (testPatternEntry.count > 0) {
4599 if (testPatternEntry.data.i32[0] != testPatternMode) {
4600 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004601 changed = true;
4602 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004603 } else if (supportTestPatternModeKey) {
4604 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4605 &testPatternMode, 1);
4606 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004607 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004608
4609 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4610 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4611 if (testPatternColor.count >= 4) {
4612 for (size_t i = 0; i < 4; i++) {
4613 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4614 testPatternColor.data.i32[i] = testPatternData[i];
4615 changed = true;
4616 }
4617 }
4618 } else if (supportTestPatternDataKey) {
4619 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4620 testPatternData, 4);
4621 changed = true;
4622 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004623 }
4624
4625 return changed;
4626}
4627
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004628status_t Camera3Device::RequestThread::setHalInterface(
4629 sp<HalInterface> newHalInterface) {
4630 if (newHalInterface.get() == nullptr) {
4631 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4632 return DEAD_OBJECT;
4633 }
4634
4635 mInterface = newHalInterface;
4636
4637 return OK;
4638}
4639
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004640/**
4641 * PreparerThread inner class methods
4642 */
4643
4644Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004645 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004646 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004647}
4648
4649Camera3Device::PreparerThread::~PreparerThread() {
4650 Thread::requestExitAndWait();
4651 if (mCurrentStream != nullptr) {
4652 mCurrentStream->cancelPrepare();
4653 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4654 mCurrentStream.clear();
4655 }
4656 clear();
4657}
4658
Ruben Brunkc78ac262015-08-13 17:58:46 -07004659status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004660 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004661 status_t res;
4662
4663 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004664 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004665
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004666 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004667 if (res == OK) {
4668 // No preparation needed, fire listener right off
4669 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004670 if (listener != NULL) {
4671 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004672 }
4673 return OK;
4674 } else if (res != NOT_ENOUGH_DATA) {
4675 return res;
4676 }
4677
4678 // Need to prepare, start up thread if necessary
4679 if (!mActive) {
4680 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4681 // isn't running
4682 Thread::requestExitAndWait();
4683 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4684 if (res != OK) {
4685 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004686 if (listener != NULL) {
4687 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004688 }
4689 return res;
4690 }
4691 mCancelNow = false;
4692 mActive = true;
4693 ALOGV("%s: Preparer stream started", __FUNCTION__);
4694 }
4695
4696 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004697 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004698 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4699
4700 return OK;
4701}
4702
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004703void Camera3Device::PreparerThread::pause() {
4704 ATRACE_CALL();
4705
4706 Mutex::Autolock l(mLock);
4707
4708 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4709 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4710 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4711 int currentMaxCount = mCurrentMaxCount;
4712 mPendingStreams.clear();
4713 mCancelNow = true;
4714 while (mActive) {
4715 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4716 if (res == TIMED_OUT) {
4717 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4718 return;
4719 } else if (res != OK) {
4720 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4721 return;
4722 }
4723 }
4724
4725 //Check whether the prepare thread was able to complete the current
4726 //stream. In case work is still pending emplace it along with the rest
4727 //of the streams in the pending list.
4728 if (currentStream != nullptr) {
4729 if (!mCurrentPrepareComplete) {
4730 pendingStreams.emplace(currentMaxCount, currentStream);
4731 }
4732 }
4733
4734 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4735 for (const auto& it : mPendingStreams) {
4736 it.second->cancelPrepare();
4737 }
4738}
4739
4740status_t Camera3Device::PreparerThread::resume() {
4741 ATRACE_CALL();
4742 status_t res;
4743
4744 Mutex::Autolock l(mLock);
4745 sp<NotificationListener> listener = mListener.promote();
4746
4747 if (mActive) {
4748 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4749 return NO_INIT;
4750 }
4751
4752 auto it = mPendingStreams.begin();
4753 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004754 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004755 if (res == OK) {
4756 if (listener != NULL) {
4757 listener->notifyPrepared(it->second->getId());
4758 }
4759 it = mPendingStreams.erase(it);
4760 } else if (res != NOT_ENOUGH_DATA) {
4761 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4762 res, strerror(-res));
4763 it = mPendingStreams.erase(it);
4764 } else {
4765 it++;
4766 }
4767 }
4768
4769 if (mPendingStreams.empty()) {
4770 return OK;
4771 }
4772
4773 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4774 if (res != OK) {
4775 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4776 __FUNCTION__, res, strerror(-res));
4777 return res;
4778 }
4779 mCancelNow = false;
4780 mActive = true;
4781 ALOGV("%s: Preparer stream started", __FUNCTION__);
4782
4783 return OK;
4784}
4785
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004786status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004787 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004788 Mutex::Autolock l(mLock);
4789
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004790 for (const auto& it : mPendingStreams) {
4791 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004792 }
4793 mPendingStreams.clear();
4794 mCancelNow = true;
4795
4796 return OK;
4797}
4798
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004799void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004800 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004801 Mutex::Autolock l(mLock);
4802 mListener = listener;
4803}
4804
4805bool Camera3Device::PreparerThread::threadLoop() {
4806 status_t res;
4807 {
4808 Mutex::Autolock l(mLock);
4809 if (mCurrentStream == nullptr) {
4810 // End thread if done with work
4811 if (mPendingStreams.empty()) {
4812 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4813 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4814 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4815 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004816 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817 return false;
4818 }
4819
4820 // Get next stream to prepare
4821 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004822 mCurrentStream = it->second;
4823 mCurrentMaxCount = it->first;
4824 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004825 mPendingStreams.erase(it);
4826 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4827 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4828 } else if (mCancelNow) {
4829 mCurrentStream->cancelPrepare();
4830 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4831 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4832 mCurrentStream.clear();
4833 mCancelNow = false;
4834 return true;
4835 }
4836 }
4837
4838 res = mCurrentStream->prepareNextBuffer();
4839 if (res == NOT_ENOUGH_DATA) return true;
4840 if (res != OK) {
4841 // Something bad happened; try to recover by cancelling prepare and
4842 // signalling listener anyway
4843 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4844 mCurrentStream->getId(), res, strerror(-res));
4845 mCurrentStream->cancelPrepare();
4846 }
4847
4848 // This stream has finished, notify listener
4849 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004850 sp<NotificationListener> listener = mListener.promote();
4851 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004852 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4853 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004854 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004855 }
4856
4857 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4858 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004859 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004860
4861 return true;
4862}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004863
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004864status_t Camera3Device::RequestBufferStateMachine::initialize(
4865 sp<camera3::StatusTracker> statusTracker) {
4866 if (statusTracker == nullptr) {
4867 ALOGE("%s: statusTracker is null", __FUNCTION__);
4868 return BAD_VALUE;
4869 }
4870
4871 std::lock_guard<std::mutex> lock(mLock);
4872 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004873 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004874 return OK;
4875}
4876
4877bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4878 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004879 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004880 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004881 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004882 return true;
4883 }
4884 return false;
4885}
4886
4887void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4888 std::lock_guard<std::mutex> lock(mLock);
4889 if (!mRequestBufferOngoing) {
4890 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4891 return;
4892 }
4893 mRequestBufferOngoing = false;
4894 if (mStatus == RB_STATUS_PENDING_STOP) {
4895 checkSwitchToStopLocked();
4896 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004897 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004898}
4899
4900void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4901 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004902 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004903 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004904 return;
4905}
4906
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004907void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004908 std::lock_guard<std::mutex> lock(mLock);
4909 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004910 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4911 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004912 mInflightMapEmpty = false;
4913 if (mStatus == RB_STATUS_STOPPED) {
4914 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004915 }
4916 return;
4917}
4918
4919void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4920 std::lock_guard<std::mutex> lock(mLock);
4921 mRequestThreadPaused = true;
4922 if (mStatus == RB_STATUS_PENDING_STOP) {
4923 checkSwitchToStopLocked();
4924 }
4925 return;
4926}
4927
4928void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4929 std::lock_guard<std::mutex> lock(mLock);
4930 mInflightMapEmpty = true;
4931 if (mStatus == RB_STATUS_PENDING_STOP) {
4932 checkSwitchToStopLocked();
4933 }
4934 return;
4935}
4936
4937void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4938 std::lock_guard<std::mutex> lock(mLock);
4939 if (!checkSwitchToStopLocked()) {
4940 mStatus = RB_STATUS_PENDING_STOP;
4941 }
4942 return;
4943}
4944
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004945bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4946 std::lock_guard<std::mutex> lock(mLock);
4947 if (mRequestBufferOngoing) {
4948 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4949 __FUNCTION__);
4950 return false;
4951 }
4952 mSwitchedToOffline = true;
4953 mInflightMapEmpty = true;
4954 mRequestThreadPaused = true;
4955 mStatus = RB_STATUS_STOPPED;
4956 return true;
4957}
4958
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004959void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4960 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4961 if (statusTracker != nullptr) {
4962 if (active) {
4963 statusTracker->markComponentActive(mRequestBufferStatusId);
4964 } else {
4965 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4966 }
4967 }
4968}
4969
4970bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4971 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4972 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004973 return true;
4974 }
4975 return false;
4976}
4977
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004978bool Camera3Device::startRequestBuffer() {
4979 return mRequestBufferSM.startRequestBuffer();
4980}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004981
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004982void Camera3Device::endRequestBuffer() {
4983 mRequestBufferSM.endRequestBuffer();
4984}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004985
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004986nsecs_t Camera3Device::getWaitDuration() {
4987 return kBaseGetBufferWait + getExpectedInFlightDuration();
4988}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004989
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004990void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4991 mInterface->getInflightBufferKeys(out);
4992}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004993
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004994void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4995 mInterface->getInflightRequestBufferKeys(out);
4996}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004997
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004998std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
4999 std::vector<sp<Camera3StreamInterface>> ret;
5000 bool hasInputStream = mInputStream != nullptr;
5001 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5002 if (hasInputStream) {
5003 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005004 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005005 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5006 ret.push_back(mOutputStreams[i]);
5007 }
5008 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5009 ret.push_back(mDeletedStreams[i]);
5010 }
5011 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005012}
5013
Emilian Peevcc0b7952020-01-07 13:54:47 -08005014void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5015 ATRACE_CALL();
5016
5017 if (offlineStreamIds == nullptr) {
5018 return;
5019 }
5020
5021 Mutex::Autolock il(mInterfaceLock);
5022
5023 auto streamIds = mOutputStreams.getStreamIds();
5024 bool hasInputStream = mInputStream != nullptr;
5025 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5026 offlineStreamIds->push_back(mInputStream->getId());
5027 }
5028
5029 for (const auto & streamId : streamIds) {
5030 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5031 // Streams that use the camera buffer manager are currently not supported in
5032 // offline mode
5033 if (stream->getOfflineProcessingSupport() &&
5034 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5035 offlineStreamIds->push_back(streamId);
5036 }
5037 }
5038}
5039
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005040status_t Camera3Device::setRotateAndCropAutoBehavior(
5041 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5042 ATRACE_CALL();
5043 Mutex::Autolock il(mInterfaceLock);
5044 Mutex::Autolock l(mLock);
5045 if (mRequestThread == nullptr) {
5046 return INVALID_OPERATION;
5047 }
5048 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5049}
5050
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005051bool Camera3Device::supportsCameraMute() {
5052 Mutex::Autolock il(mInterfaceLock);
5053 Mutex::Autolock l(mLock);
5054
5055 return mSupportCameraMute;
5056}
5057
5058status_t Camera3Device::setCameraMute(bool enabled) {
5059 ATRACE_CALL();
5060 Mutex::Autolock il(mInterfaceLock);
5061 Mutex::Autolock l(mLock);
5062
5063 if (mRequestThread == nullptr || !mSupportCameraMute) {
5064 return INVALID_OPERATION;
5065 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005066 int32_t muteMode =
5067 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5068 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5069 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5070 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005071}
5072
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005073status_t Camera3Device::injectCamera(const String8& injectedCamId,
5074 sp<CameraProviderManager> manager) {
5075 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5076 ATRACE_CALL();
5077 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005078 // When the camera device is active, injectCamera() and stopInjection() will call
5079 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5080 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5081 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5082 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5083 // waitUntilStateThenRelock().
5084 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005085
5086 status_t res = NO_ERROR;
5087 if (mInjectionMethods->isInjecting()) {
5088 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5089 return OK;
5090 } else {
5091 res = mInjectionMethods->stopInjection();
5092 if (res != OK) {
5093 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5094 __FUNCTION__, res);
5095 return res;
5096 }
5097 }
5098 }
5099
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005100 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005101 if (res != OK) {
5102 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5103 __FUNCTION__, res);
5104 return res;
5105 }
5106
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005107 // When the second display of android is cast to the remote device, and the opened camera is
5108 // also cast to the second display, in this case, because the camera has configured the streams
5109 // at this time, we can directly call injectCamera() to replace the internal camera with
5110 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005111 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5112 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5113
5114 camera3::camera_stream_configuration injectionConfig;
5115 std::vector<uint32_t> injectionBufferSizes;
5116 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5117 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5118 || injectionBufferSizes.size() <= 0) {
5119 ALOGE("Failed to inject camera due to abandoned configuration! "
5120 "mOperatingMode: %d injectionConfig.num_streams: %d "
5121 "injectionBufferSizes.size(): %zu", mOperatingMode,
5122 injectionConfig.num_streams, injectionBufferSizes.size());
5123 return DEAD_OBJECT;
5124 }
5125
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005126 res = mInjectionMethods->injectCamera(
5127 injectionConfig, injectionBufferSizes);
5128 if (res != OK) {
5129 ALOGE("Can't finish inject camera process!");
5130 return res;
5131 }
5132 }
5133
5134 return OK;
5135}
5136
5137status_t Camera3Device::stopInjection() {
5138 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5139 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005140 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005141 return mInjectionMethods->stopInjection();
5142}
5143
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005144}; // namespace android