blob: 997be51b9b16521b1aa47aa2327e6c7432510f7f [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080087 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080088 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070090 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070093 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000095 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010096 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070097 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070098 mNeedFixupMonochromeTags(false),
99 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
105Camera3Device::~Camera3Device()
106{
107 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700109 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800113 return mId;
114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116status_t Camera3Device::initializeCommonLocked() {
117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700118 /** Start up status tracker thread */
119 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700121 if (res != OK) {
122 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
123 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 mStatusTracker.clear();
126 return res;
127 }
128
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700129 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700130 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700132 if (mUseHalBufManager) {
133 res = mRequestBufferSM.initialize(mStatusTracker);
134 if (res != OK) {
135 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
136 strerror(-res), res);
137 mInterface->close();
138 mStatusTracker.clear();
139 return res;
140 }
141 }
142
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800143 /** Create buffer manager */
144 mBufferManager = new Camera3BufferManager();
145
146 Vector<int32_t> sessionParamKeys;
147 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
148 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
149 if (sessionKeysEntry.count > 0) {
150 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
151 }
152
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700153 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
154 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
155 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
156 if (availableTestPatternModes.data.i32[i] ==
157 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
158 mSupportCameraMute = true;
159 mSupportTestPatternSolidColor = true;
160 break;
161 } else if (availableTestPatternModes.data.i32[i] ==
162 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
163 mSupportCameraMute = true;
164 mSupportTestPatternSolidColor = false;
165 }
166 }
167
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700168 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800169 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700170 this, mStatusTracker, mInterface, sessionParamKeys,
171 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800173 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700174 SET_ERR_L("Unable to start request queue thread: %s (%d)",
175 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800177 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800178 return res;
179 }
180
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700181 mPreparerThread = new PreparerThread();
182
Ruben Brunk183f0562015-08-12 12:55:02 -0700183 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800184 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400185 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700186 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700187 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800188 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800190 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800191 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 camera_metadata_entry timestampSource =
193 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
194 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
195 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800196 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 }
198
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700199 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100200 camera_metadata_entry partialResultsCount =
201 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
202 if (partialResultsCount.count > 0) {
203 mNumPartialResults = partialResultsCount.data.i32[0];
204 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700205 }
206
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800207 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
208 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700209 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700210 if (res != OK) {
211 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
212 return res;
213 }
214 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800216 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700219 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
220 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
221 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
222 }
223
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800224 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
225 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
226 }
227
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800228 // Hidl/AidlCamera3DeviceInjectionMethods
229 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800230
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 return OK;
232}
233
234status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700235 return disconnectImpl();
236}
237
238status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700240 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800241
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700242 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700243 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800245 Mutex::Autolock il(mInterfaceLock);
246 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
247 {
248 Mutex::Autolock l(mLock);
249 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700250
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800251 if (mStatus == STATUS_ACTIVE ||
252 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
253 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 } else {
258 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
259 if (res != OK) {
260 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
261 maxExpectedDuration);
262 // Continue to close device even in case of error
263 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800266
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 if (mStatus == STATUS_ERROR) {
268 CLOGE("Shutting down in an error state");
269 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatusTracker != NULL) {
272 mStatusTracker->requestExit();
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mRequestThread != NULL) {
276 mRequestThread->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
280 for (size_t i = 0; i < mOutputStreams.size(); i++) {
281 streams.push_back(mOutputStreams[i]);
282 }
283 if (mInputStream != nullptr) {
284 streams.push_back(mInputStream);
285 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
289 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
291 // HAL may be in a bad state, so waiting for request thread
292 // (which may be stuck in the HAL processCaptureRequest call)
293 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 // give up mInterfaceLock here and then lock it again. Could this lead
295 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 mRequestThread->join();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 Mutex::Autolock il(mInterfaceLock);
300 if (mStatusTracker != NULL) {
301 mStatusTracker->join();
302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800304 if (mInjectionMethods->isInjecting()) {
305 mInjectionMethods->stopInjection();
306 }
307
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 HalInterface* interface;
309 {
310 Mutex::Autolock l(mLock);
311 mRequestThread.clear();
312 Mutex::Autolock stLock(mTrackerLock);
313 mStatusTracker.clear();
314 interface = mInterface.get();
315 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700316
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 // Call close without internal mutex held, as the HAL close may need to
318 // wait on assorted callbacks,etc, to complete before it can return.
319 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 {
324 Mutex::Autolock l(mLock);
325 mInterface->clear();
326 mOutputStreams.clear();
327 mInputStream.clear();
328 mDeletedStreams.clear();
329 mBufferManager.clear();
330 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
331 }
332
333 for (auto& weakStream : streams) {
334 sp<Camera3StreamInterface> stream = weakStream.promote();
335 if (stream != nullptr) {
336 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
337 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
338 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 }
340 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343}
344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345// For dumping/debugging only -
346// try to acquire a lock a few times, eventually give up to proceed with
347// debug/dump operations
348bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
349 bool gotLock = false;
350 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
351 if (lock.tryLock() == NO_ERROR) {
352 gotLock = true;
353 break;
354 } else {
355 usleep(kDumpSleepDuration);
356 }
357 }
358 return gotLock;
359}
360
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800361nsecs_t Camera3Device::getMonoToBoottimeOffset() {
362 // try three times to get the clock offset, choose the one
363 // with the minimum gap in measurements.
364 const int tries = 3;
365 nsecs_t bestGap, measured;
366 for (int i = 0; i < tries; ++i) {
367 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
369 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t gap = tmono2 - tmono;
371 if (i == 0 || gap < bestGap) {
372 bestGap = gap;
373 measured = tbase - ((tmono + tmono2) >> 1);
374 }
375 }
376 return measured;
377}
378
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800379ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
380 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700381 // Get max jpeg size (area-wise) for default sensor pixel mode
382 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800383 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700384 /*isUltraHighResolutionSensor*/false);
385 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
386 // not ultra high res sensor
387 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800388 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700389 /*isUltraHighResolution*/true);
390 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
392 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700393 return BAD_VALUE;
394 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700395 bool useMaxSensorPixelModeThreshold = false;
396 if (uhrMaxJpegResolution.width != 0 &&
397 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
398 // Use the ultra high res max jpeg size and max jpeg buffer size
399 useMaxSensorPixelModeThreshold = true;
400 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700401
Zhijun Hef7da0962014-04-24 13:27:56 -0700402 // Get max jpeg buffer size
403 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
407 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700408 return BAD_VALUE;
409 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700410 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411
412 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
413 if (useMaxSensorPixelModeThreshold) {
414 maxJpegBufferSize =
415 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
416 maxDefaultJpegResolution, maxJpegBufferSize);
417 chosenMaxJpegResolution = uhrMaxJpegResolution;
418 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800419 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700420
421 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700422 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800424 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
425 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700426 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800427 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
428 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 return jpegBufferSize;
432}
433
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700435 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800436 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700437 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800438 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
439 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700440 return BAD_VALUE;
441 }
442 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
443 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
444 return maxBytesForPointCloud;
445}
446
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800447ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
448 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800449 const int PER_CONFIGURATION_SIZE = 3;
450 const int WIDTH_OFFSET = 0;
451 const int HEIGHT_OFFSET = 1;
452 const int SIZE_OFFSET = 2;
453 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800454 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800455 camera3::SessionConfigurationUtils::getAppropriateModeTag(
456 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
457 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800458 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800460 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
461 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800462 return BAD_VALUE;
463 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800465 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
466 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
467 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
468 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
469 }
470 }
471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800472 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
473 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 return BAD_VALUE;
475}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700476
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800477status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
478 ATRACE_CALL();
479 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700480
481 // Try to lock, but continue in case of failure (to avoid blocking in
482 // deadlocks)
483 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
484 bool gotLock = tryLockSpinRightRound(mLock);
485
486 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
488 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700489 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
491 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700492
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800493 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700494
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800495 String16 templatesOption("-t");
496 int n = args.size();
497 for (int i = 0; i < n; i++) {
498 if (args[i] == templatesOption) {
499 dumpTemplates = true;
500 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000501 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700502 if (i + 1 < n) {
503 String8 monitorTags = String8(args[i + 1]);
504 if (monitorTags == "off") {
505 mTagMonitor.disableMonitoring();
506 } else {
507 mTagMonitor.parseTagsToMonitor(monitorTags);
508 }
509 } else {
510 mTagMonitor.disableMonitoring();
511 }
512 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800513 }
514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800515 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800517 const char *status =
518 mStatus == STATUS_ERROR ? "ERROR" :
519 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700520 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
521 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800522 mStatus == STATUS_ACTIVE ? "ACTIVE" :
523 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700526 if (mStatus == STATUS_ERROR) {
527 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800529 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800530 const char *mode =
531 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
532 mOperatingMode == static_cast<int>(
533 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
534 "CUSTOM";
535 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800536
537 if (mInputStream != NULL) {
538 write(fd, lines.string(), lines.size());
539 mInputStream->dump(fd, args);
540 } else {
541 lines.appendFormat(" No input stream.\n");
542 write(fd, lines.string(), lines.size());
543 }
544 for (size_t i = 0; i < mOutputStreams.size(); i++) {
545 mOutputStreams[i]->dump(fd,args);
546 }
547
Zhijun He431503c2016-03-07 17:30:16 -0800548 if (mBufferManager != NULL) {
549 lines = String8(" Camera3 Buffer Manager:\n");
550 write(fd, lines.string(), lines.size());
551 mBufferManager->dump(fd, args);
552 }
Zhijun He125684a2015-12-26 15:07:30 -0800553
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700554 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700555 if (mInFlightLock.try_lock()) {
556 if (mInFlightMap.size() == 0) {
557 lines.append(" None\n");
558 } else {
559 for (size_t i = 0; i < mInFlightMap.size(); i++) {
560 InFlightRequest r = mInFlightMap.valueAt(i);
561 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
562 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
563 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
564 r.numBuffersLeft);
565 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700566 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700567 mInFlightLock.unlock();
568 } else {
569 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700570 }
571 write(fd, lines.string(), lines.size());
572
Shuzhen Wang686f6442017-06-20 16:16:04 -0700573 if (mRequestThread != NULL) {
574 mRequestThread->dumpCaptureRequestLatency(fd,
575 " ProcessCaptureRequest latency histogram:");
576 }
577
Igor Murashkin1e479c02013-09-06 16:55:14 -0700578 {
579 lines = String8(" Last request sent:\n");
580 write(fd, lines.string(), lines.size());
581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700582 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700583 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
584 }
585
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700587 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800588 "TEMPLATE_PREVIEW",
589 "TEMPLATE_STILL_CAPTURE",
590 "TEMPLATE_VIDEO_RECORD",
591 "TEMPLATE_VIDEO_SNAPSHOT",
592 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800593 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800594 };
595
Emilian Peevf4816702020-04-03 15:44:51 -0700596 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 camera_metadata_t *templateRequest = nullptr;
598 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700599 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800601 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 lines.append(" Not supported\n");
603 write(fd, lines.string(), lines.size());
604 } else {
605 write(fd, lines.string(), lines.size());
606 dump_indented_camera_metadata(templateRequest,
607 fd, /*verbosity*/2, /*indentation*/8);
608 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 }
611 }
612
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700613 mTagMonitor.dumpMonitoredMetadata(fd);
614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800616 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800620
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700621 if (gotLock) mLock.unlock();
622 if (gotInterfaceLock) mInterfaceLock.unlock();
623
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800624 return OK;
625}
626
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700627status_t Camera3Device::startWatchingTags(const String8 &tags) {
628 mTagMonitor.parseTagsToMonitor(tags);
629 return OK;
630}
631
632status_t Camera3Device::stopWatchingTags() {
633 mTagMonitor.disableMonitoring();
634 return OK;
635}
636
637status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
638 mTagMonitor.getLatestMonitoredTagEvents(out);
639 return OK;
640}
641
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800642const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
645 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700646 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 mStatus == STATUS_ERROR ?
648 "when in error state" : "before init");
649 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700650 if (physicalId.isEmpty()) {
651 return mDeviceInfo;
652 } else {
653 std::string id(physicalId.c_str());
654 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
655 return mPhysicalDeviceInfoMap.at(id);
656 } else {
657 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
658 return mDeviceInfo;
659 }
660 }
661}
662
663const CameraMetadata& Camera3Device::info() const {
664 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666}
667
Jianing Wei90e59c92014-03-12 18:29:36 -0700668status_t Camera3Device::checkStatusOkToCaptureLocked() {
669 switch (mStatus) {
670 case STATUS_ERROR:
671 CLOGE("Device has encountered a serious error");
672 return INVALID_OPERATION;
673 case STATUS_UNINITIALIZED:
674 CLOGE("Device not initialized");
675 return INVALID_OPERATION;
676 case STATUS_UNCONFIGURED:
677 case STATUS_CONFIGURED:
678 case STATUS_ACTIVE:
679 // OK
680 break;
681 default:
682 SET_ERR_L("Unexpected status: %d", mStatus);
683 return INVALID_OPERATION;
684 }
685 return OK;
686}
687
688status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000689 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700690 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700691 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700692 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700693 if (requestList == NULL) {
694 CLOGE("requestList cannot be NULL.");
695 return BAD_VALUE;
696 }
697
Jianing Weicb0652e2014-03-12 18:29:36 -0700698 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
701 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
702 ++metadataIt, ++surfaceMapIt) {
703 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700704 if (newRequest == 0) {
705 CLOGE("Can't create capture request");
706 return BAD_VALUE;
707 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700708
Shuzhen Wang9d066012016-09-30 11:30:20 -0700709 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700710 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700711
Jianing Weicb0652e2014-03-12 18:29:36 -0700712 // Setup burst Id and request Id
713 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800714 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
715 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700716 CLOGE("RequestID does not exist in metadata");
717 return BAD_VALUE;
718 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800719 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700720
Jianing Wei90e59c92014-03-12 18:29:36 -0700721 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700722
723 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700724 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700725 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
726 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
727 return BAD_VALUE;
728 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700729
730 // Setup batch size if this is a high speed video recording request.
731 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
732 auto firstRequest = requestList->begin();
733 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
734 if (outputStream->isVideoStream()) {
735 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800736 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700737 break;
738 }
739 }
740 }
741
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 return OK;
743}
744
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800745status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800746 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800747
Emilian Peevaebbe412018-01-15 13:53:24 +0000748 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000750 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800752 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753}
754
Emilian Peevaebbe412018-01-15 13:53:24 +0000755void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 std::list<const SurfaceMap>& surfaceMaps,
757 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 PhysicalCameraSettingsList requestList;
759 requestList.push_back({std::string(getId().string()), request});
760 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
762 SurfaceMap surfaceMap;
763 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
764 // With no surface list passed in, stream and surface will have 1-to-1
765 // mapping. So the surface index is 0 for each stream in the surfaceMap.
766 for (size_t i = 0; i < streams.count; i++) {
767 surfaceMap[streams.data.i32[i]].push_back(0);
768 }
769 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770}
771
Jianing Wei90e59c92014-03-12 18:29:36 -0700772status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 const std::list<const SurfaceMap> &surfaceMaps,
775 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700776 /*out*/
777 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700779 nsecs_t requestTimeNs = systemTime();
780
Jianing Wei90e59c92014-03-12 18:29:36 -0700781 Mutex::Autolock il(mInterfaceLock);
782 Mutex::Autolock l(mLock);
783
784 status_t res = checkStatusOkToCaptureLocked();
785 if (res != OK) {
786 // error logged by previous call
787 return res;
788 }
789
790 RequestList requestList;
791
Shuzhen Wang0129d522016-10-30 22:43:41 -0700792 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700793 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700794 if (res != OK) {
795 // error logged by previous call
796 return res;
797 }
798
799 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700802 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 }
804
805 if (res == OK) {
806 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
807 if (res != OK) {
808 SET_ERR_L("Can't transition to active in %f seconds!",
809 kActiveTimeout/1e9);
810 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 } else {
814 CLOGE("Cannot queue request. Impossible.");
815 return BAD_VALUE;
816 }
817
818 return res;
819}
820
Emilian Peevaebbe412018-01-15 13:53:24 +0000821status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700823 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 ATRACE_CALL();
825
Emilian Peevaebbe412018-01-15 13:53:24 +0000826 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828
Jianing Weicb0652e2014-03-12 18:29:36 -0700829status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
830 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836
Emilian Peevaebbe412018-01-15 13:53:24 +0000837 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700838 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839}
840
Emilian Peevaebbe412018-01-15 13:53:24 +0000841status_t Camera3Device::setStreamingRequestList(
842 const List<const PhysicalCameraSettingsList> &requestsList,
843 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 ATRACE_CALL();
845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700847}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800848
849sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 status_t res;
852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700853 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800854 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
855 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700857 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700858 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700862 } else if (mStatus == STATUS_UNCONFIGURED) {
863 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700864 CLOGE("No streams configured");
865 return NULL;
866 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800867 }
868
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800870 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800871}
872
Jianing Weicb0652e2014-03-12 18:29:36 -0700873status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700875 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 switch (mStatus) {
879 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700880 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700883 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700891 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 return INVALID_OPERATION;
893 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700895
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897}
898
899status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
900 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700901 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700903 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904}
905
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700906status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800907 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700908 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700910 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700911 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800912 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
913 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700914
915 status_t res;
916 bool wasActive = false;
917
918 switch (mStatus) {
919 case STATUS_ERROR:
920 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
921 return INVALID_OPERATION;
922 case STATUS_UNINITIALIZED:
923 ALOGE("%s: Device not initialized", __FUNCTION__);
924 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 case STATUS_UNCONFIGURED:
926 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700927 // OK
928 break;
929 case STATUS_ACTIVE:
930 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700931 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 return res;
935 }
936 wasActive = true;
937 break;
938 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700940 return INVALID_OPERATION;
941 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700942 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700943
944 if (mInputStream != 0) {
945 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
946 return INVALID_OPERATION;
947 }
948
949 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
950 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700951 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952
953 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800954 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955
956 *id = mNextStreamId++;
957
958 // Continue captures if active at start
959 if (wasActive) {
960 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100961 // Reuse current operating mode and session parameters for new stream config
962 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 if (res != OK) {
964 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
965 __FUNCTION__, mNextStreamId, strerror(-res), res);
966 return res;
967 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700968 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700969 }
970
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700972 return OK;
973}
974
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700975status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700976 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700977 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800978 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800979 const std::unordered_set<int32_t> &sensorPixelModesUsed,
980 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Emilian Peevc81a7592022-02-14 17:38:18 -0800981 uint64_t consumerUsage, int64_t dynamicRangeProfile, int streamUseCase,
982 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700983 ATRACE_CALL();
984
985 if (consumer == nullptr) {
986 ALOGE("%s: consumer must not be null", __FUNCTION__);
987 return BAD_VALUE;
988 }
989
990 std::vector<sp<Surface>> consumers;
991 consumers.push_back(consumer);
992
993 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800994 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800995 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800996 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800997}
998
999static bool isRawFormat(int format) {
1000 switch (format) {
1001 case HAL_PIXEL_FORMAT_RAW16:
1002 case HAL_PIXEL_FORMAT_RAW12:
1003 case HAL_PIXEL_FORMAT_RAW10:
1004 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1005 return true;
1006 default:
1007 return false;
1008 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001009}
1010
1011status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1012 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001013 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001014 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001015 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Emilian Peevc81a7592022-02-14 17:38:18 -08001016 uint64_t consumerUsage, int64_t dynamicRangeProfile, int streamUseCase, int timestampBase,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001017 int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001018 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001019
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001020 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001021 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001022 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001023 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001024 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Emilian Peevc81a7592022-02-14 17:38:18 -08001025 " dynamicRangeProfile %" PRIx64 ", streamUseCase %d, timestampBase %d, mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001026 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001027 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001028 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001029
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001030 status_t res;
1031 bool wasActive = false;
1032
1033 switch (mStatus) {
1034 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001035 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001036 return INVALID_OPERATION;
1037 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001038 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001039 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001040 case STATUS_UNCONFIGURED:
1041 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001042 // OK
1043 break;
1044 case STATUS_ACTIVE:
1045 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001046 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001048 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001049 return res;
1050 }
1051 wasActive = true;
1052 break;
1053 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001054 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 return INVALID_OPERATION;
1056 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001057 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058
1059 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 if (consumers.size() == 0 && !hasDeferredConsumer) {
1062 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1063 return BAD_VALUE;
1064 }
Zhijun He5d677d12016-05-29 16:52:39 -07001065
Shuzhen Wang0129d522016-10-30 22:43:41 -07001066 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001067 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1068 return BAD_VALUE;
1069 }
1070
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001071 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1072 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1073 // be found in only one sensor pixel mode.
1074 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1075 return BAD_VALUE;
1076 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001077 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001078 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001079 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001080 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001081 if (blobBufferSize <= 0) {
1082 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1083 return BAD_VALUE;
1084 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001085 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1086 blobBufferSize = width * height;
1087 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001088 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001089 if (blobBufferSize <= 0) {
1090 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1091 return BAD_VALUE;
1092 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001093 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001094 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001095 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001096 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001097 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001098 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001099 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001100 bool maxResolution =
1101 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1102 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001103 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1104 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001105 if (rawOpaqueBufferSize <= 0) {
1106 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1107 return BAD_VALUE;
1108 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001109 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001110 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001111 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001112 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001113 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001114 } else if (isShared) {
1115 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1116 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001117 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001118 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001119 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001121 newStream = new Camera3OutputStream(mNextStreamId,
1122 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001123 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001124 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001125 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001126 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001127 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001128 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001129 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001130 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001131 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001132 }
Emilian Peev40ead602017-09-26 15:46:36 +01001133
1134 size_t consumerCount = consumers.size();
1135 for (size_t i = 0; i < consumerCount; i++) {
1136 int id = newStream->getSurfaceId(consumers[i]);
1137 if (id < 0) {
1138 SET_ERR_L("Invalid surface id");
1139 return BAD_VALUE;
1140 }
1141 if (surfaceIds != nullptr) {
1142 surfaceIds->push_back(id);
1143 }
1144 }
1145
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001146 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001147
Emilian Peev08dd2452017-04-06 16:55:14 +01001148 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001149
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001150 newStream->setImageDumpMask(mImageDumpMask);
1151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152 res = mOutputStreams.add(mNextStreamId, newStream);
1153 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001154 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001155 return res;
1156 }
1157
Shuzhen Wang316781a2020-08-18 18:11:01 -07001158 mSessionStatsBuilder.addStream(mNextStreamId);
1159
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001160 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001161 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001162
1163 // Continue captures if active at start
1164 if (wasActive) {
1165 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001166 // Reuse current operating mode and session parameters for new stream config
1167 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001168 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001169 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1170 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 return res;
1172 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001173 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001174 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001175 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177}
1178
Emilian Peev710c1422017-08-30 11:19:38 +01001179status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001181 if (nullptr == streamInfo) {
1182 return BAD_VALUE;
1183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001186
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 switch (mStatus) {
1188 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001189 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190 return INVALID_OPERATION;
1191 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001192 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001194 case STATUS_UNCONFIGURED:
1195 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 case STATUS_ACTIVE:
1197 // OK
1198 break;
1199 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 return INVALID_OPERATION;
1202 }
1203
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001204 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1205 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001206 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001207 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 }
1209
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001210 streamInfo->width = stream->getWidth();
1211 streamInfo->height = stream->getHeight();
1212 streamInfo->format = stream->getFormat();
1213 streamInfo->dataSpace = stream->getDataSpace();
1214 streamInfo->formatOverridden = stream->isFormatOverridden();
1215 streamInfo->originalFormat = stream->getOriginalFormat();
1216 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1217 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001218 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
1222status_t Camera3Device::setStreamTransform(int id,
1223 int transform) {
1224 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001227
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 switch (mStatus) {
1229 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001230 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 return INVALID_OPERATION;
1232 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 case STATUS_UNCONFIGURED:
1236 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 case STATUS_ACTIVE:
1238 // OK
1239 break;
1240 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 }
1244
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001245 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1246 if (stream == nullptr) {
1247 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return BAD_VALUE;
1249 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001250 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251}
1252
1253status_t Camera3Device::deleteStream(int id) {
1254 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001255 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 Mutex::Autolock l(mLock);
1257 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001258
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001259 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001260
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 // CameraDevice semantics require device to already be idle before
1262 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001264 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001265 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 }
1267
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001268 if (mStatus == STATUS_ERROR) {
1269 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1270 __FUNCTION__, mId.string());
1271 return -EBUSY;
1272 }
1273
Igor Murashkin2fba5842013-04-22 14:03:54 -07001274 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001275 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001276 if (mInputStream != NULL && id == mInputStream->getId()) {
1277 deletedStream = mInputStream;
1278 mInputStream.clear();
1279 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001280 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001281 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 return BAD_VALUE;
1283 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001284 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001285 }
1286
1287 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001288 if (stream != nullptr) {
1289 deletedStream = stream;
1290 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291 }
1292
1293 // Free up the stream endpoint so that it can be used by some other stream
1294 res = deletedStream->disconnect();
1295 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001296 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001297 // fall through since we want to still list the stream as deleted.
1298 }
1299 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001300 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001301
1302 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001303}
1304
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001305status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001306 ATRACE_CALL();
1307 ALOGV("%s: E", __FUNCTION__);
1308
1309 Mutex::Autolock il(mInterfaceLock);
1310 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001311
Emilian Peev811d2952018-05-25 11:08:40 +01001312 // In case the client doesn't include any session parameter, try a
1313 // speculative configuration using the values from the last cached
1314 // default request.
1315 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001316 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001317 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1318 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1319 mLastTemplateId);
1320 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1321 operatingMode);
1322 }
1323
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001324 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1325}
1326
1327status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1328 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001329 //Filter out any incoming session parameters
1330 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001331 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1332 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001333 CameraMetadata filteredParams(availableSessionKeys.count);
1334 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1335 filteredParams.getAndLock());
1336 set_camera_metadata_vendor_id(meta, mVendorTagId);
1337 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001338 if (availableSessionKeys.count > 0) {
1339 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1340 camera_metadata_ro_entry entry = params.find(
1341 availableSessionKeys.data.i32[i]);
1342 if (entry.count > 0) {
1343 filteredParams.update(entry);
1344 }
1345 }
1346 }
1347
1348 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001349}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001350
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001351status_t Camera3Device::getInputBufferProducer(
1352 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001353 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001354 Mutex::Autolock il(mInterfaceLock);
1355 Mutex::Autolock l(mLock);
1356
1357 if (producer == NULL) {
1358 return BAD_VALUE;
1359 } else if (mInputStream == NULL) {
1360 return INVALID_OPERATION;
1361 }
1362
1363 return mInputStream->getInputBufferProducer(producer);
1364}
1365
Emilian Peevf4816702020-04-03 15:44:51 -07001366status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001367 CameraMetadata *request) {
1368 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001369 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001370
Emilian Peevf4816702020-04-03 15:44:51 -07001371 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001372 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001373 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001374 return BAD_VALUE;
1375 }
1376
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001377 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001379 {
1380 Mutex::Autolock l(mLock);
1381 switch (mStatus) {
1382 case STATUS_ERROR:
1383 CLOGE("Device has encountered a serious error");
1384 return INVALID_OPERATION;
1385 case STATUS_UNINITIALIZED:
1386 CLOGE("Device is not initialized!");
1387 return INVALID_OPERATION;
1388 case STATUS_UNCONFIGURED:
1389 case STATUS_CONFIGURED:
1390 case STATUS_ACTIVE:
1391 // OK
1392 break;
1393 default:
1394 SET_ERR_L("Unexpected status: %d", mStatus);
1395 return INVALID_OPERATION;
1396 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001397
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001398 if (!mRequestTemplateCache[templateId].isEmpty()) {
1399 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001400 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001401 return OK;
1402 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001403 }
1404
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001405 camera_metadata_t *rawRequest;
1406 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001407 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001408
1409 {
1410 Mutex::Autolock l(mLock);
1411 if (res == BAD_VALUE) {
1412 ALOGI("%s: template %d is not supported on this camera device",
1413 __FUNCTION__, templateId);
1414 return res;
1415 } else if (res != OK) {
1416 CLOGE("Unable to construct request template %d: %s (%d)",
1417 templateId, strerror(-res), res);
1418 return res;
1419 }
1420
1421 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1422 mRequestTemplateCache[templateId].acquire(rawRequest);
1423
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001424 // Override the template request with zoomRatioMapper
1425 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1426 &mRequestTemplateCache[templateId]);
1427 if (res != OK) {
1428 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1429 templateId, strerror(-res), res);
1430 return res;
1431 }
1432
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001433 // Fill in JPEG_QUALITY if not available
1434 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1435 static const uint8_t kDefaultJpegQuality = 95;
1436 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1437 &kDefaultJpegQuality, 1);
1438 }
1439
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001440 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001441 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001442 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001443 return OK;
1444}
1445
1446status_t Camera3Device::waitUntilDrained() {
1447 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001449 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001451
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001452 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001453}
1454
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001455status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 switch (mStatus) {
1457 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001458 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 ALOGV("%s: Already idle", __FUNCTION__);
1460 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001461 case STATUS_CONFIGURED:
1462 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 case STATUS_ERROR:
1464 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001465 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 break;
1467 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001468 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return INVALID_OPERATION;
1470 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001471 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1472 maxExpectedDuration);
1473 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001474 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001475 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001476 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1477 res);
1478 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001479 return res;
1480}
1481
Ruben Brunk183f0562015-08-12 12:55:02 -07001482void Camera3Device::internalUpdateStatusLocked(Status status) {
1483 mStatus = status;
1484 mRecentStatusUpdates.add(mStatus);
1485 mStatusChanged.broadcast();
1486}
1487
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001489status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001490 if (mRequestThread.get() != nullptr) {
1491 mRequestThread->setPaused(true);
1492 } else {
1493 return NO_INIT;
1494 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001496 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1497 maxExpectedDuration);
1498 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 if (res != OK) {
1500 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001501 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 }
1503
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 return res;
1505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001507// Resume after internalPauseAndWaitLocked
1508status_t Camera3Device::internalResumeLocked() {
1509 status_t res;
1510
1511 mRequestThread->setPaused(false);
1512
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001513 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1514 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1516 if (res != OK) {
1517 SET_ERR_L("Can't transition to active in %f seconds!",
1518 kActiveTimeout/1e9);
1519 }
1520 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522}
1523
Ruben Brunk183f0562015-08-12 12:55:02 -07001524status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001526
1527 size_t startIndex = 0;
1528 if (mStatusWaiters == 0) {
1529 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1530 // this status list
1531 mRecentStatusUpdates.clear();
1532 } else {
1533 // If other threads are waiting on updates to this status list, set the position of the
1534 // first element that this list will check rather than clearing the list.
1535 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 }
1537
Ruben Brunk183f0562015-08-12 12:55:02 -07001538 mStatusWaiters++;
1539
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001540 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001541 if (!active && mUseHalBufManager) {
1542 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001543 if (mStatus == STATUS_ACTIVE) {
1544 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001545 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001546 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001547 mRequestBufferSM.onWaitUntilIdle();
1548 }
1549
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 bool stateSeen = false;
1551 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001552 if (active == (mStatus == STATUS_ACTIVE)) {
1553 // Desired state is current
1554 break;
1555 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556
1557 res = mStatusChanged.waitRelative(mLock, timeout);
1558 if (res != OK) break;
1559
Ruben Brunk183f0562015-08-12 12:55:02 -07001560 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1561 // transitions.
1562 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1563 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1564 __FUNCTION__);
1565
1566 // Encountered desired state since we began waiting
1567 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1569 stateSeen = true;
1570 break;
1571 }
1572 }
1573 } while (!stateSeen);
1574
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001575 if (signalPipelineDrain) {
1576 mRequestThread->resetPipelineDrain();
1577 }
1578
Ruben Brunk183f0562015-08-12 12:55:02 -07001579 mStatusWaiters--;
1580
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001581 return res;
1582}
1583
1584
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001585status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001587 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001589 if (listener != NULL && mListener != NULL) {
1590 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1591 }
1592 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001593 mRequestThread->setNotificationListener(listener);
1594 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001595
1596 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597}
1598
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001599bool Camera3Device::willNotify3A() {
1600 return false;
1601}
1602
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001604 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001605 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001606
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001607 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001608 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1609 if (st == std::cv_status::timeout) {
1610 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001611 }
1612 }
1613 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614}
1615
Jianing Weicb0652e2014-03-12 18:29:36 -07001616status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001618 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001620 if (mResultQueue.empty()) {
1621 return NOT_ENOUGH_DATA;
1622 }
1623
Jianing Weicb0652e2014-03-12 18:29:36 -07001624 if (frame == NULL) {
1625 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1626 return BAD_VALUE;
1627 }
1628
1629 CaptureResult &result = *(mResultQueue.begin());
1630 frame->mResultExtras = result.mResultExtras;
1631 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001632 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001633 mResultQueue.erase(mResultQueue.begin());
1634
1635 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001636}
1637
1638status_t Camera3Device::triggerAutofocus(uint32_t id) {
1639 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001640 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001641
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001642 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1643 // Mix-in this trigger into the next request and only the next request.
1644 RequestTrigger trigger[] = {
1645 {
1646 ANDROID_CONTROL_AF_TRIGGER,
1647 ANDROID_CONTROL_AF_TRIGGER_START
1648 },
1649 {
1650 ANDROID_CONTROL_AF_TRIGGER_ID,
1651 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001652 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001653 };
1654
1655 return mRequestThread->queueTrigger(trigger,
1656 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001657}
1658
1659status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1660 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001663 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1664 // Mix-in this trigger into the next request and only the next request.
1665 RequestTrigger trigger[] = {
1666 {
1667 ANDROID_CONTROL_AF_TRIGGER,
1668 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1669 },
1670 {
1671 ANDROID_CONTROL_AF_TRIGGER_ID,
1672 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001673 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001674 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001676 return mRequestThread->queueTrigger(trigger,
1677 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001678}
1679
1680status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1681 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001682 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001683
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001684 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1685 // Mix-in this trigger into the next request and only the next request.
1686 RequestTrigger trigger[] = {
1687 {
1688 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1689 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1690 },
1691 {
1692 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1693 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001694 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001695 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001696
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 return mRequestThread->queueTrigger(trigger,
1698 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001699}
1700
Jianing Weicb0652e2014-03-12 18:29:36 -07001701status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001702 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001703 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001705
Zhijun He7ef20392014-04-21 16:04:17 -07001706 {
1707 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001708
1709 // b/116514106 "disconnect()" can get called twice for the same device. The
1710 // camera device will not be initialized during the second run.
1711 if (mStatus == STATUS_UNINITIALIZED) {
1712 return OK;
1713 }
1714
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001715 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001716
1717 // Stop session and stream counter
1718 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001719 }
1720
Emilian Peev08dd2452017-04-06 16:55:14 +01001721 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001722}
1723
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001724status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001725 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1726}
1727
1728status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001729 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001730 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001731 Mutex::Autolock il(mInterfaceLock);
1732 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001733
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001734 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1735 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001736 CLOGE("Stream %d does not exist", streamId);
1737 return BAD_VALUE;
1738 }
1739
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001741 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001742 return BAD_VALUE;
1743 }
1744
1745 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001746 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001747 return BAD_VALUE;
1748 }
1749
Ruben Brunkc78ac262015-08-13 17:58:46 -07001750 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001751}
1752
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001753status_t Camera3Device::tearDown(int streamId) {
1754 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001755 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001756 Mutex::Autolock il(mInterfaceLock);
1757 Mutex::Autolock l(mLock);
1758
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001759 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1760 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001761 CLOGE("Stream %d does not exist", streamId);
1762 return BAD_VALUE;
1763 }
1764
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001765 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1766 CLOGE("Stream %d is a target of a in-progress request", streamId);
1767 return BAD_VALUE;
1768 }
1769
1770 return stream->tearDown();
1771}
1772
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001773status_t Camera3Device::addBufferListenerForStream(int streamId,
1774 wp<Camera3StreamBufferListener> listener) {
1775 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001776 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001777 Mutex::Autolock il(mInterfaceLock);
1778 Mutex::Autolock l(mLock);
1779
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001780 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1781 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001782 CLOGE("Stream %d does not exist", streamId);
1783 return BAD_VALUE;
1784 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001785 stream->addBufferListener(listener);
1786
1787 return OK;
1788}
1789
Austin Borger4a870a32022-02-25 01:48:41 +00001790float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1791 camera_metadata_entry minDurations =
1792 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1793 for (size_t i = 0; i < minDurations.count; i += 4) {
1794 if (minDurations.data.i64[i] == stream->getFormat()
1795 && minDurations.data.i64[i+1] == stream->getWidth()
1796 && minDurations.data.i64[i+2] == stream->getHeight()) {
1797 int64_t minFrameDuration = minDurations.data.i64[i+3];
1798 return 1e9f / minFrameDuration;
1799 }
1800 }
1801 return 0.0f;
1802}
1803
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001804/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001805 * Methods called by subclasses
1806 */
1807
1808void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001809 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001810 std::vector<int> streamIds;
1811 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001812 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 {
1815 // Need mLock to safely update state and synchronize to current
1816 // state of methods in flight.
1817 Mutex::Autolock l(mLock);
1818 // We can get various system-idle notices from the status tracker
1819 // while starting up. Only care about them if we've actually sent
1820 // in some requests recently.
1821 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1822 return;
1823 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001824 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1825 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001826 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827
1828 // Skip notifying listener if we're doing some user-transparent
1829 // state changes
1830 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001831
Austin Borger4a870a32022-02-25 01:48:41 +00001832 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1833 auto stream = mOutputStreams[i];
1834 if (stream.get() == nullptr) continue;
1835
1836 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1837 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1838
1839 // Populate stream statistics in case of Idle
1840 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001841 streamIds.push_back(stream->getId());
1842 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1843 int64_t usage = 0LL;
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001844 int streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001845 if (camera3Stream != nullptr) {
1846 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001847 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001848 }
1849 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001850 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001851 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001852 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001853 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001854 }
1855 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001857
1858 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001859 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001860 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001861 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001863 status_t res = OK;
1864 if (listener != nullptr) {
1865 if (idle) {
1866 // Get session stats from the builder, and notify the listener.
1867 int64_t requestCount, resultErrorCount;
1868 bool deviceError;
1869 std::map<int, StreamStats> streamStatsMap;
1870 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1871 &deviceError, &streamStatsMap);
1872 for (size_t i = 0; i < streamIds.size(); i++) {
1873 int streamId = streamIds[i];
1874 auto stats = streamStatsMap.find(streamId);
1875 if (stats != streamStatsMap.end()) {
1876 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1877 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1878 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1879 streamStats[i].mHistogramType =
1880 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1881 streamStats[i].mHistogramBins.assign(
1882 stats->second.mCaptureLatencyBins.begin(),
1883 stats->second.mCaptureLatencyBins.end());
1884 streamStats[i].mHistogramCounts.assign(
1885 stats->second.mCaptureLatencyHistogram.begin(),
1886 stats->second.mCaptureLatencyHistogram.end());
1887 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001888 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001889 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1890 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001891 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001892 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001893 }
1894 if (res != OK) {
1895 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1896 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001897 }
1898}
1899
Shuzhen Wang758c2152017-01-10 18:26:18 -08001900status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001901 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001902 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001903 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1904 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001905
1906 if (surfaceIds == nullptr) {
1907 return BAD_VALUE;
1908 }
1909
Zhijun He5d677d12016-05-29 16:52:39 -07001910 Mutex::Autolock il(mInterfaceLock);
1911 Mutex::Autolock l(mLock);
1912
Shuzhen Wang758c2152017-01-10 18:26:18 -08001913 if (consumers.size() == 0) {
1914 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001915 return BAD_VALUE;
1916 }
1917
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001918 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1919 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001920 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001921 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001922 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001923
1924 // isConsumerConfigurationDeferred will be off after setConsumers
1925 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001926 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001927 if (res != OK) {
1928 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1929 return res;
1930 }
1931
Emilian Peev40ead602017-09-26 15:46:36 +01001932 for (auto &consumer : consumers) {
1933 int id = stream->getSurfaceId(consumer);
1934 if (id < 0) {
1935 CLOGE("Invalid surface id!");
1936 return BAD_VALUE;
1937 }
1938 surfaceIds->push_back(id);
1939 }
1940
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001941 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001942 if (!stream->isConfiguring()) {
1943 CLOGE("Stream %d was already fully configured.", streamId);
1944 return INVALID_OPERATION;
1945 }
Zhijun He5d677d12016-05-29 16:52:39 -07001946
Shuzhen Wang0129d522016-10-30 22:43:41 -07001947 res = stream->finishConfiguration();
1948 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001949 // If finishConfiguration fails due to abandoned surface, do not set
1950 // device to error state.
1951 bool isSurfaceAbandoned =
1952 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1953 if (!isSurfaceAbandoned) {
1954 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1955 stream->getId(), strerror(-res), res);
1956 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001957 return res;
1958 }
Zhijun He5d677d12016-05-29 16:52:39 -07001959 }
1960
1961 return OK;
1962}
1963
Emilian Peev40ead602017-09-26 15:46:36 +01001964status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1965 const std::vector<OutputStreamInfo> &outputInfo,
1966 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1967 Mutex::Autolock il(mInterfaceLock);
1968 Mutex::Autolock l(mLock);
1969
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001970 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1971 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001972 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001973 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001974 }
1975
1976 for (const auto &it : removedSurfaceIds) {
1977 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1978 CLOGE("Shared surface still part of a pending request!");
1979 return -EBUSY;
1980 }
1981 }
1982
Emilian Peev40ead602017-09-26 15:46:36 +01001983 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1984 if (res != OK) {
1985 CLOGE("Stream %d failed to update stream (error %d %s) ",
1986 streamId, res, strerror(-res));
1987 if (res == UNKNOWN_ERROR) {
1988 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1989 __FUNCTION__);
1990 }
1991 return res;
1992 }
1993
1994 return res;
1995}
1996
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001997status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1998 Mutex::Autolock il(mInterfaceLock);
1999 Mutex::Autolock l(mLock);
2000
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002001 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2002 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002003 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2004 return BAD_VALUE;
2005 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002006
2007 if (dropping) {
2008 mSessionStatsBuilder.stopCounter(streamId);
2009 } else {
2010 mSessionStatsBuilder.startCounter(streamId);
2011 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002012 return stream->dropBuffers(dropping);
2013}
2014
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002015/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016 * Camera3Device private methods
2017 */
2018
2019sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002020 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002021 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002023 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002024 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002025
2026 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002027 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002028 if (inputStreams.count > 0) {
2029 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002030 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002031 CLOGE("Request references unknown input stream %d",
2032 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002033 return NULL;
2034 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002035
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002036 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002037 SET_ERR_L("%s: input stream %d is not configured!",
2038 __FUNCTION__, mInputStream->getId());
2039 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002041 // Check if stream prepare is blocking requests.
2042 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002043 CLOGE("Request references an input stream that's being prepared!");
2044 return NULL;
2045 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046
2047 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002048 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049 }
2050
2051 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002052 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002054 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002055 return NULL;
2056 }
2057
2058 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002059 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2060 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002061 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002062 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063 return NULL;
2064 }
Zhijun He5d677d12016-05-29 16:52:39 -07002065 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002066 auto iter = surfaceMap.find(streams.data.i32[i]);
2067 if (iter != surfaceMap.end()) {
2068 const std::vector<size_t>& surfaces = iter->second;
2069 for (const auto& surface : surfaces) {
2070 if (stream->isConsumerConfigurationDeferred(surface)) {
2071 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2072 "due to deferred consumer", stream->getId(), surface);
2073 return NULL;
2074 }
2075 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002076 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002077 }
2078
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002080 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2081 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002082 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002083 // Check if stream prepare is blocking requests.
2084 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002085 CLOGE("Request references an output stream that's being prepared!");
2086 return NULL;
2087 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088
2089 newRequest->mOutputStreams.push(stream);
2090 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002091 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002092 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002094 auto rotateAndCropEntry =
2095 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2096 if (rotateAndCropEntry.count > 0 &&
2097 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2098 newRequest->mRotateAndCropAuto = true;
2099 } else {
2100 newRequest->mRotateAndCropAuto = false;
2101 }
2102
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002103 auto zoomRatioEntry =
2104 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2105 if (zoomRatioEntry.count > 0 &&
2106 zoomRatioEntry.data.f[0] == 1.0f) {
2107 newRequest->mZoomRatioIs1x = true;
2108 } else {
2109 newRequest->mZoomRatioIs1x = false;
2110 }
2111
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002112 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002113 for (auto& settings : newRequest->mSettingsList) {
2114 auto testPatternModeEntry =
2115 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2116 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2117 testPatternModeEntry.data.i32[0] :
2118 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002119
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002120 auto testPatternDataEntry =
2121 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2122 if (testPatternDataEntry.count >= 4) {
2123 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2124 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2125 } else {
2126 settings.mOriginalTestPatternData[0] = 0;
2127 settings.mOriginalTestPatternData[1] = 0;
2128 settings.mOriginalTestPatternData[2] = 0;
2129 settings.mOriginalTestPatternData[3] = 0;
2130 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002131 }
2132 }
2133
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002134 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002135}
2136
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002137void Camera3Device::cancelStreamsConfigurationLocked() {
2138 int res = OK;
2139 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2140 res = mInputStream->cancelConfiguration();
2141 if (res != OK) {
2142 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2143 mInputStream->getId(), strerror(-res), res);
2144 }
2145 }
2146
2147 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002148 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002149 if (outputStream->isConfiguring()) {
2150 res = outputStream->cancelConfiguration();
2151 if (res != OK) {
2152 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2153 outputStream->getId(), strerror(-res), res);
2154 }
2155 }
2156 }
2157
2158 // Return state to that at start of call, so that future configures
2159 // properly clean things up
2160 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2161 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002162
2163 res = mPreparerThread->resume();
2164 if (res != OK) {
2165 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2166 }
2167}
2168
Emilian Peev0d0191e2020-04-21 17:01:18 -07002169bool Camera3Device::checkAbandonedStreamsLocked() {
2170 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2171 return true;
2172 }
2173
2174 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2175 auto stream = mOutputStreams[i];
2176 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2177 return true;
2178 }
2179 }
2180
2181 return false;
2182}
2183
Emilian Peev3bead5f2020-05-28 17:29:08 -07002184bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002185 ATRACE_CALL();
2186 bool ret = false;
2187
Shuzhen Wang316781a2020-08-18 18:11:01 -07002188 nsecs_t startTime = systemTime();
2189
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002190 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002191 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2192
2193 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002194 if (checkAbandonedStreamsLocked()) {
2195 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2196 __FUNCTION__);
2197 return true;
2198 }
2199
Emilian Peev3bead5f2020-05-28 17:29:08 -07002200 status_t rc = NO_ERROR;
2201 bool markClientActive = false;
2202 if (mStatus == STATUS_ACTIVE) {
2203 markClientActive = true;
2204 mPauseStateNotify = true;
2205 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2206
2207 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2208 }
2209
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002210 if (rc == NO_ERROR) {
2211 mNeedConfig = true;
2212 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2213 if (rc == NO_ERROR) {
2214 ret = true;
2215 mPauseStateNotify = false;
2216 //Moving to active state while holding 'mLock' is important.
2217 //There could be pending calls to 'create-/deleteStream' which
2218 //will trigger another stream configuration while the already
2219 //present streams end up with outstanding buffers that will
2220 //not get drained.
2221 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002222 } else if (rc == DEAD_OBJECT) {
2223 // DEAD_OBJECT can be returned if either the consumer surface is
2224 // abandoned, or the HAL has died.
2225 // - If the HAL has died, configureStreamsLocked call will set
2226 // device to error state,
2227 // - If surface is abandoned, we should not set device to error
2228 // state.
2229 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002230 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002231 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002232 }
2233 } else {
2234 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2235 }
2236
Shuzhen Wang316781a2020-08-18 18:11:01 -07002237 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2238 ns2ms(systemTime() - startTime));
2239
Emilian Peev3bead5f2020-05-28 17:29:08 -07002240 if (markClientActive) {
2241 mStatusTracker->markComponentActive(clientStatusId);
2242 }
2243
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002244 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002245}
2246
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002247status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002248 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 ATRACE_CALL();
2250 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002251
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002252 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002253 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 return INVALID_OPERATION;
2255 }
2256
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002257 if (operatingMode < 0) {
2258 CLOGE("Invalid operating mode: %d", operatingMode);
2259 return BAD_VALUE;
2260 }
2261
2262 bool isConstrainedHighSpeed =
2263 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2264 operatingMode;
2265
2266 if (mOperatingMode != operatingMode) {
2267 mNeedConfig = true;
2268 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2269 mOperatingMode = operatingMode;
2270 }
2271
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002272 // In case called from configureStreams, abort queued input buffers not belonging to
2273 // any pending requests.
2274 if (mInputStream != NULL && notifyRequestThread) {
2275 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002276 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002277 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002278 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002279 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002280 if (res != OK) {
2281 // Exhausted acquiring all input buffers.
2282 break;
2283 }
2284
Emilian Peevf4816702020-04-03 15:44:51 -07002285 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002286 res = mInputStream->returnInputBuffer(inputBuffer);
2287 if (res != OK) {
2288 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2289 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2290 }
2291 }
2292 }
2293
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002294 if (!mNeedConfig) {
2295 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2296 return OK;
2297 }
2298
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002299 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002300 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002301 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2302 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002303 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002304 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002305 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002306 }
2307
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002309 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002311 mPreparerThread->pause();
2312
Emilian Peevf4816702020-04-03 15:44:51 -07002313 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002314 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002315 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002316 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317
Emilian Peevf4816702020-04-03 15:44:51 -07002318 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002320 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002321
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002322
2323 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002324 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325 inputStream = mInputStream->startConfiguration();
2326 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002327 CLOGE("Can't start input stream configuration");
2328 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002329 return INVALID_OPERATION;
2330 }
2331 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002332
2333 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002334 }
2335
Shuzhen Wang99080502021-03-07 21:08:20 -08002336 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002337 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002338 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002339
2340 // Don't configure bidi streams twice, nor add them twice to the list
2341 if (mOutputStreams[i].get() ==
2342 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2343
2344 config.num_streams--;
2345 continue;
2346 }
2347
Emilian Peevf4816702020-04-03 15:44:51 -07002348 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002349 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002351 CLOGE("Can't start output stream configuration");
2352 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002353 return INVALID_OPERATION;
2354 }
2355 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002356
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002357 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002358 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2359 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002360 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2361 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002362 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2363 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002364 } else if (outputStream->data_space ==
2365 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2366 bufferSizes[k] = outputStream->width * outputStream->height;
2367 } else {
2368 ALOGW("%s: Blob dataSpace %d not supported",
2369 __FUNCTION__, outputStream->data_space);
2370 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002371 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002372
2373 if (mOutputStreams[i]->isMultiResolution()) {
2374 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2375 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2376 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2377 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002378
2379 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2380 composerSurfacePresent = true;
2381 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 }
2383
2384 config.streams = streams.editArray();
2385
2386 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002387 // max_buffers, usage, and priv fields, as well as data_space and format
2388 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002389
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002390 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002391 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002392 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002394 if (res == BAD_VALUE) {
2395 // HAL rejected this set of streams as unsupported, clean up config
2396 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002397 CLOGE("Set of requested inputs/outputs not supported by HAL");
2398 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002399 return BAD_VALUE;
2400 } else if (res != OK) {
2401 // Some other kind of error from configure_streams - this is not
2402 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002403 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2404 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002405 return res;
2406 }
2407
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002408 // Finish all stream configuration immediately.
2409 // TODO: Try to relax this later back to lazy completion, which should be
2410 // faster
2411
Igor Murashkin073f8572013-05-02 14:59:28 -07002412 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002413 bool streamReConfigured = false;
2414 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002415 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002416 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002417 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002418 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002419 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2420 return DEAD_OBJECT;
2421 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002422 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002423 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002424 if (streamReConfigured) {
2425 mInterface->onStreamReConfigured(mInputStream->getId());
2426 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002427 }
2428
2429 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002430 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002431 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002432 bool streamReConfigured = false;
2433 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002434 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002435 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002436 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002437 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002438 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2439 return DEAD_OBJECT;
2440 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002441 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002442 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002443 if (streamReConfigured) {
2444 mInterface->onStreamReConfigured(outputStream->getId());
2445 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002446 }
2447 }
2448
Emilian Peeve23f1d92021-09-20 14:56:01 -07002449 mRequestThread->setComposerSurface(composerSurfacePresent);
2450
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002451 // Request thread needs to know to avoid using repeat-last-settings protocol
2452 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002453 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002454 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2455 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002456 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457
Zhijun He90f7c372016-08-16 16:19:43 -07002458 char value[PROPERTY_VALUE_MAX];
2459 property_get("camera.fifo.disable", value, "0");
2460 int32_t disableFifo = atoi(value);
2461 if (disableFifo != 1) {
2462 // Boost priority of request thread to SCHED_FIFO.
2463 pid_t requestThreadTid = mRequestThread->getTid();
2464 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002465 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002466 if (res != OK) {
2467 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2468 strerror(-res), res);
2469 } else {
2470 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2471 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002472 }
2473
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002474 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002475 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2476 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2477 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2478 sessionParams.unlock(newSessionParams);
2479 mSessionParams.unlock(currentSessionParams);
2480 if (updateSessionParams) {
2481 mSessionParams = sessionParams;
2482 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002483
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002484 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002485
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002486 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002487 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002488
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002489 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002490
Zhijun He0a210512014-07-24 13:45:15 -07002491 // tear down the deleted streams after configure streams.
2492 mDeletedStreams.clear();
2493
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002494 auto rc = mPreparerThread->resume();
2495 if (rc != OK) {
2496 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2497 return rc;
2498 }
2499
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002500 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002501 mRequestBufferSM.onStreamsConfigured();
2502 }
2503
Cliff Wu3b268182021-07-06 15:44:43 +08002504 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002505 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002506 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002507 // configure the injection streams.
2508 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002509 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002510 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2511 res = mInjectionMethods->injectCamera(config, bufferSizes);
2512 if (res != OK) {
2513 ALOGE("Can't finish inject camera process!");
2514 return res;
2515 }
Cliff Wu3b268182021-07-06 15:44:43 +08002516 } else {
2517 // First run configureStreamsLocked() and then call injectCamera() case:
2518 // If the stream configuration has been completed and camera deive is active, but the
2519 // injection camera has not been injected yet, we need to store the stream configuration of
2520 // the internal camera (because the stream configuration of the injection camera is based
2521 // on the internal camera). When injecting occurs later, this configuration can be used by
2522 // the injection camera.
2523 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2524 " injection camera has not been injected yet.", __FUNCTION__);
2525 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002526 }
2527
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002528 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002529}
2530
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002531status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002532 ATRACE_CALL();
2533 status_t res;
2534
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002535 if (mFakeStreamId != NO_STREAM) {
2536 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002537 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002538 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002539 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002540 return INVALID_OPERATION;
2541 }
2542
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002543 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002544
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002545 sp<Camera3OutputStreamInterface> fakeStream =
2546 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002547
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002548 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002549 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002551 return res;
2552 }
2553
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002554 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002555 mNextStreamId++;
2556
2557 return OK;
2558}
2559
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002560status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002561 ATRACE_CALL();
2562 status_t res;
2563
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002564 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002565 if (mOutputStreams.size() == 1) return OK;
2566
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002567 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002568
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002569 // Ok, have a fake stream and there's at least one other output stream,
2570 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002571
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002572 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002573 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002574 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002575 return INVALID_OPERATION;
2576 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002577 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002578
2579 // Free up the stream endpoint so that it can be used by some other stream
2580 res = deletedStream->disconnect();
2581 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002582 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002583 // fall through since we want to still list the stream as deleted.
2584 }
2585 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002586 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002587
2588 return res;
2589}
2590
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002591void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002592 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002593 Mutex::Autolock l(mLock);
2594 va_list args;
2595 va_start(args, fmt);
2596
2597 setErrorStateLockedV(fmt, args);
2598
2599 va_end(args);
2600}
2601
2602void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002603 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002604 Mutex::Autolock l(mLock);
2605 setErrorStateLockedV(fmt, args);
2606}
2607
2608void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2609 va_list args;
2610 va_start(args, fmt);
2611
2612 setErrorStateLockedV(fmt, args);
2613
2614 va_end(args);
2615}
2616
2617void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002618 // Print out all error messages to log
2619 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002620 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002621
2622 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002623 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002624
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002625 mErrorCause = errorCause;
2626
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002627 if (mRequestThread != nullptr) {
2628 mRequestThread->setPaused(true);
2629 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002630 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002631
2632 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002633 sp<NotificationListener> listener = mListener.promote();
2634 if (listener != NULL) {
2635 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002636 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002637 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002638 }
2639
2640 // Save stack trace. View by dumping it later.
2641 CameraTraces::saveTrace();
2642 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002643}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644
2645/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002646 * In-flight request management
2647 */
2648
Jianing Weicb0652e2014-03-12 18:29:36 -07002649status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002650 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002651 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002652 const std::set<std::set<String8>>& physicalCameraIds,
2653 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2654 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002655 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002656 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002657 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002658
2659 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002660 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002661 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002662 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002663 if (res < 0) return res;
2664
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002665 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002666 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2667 // avoid a deadlock during reprocess requests.
2668 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002669 if (mStatusTracker != nullptr) {
2670 mStatusTracker->markComponentActive(mInFlightStatusId);
2671 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002672 }
2673
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002674 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002675 return OK;
2676}
2677
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002678void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002679 // Indicate idle inFlightMap to the status tracker
2680 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002681 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002682 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2683 // avoid a deadlock during reprocess requests.
2684 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002685 if (mStatusTracker != nullptr) {
2686 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2687 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002688 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002689 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002690}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002691
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002692void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002693 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002694 // something has likely gone wrong. This might still be legit only if application send in
2695 // a long burst of long exposure requests.
2696 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2697 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2698 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2699 mInFlightMap.size(), mExpectedInflightDuration);
2700 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2701 kInFlightWarnLimitHighSpeed) {
2702 CLOGW("In-flight list too large for high speed configuration: %zu,"
2703 "total inflight duration %" PRIu64,
2704 mInFlightMap.size(), mExpectedInflightDuration);
2705 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002706 }
2707}
2708
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002709void Camera3Device::onInflightMapFlushedLocked() {
2710 mExpectedInflightDuration = 0;
2711}
2712
2713void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002714 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002715 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2716 mInFlightMap.removeItemsAt(idx, 1);
2717
2718 onInflightEntryRemovedLocked(duration);
2719}
2720
2721
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002722void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002723 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002724 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002725 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002726 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002727 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002728 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002729
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002730 FlushInflightReqStates states {
2731 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002732 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002733
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002734 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002735}
2736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002737CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002738 ALOGV("%s", __FUNCTION__);
2739
Igor Murashkin1e479c02013-09-06 16:55:14 -07002740 CameraMetadata retVal;
2741
2742 if (mRequestThread != NULL) {
2743 retVal = mRequestThread->getLatestRequest();
2744 }
2745
Igor Murashkin1e479c02013-09-06 16:55:14 -07002746 return retVal;
2747}
2748
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002749void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002750 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002751 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002752 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2753 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002754
2755 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002756 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002757}
2758
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002759void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002760 std::vector<native_handle_t*> *handles, bool closeFd) {
2761 if (handles == nullptr) {
2762 return;
2763 }
2764 if (closeFd) {
2765 for (auto& handle : *handles) {
2766 native_handle_close(handle);
2767 }
2768 }
2769 for (auto& handle : *handles) {
2770 native_handle_delete(handle);
2771 }
2772 handles->clear();
2773 return;
2774}
2775
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002776/**
2777 * HalInterface inner class methods
2778 */
2779
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002780void Camera3Device::HalInterface::getInflightBufferKeys(
2781 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002782 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002783 return;
2784}
2785
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002786void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2787 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002788 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002789 return;
2790}
2791
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002792bool Camera3Device::HalInterface::verifyBufferIds(
2793 int32_t streamId, std::vector<uint64_t>& bufIds) {
2794 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002795}
2796
2797status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002798 int32_t frameNumber, int32_t streamId,
2799 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002801}
2802
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002803status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002804 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002805 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002806}
2807
2808// Find and pop a buffer_handle_t based on bufferId
2809status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002810 uint64_t bufferId,
2811 /*out*/ buffer_handle_t** buffer,
2812 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002813 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002814}
2815
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002816std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2817 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002818 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002819}
2820
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002821uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2822 const native_handle_t* handle) {
2823 return mBufferRecords.removeOneBufferCache(streamId, handle);
2824}
2825
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002826void Camera3Device::HalInterface::onBufferFreed(
2827 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002828 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2829 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2830 if (bufferId != BUFFER_ID_NO_BUFFER) {
2831 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002832 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002833}
2834
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002835void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002836 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2837 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2838 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002839 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2840 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002841}
2842
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002843/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002844 * RequestThread inner class methods
2845 */
2846
2847Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002848 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002849 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002850 bool useHalBufManager,
2851 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002852 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002854 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002855 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002856 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002857 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002858 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002859 mReconfigured(false),
2860 mDoPause(false),
2861 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002862 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002863 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002864 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002865 mCurrentAfTriggerId(0),
2866 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002867 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002868 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002869 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002870 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002871 mRepeatingLastFrameNumber(
2872 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002873 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002874 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002875 mRequestLatency(kRequestLatencyBinSize),
2876 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002877 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002878 mUseHalBufManager(useHalBufManager),
2879 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002880 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002881}
2882
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002883Camera3Device::RequestThread::~RequestThread() {}
2884
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002885void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002886 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002887 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002888 Mutex::Autolock l(mRequestLock);
2889 mListener = listener;
2890}
2891
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002892void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002893 const CameraMetadata& sessionParams,
2894 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002895 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002896 Mutex::Autolock l(mRequestLock);
2897 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002898 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002899 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002900 // Prepare video stream for high speed recording.
2901 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002902 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002903}
2904
Jianing Wei90e59c92014-03-12 18:29:36 -07002905status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002906 List<sp<CaptureRequest> > &requests,
2907 /*out*/
2908 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002909 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002910 Mutex::Autolock l(mRequestLock);
2911 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2912 ++it) {
2913 mRequestQueue.push_back(*it);
2914 }
2915
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002916 if (lastFrameNumber != NULL) {
2917 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2918 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2919 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2920 *lastFrameNumber);
2921 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002922
Jianing Wei90e59c92014-03-12 18:29:36 -07002923 unpauseForNewRequests();
2924
2925 return OK;
2926}
2927
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002928
2929status_t Camera3Device::RequestThread::queueTrigger(
2930 RequestTrigger trigger[],
2931 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002932 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002933 Mutex::Autolock l(mTriggerMutex);
2934 status_t ret;
2935
2936 for (size_t i = 0; i < count; ++i) {
2937 ret = queueTriggerLocked(trigger[i]);
2938
2939 if (ret != OK) {
2940 return ret;
2941 }
2942 }
2943
2944 return OK;
2945}
2946
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002947const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2948 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002949 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002950 if (d != nullptr) return d->mId;
2951 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952}
2953
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002954status_t Camera3Device::RequestThread::queueTriggerLocked(
2955 RequestTrigger trigger) {
2956
2957 uint32_t tag = trigger.metadataTag;
2958 ssize_t index = mTriggerMap.indexOfKey(tag);
2959
2960 switch (trigger.getTagType()) {
2961 case TYPE_BYTE:
2962 // fall-through
2963 case TYPE_INT32:
2964 break;
2965 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002966 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2967 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002968 return INVALID_OPERATION;
2969 }
2970
2971 /**
2972 * Collect only the latest trigger, since we only have 1 field
2973 * in the request settings per trigger tag, and can't send more than 1
2974 * trigger per request.
2975 */
2976 if (index != NAME_NOT_FOUND) {
2977 mTriggerMap.editValueAt(index) = trigger;
2978 } else {
2979 mTriggerMap.add(tag, trigger);
2980 }
2981
2982 return OK;
2983}
2984
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002985status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002986 const RequestList &requests,
2987 /*out*/
2988 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002989 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002990 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002991 if (lastFrameNumber != NULL) {
2992 *lastFrameNumber = mRepeatingLastFrameNumber;
2993 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002994 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002995 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002996 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2997 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002998
2999 unpauseForNewRequests();
3000
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003001 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003002 return OK;
3003}
3004
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003005bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003006 if (mRepeatingRequests.empty()) {
3007 return false;
3008 }
3009 int32_t requestId = requestIn->mResultExtras.requestId;
3010 const RequestList &repeatRequests = mRepeatingRequests;
3011 // All repeating requests are guaranteed to have same id so only check first quest
3012 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3013 return (firstRequest->mResultExtras.requestId == requestId);
3014}
3015
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003016status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003017 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003018 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003019 return clearRepeatingRequestsLocked(lastFrameNumber);
3020
3021}
3022
3023status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003024 std::vector<int32_t> streamIds;
3025 for (const auto& request : mRepeatingRequests) {
3026 for (const auto& stream : request->mOutputStreams) {
3027 streamIds.push_back(stream->getId());
3028 }
3029 }
3030
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003031 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003032 if (lastFrameNumber != NULL) {
3033 *lastFrameNumber = mRepeatingLastFrameNumber;
3034 }
Emilian Peev2295df72021-11-12 18:14:10 -08003035
3036 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3037
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003039 return OK;
3040}
3041
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003042status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003043 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003044 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003045 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003046 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003047
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003048 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003049
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003050 // Send errors for all requests pending in the request queue, including
3051 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003052 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003053 if (listener != NULL) {
3054 for (RequestList::iterator it = mRequestQueue.begin();
3055 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003056 // Abort the input buffers for reprocess requests.
3057 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003058 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003059 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003060 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003061 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003062 if (res != OK) {
3063 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3064 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3065 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003066 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003067 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3068 if (res != OK) {
3069 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3070 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3071 }
3072 }
3073 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003074 // Set the frame number this request would have had, if it
3075 // had been submitted; this frame number will not be reused.
3076 // The requestId and burstId fields were set when the request was
3077 // submitted originally (in convertMetadataListToRequestListLocked)
3078 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003079 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003080 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003081 }
3082 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003083 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003084
3085 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003086 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003087 if (lastFrameNumber != NULL) {
3088 *lastFrameNumber = mRepeatingLastFrameNumber;
3089 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003090 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003091 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003092 return OK;
3093}
3094
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003095status_t Camera3Device::RequestThread::flush() {
3096 ATRACE_CALL();
3097 Mutex::Autolock l(mFlushLock);
3098
Emilian Peev08dd2452017-04-06 16:55:14 +01003099 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003100}
3101
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003102void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003103 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003104 Mutex::Autolock l(mPauseLock);
3105 mDoPause = paused;
3106 mDoPauseSignal.signal();
3107}
3108
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003109status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3110 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003111 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003112 Mutex::Autolock l(mLatestRequestMutex);
3113 status_t res;
3114 while (mLatestRequestId != requestId) {
3115 nsecs_t startTime = systemTime();
3116
3117 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3118 if (res != OK) return res;
3119
3120 timeout -= (systemTime() - startTime);
3121 }
3122
3123 return OK;
3124}
3125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003126void Camera3Device::RequestThread::requestExit() {
3127 // Call parent to set up shutdown
3128 Thread::requestExit();
3129 // The exit from any possible waits
3130 mDoPauseSignal.signal();
3131 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003132
3133 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3134 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003135}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003136
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003137void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003138 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003139 bool surfaceAbandoned = false;
3140 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003141 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003142 {
3143 Mutex::Autolock l(mRequestLock);
3144 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3145 // repeating requests.
3146 for (const auto& request : mRepeatingRequests) {
3147 for (const auto& s : request->mOutputStreams) {
3148 if (s->isAbandoned()) {
3149 surfaceAbandoned = true;
3150 clearRepeatingRequestsLocked(&lastFrameNumber);
3151 break;
3152 }
3153 }
3154 if (surfaceAbandoned) {
3155 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003156 }
3157 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003158 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003159 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003160
3161 if (listener != NULL && surfaceAbandoned) {
3162 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003163 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003164}
3165
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003166bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003167 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003168 status_t res;
3169 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003170 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003171 uint32_t numRequestProcessed = 0;
3172 for (size_t i = 0; i < batchSize; i++) {
3173 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003174 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003175 }
3176
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003177 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3178
3179 bool triggerRemoveFailed = false;
3180 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3181 for (size_t i = 0; i < numRequestProcessed; i++) {
3182 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3183 nextRequest.submitted = true;
3184
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003185 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003186
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003187 if (!triggerRemoveFailed) {
3188 // Remove any previously queued triggers (after unlock)
3189 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3190 if (removeTriggerRes != OK) {
3191 triggerRemoveFailed = true;
3192 triggerFailedRequest = nextRequest;
3193 }
3194 }
3195 }
3196
3197 if (triggerRemoveFailed) {
3198 SET_ERR("RequestThread: Unable to remove triggers "
3199 "(capture request %d, HAL device: %s (%d)",
3200 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3201 cleanUpFailedRequests(/*sendRequestError*/ false);
3202 return false;
3203 }
3204
3205 if (res != OK) {
3206 // Should only get a failure here for malformed requests or device-level
3207 // errors, so consider all errors fatal. Bad metadata failures should
3208 // come through notify.
3209 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3210 mNextRequests[numRequestProcessed].halRequest.frame_number,
3211 strerror(-res), res);
3212 cleanUpFailedRequests(/*sendRequestError*/ false);
3213 return false;
3214 }
3215 return true;
3216}
3217
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003218nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3219 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3220 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3221 find_camera_metadata_ro_entry(request,
3222 ANDROID_CONTROL_AE_MODE,
3223 &e);
3224 if (e.count == 0) return maxExpectedDuration;
3225
3226 switch (e.data.u8[0]) {
3227 case ANDROID_CONTROL_AE_MODE_OFF:
3228 find_camera_metadata_ro_entry(request,
3229 ANDROID_SENSOR_EXPOSURE_TIME,
3230 &e);
3231 if (e.count > 0) {
3232 maxExpectedDuration = e.data.i64[0];
3233 }
3234 find_camera_metadata_ro_entry(request,
3235 ANDROID_SENSOR_FRAME_DURATION,
3236 &e);
3237 if (e.count > 0) {
3238 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3239 }
3240 break;
3241 default:
3242 find_camera_metadata_ro_entry(request,
3243 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3244 &e);
3245 if (e.count > 1) {
3246 maxExpectedDuration = 1e9 / e.data.u8[0];
3247 }
3248 break;
3249 }
3250
3251 return maxExpectedDuration;
3252}
3253
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003254bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3255 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3256 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3257 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3258 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3259 return true;
3260 }
3261
3262 return false;
3263}
3264
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003265void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3266 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003267 camera_capture_request_t& halRequest = nextRequest.halRequest;
3268 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003269 Mutex::Autolock al(mLatestRequestMutex);
3270
Shuzhen Wang83bff122020-11-20 15:51:39 -08003271 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003272 mLatestRequest.acquire(cloned);
3273
3274 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003275 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3276 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3277 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003278 CameraMetadata(cloned));
3279 }
3280
3281 sp<Camera3Device> parent = mParent.promote();
3282 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003283 int32_t inputStreamId = -1;
3284 if (halRequest.input_buffer != nullptr) {
3285 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3286 }
3287
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003288 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003289 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003290 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3291 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003292 }
3293 }
3294
Shuzhen Wang83bff122020-11-20 15:51:39 -08003295 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003296 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003297 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003298 }
3299
Shuzhen Wang83bff122020-11-20 15:51:39 -08003300 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003301}
3302
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003303bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3304 ATRACE_CALL();
3305 bool updatesDetected = false;
3306
Emilian Peev4ec17882019-01-24 17:16:58 -08003307 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003308 for (auto tag : mSessionParamKeys) {
3309 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003310 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003311
3312 if (entry.count > 0) {
3313 bool isDifferent = false;
3314 if (lastEntry.count > 0) {
3315 // Have a last value, compare to see if changed
3316 if (lastEntry.type == entry.type &&
3317 lastEntry.count == entry.count) {
3318 // Same type and count, compare values
3319 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3320 size_t entryBytes = bytesPerValue * lastEntry.count;
3321 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3322 if (cmp != 0) {
3323 isDifferent = true;
3324 }
3325 } else {
3326 // Count or type has changed
3327 isDifferent = true;
3328 }
3329 } else {
3330 // No last entry, so always consider to be different
3331 isDifferent = true;
3332 }
3333
3334 if (isDifferent) {
3335 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003336 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3337 updatesDetected = true;
3338 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003339 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003340 }
3341 } else if (lastEntry.count > 0) {
3342 // Value has been removed
3343 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003344 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003345 updatesDetected = true;
3346 }
3347 }
3348
Emilian Peev4ec17882019-01-24 17:16:58 -08003349 bool reconfigureRequired;
3350 if (updatesDetected) {
3351 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3352 updatedParams);
3353 mLatestSessionParams = updatedParams;
3354 } else {
3355 reconfigureRequired = false;
3356 }
3357
3358 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003359}
3360
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003361bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003362 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003363 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003364 // Any function called from threadLoop() must not hold mInterfaceLock since
3365 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3366 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003367
3368 // Handle paused state.
3369 if (waitIfPaused()) {
3370 return true;
3371 }
3372
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003373 // Wait for the next batch of requests.
3374 waitForNextRequestBatch();
3375 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003376 return true;
3377 }
3378
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003379 // Get the latest request ID, if any
3380 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003381 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003382 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003383 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003384 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003385 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003386 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3387 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003388 }
3389
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003390 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3391 // or a single request from streaming or burst. In either case the first element
3392 // should contain the latest camera settings that we need to check for any session
3393 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003394 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003395 res = OK;
3396
3397 //Input stream buffers are already acquired at this point so an input stream
3398 //will not be able to move to idle state unless we force it.
3399 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3400 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3401 if (res != OK) {
3402 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3403 cleanUpFailedRequests(/*sendRequestError*/ false);
3404 return false;
3405 }
3406 }
3407
3408 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003409 sp<Camera3Device> parent = mParent.promote();
3410 if (parent != nullptr) {
3411 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003412 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003413 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003414
3415 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3416 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3417 if (res != OK) {
3418 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3419 cleanUpFailedRequests(/*sendRequestError*/ false);
3420 return false;
3421 }
3422 }
3423 }
3424 }
3425
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003426 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003427 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003428 if (res == TIMED_OUT) {
3429 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003430 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003431 // Check if any stream is abandoned.
3432 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003433 return true;
3434 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003435 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003436 return false;
3437 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003438
Zhijun Hecc27e112013-10-03 16:12:43 -07003439 // Inform waitUntilRequestProcessed thread of a new request ID
3440 {
3441 Mutex::Autolock al(mLatestRequestMutex);
3442
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003443 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003444 mLatestRequestSignal.signal();
3445 }
3446
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003447 // Submit a batch of requests to HAL.
3448 // Use flush lock only when submitting multilple requests in a batch.
3449 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3450 // which may take a long time to finish so synchronizing flush() and
3451 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3452 // For now, only synchronize for high speed recording and we should figure something out for
3453 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003454 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003455
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003456 if (useFlushLock) {
3457 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003458 }
3459
Zhijun Hef0645c12016-08-02 00:58:11 -07003460 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003461 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003462
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003463 sp<Camera3Device> parent = mParent.promote();
3464 if (parent != nullptr) {
3465 parent->mRequestBufferSM.onSubmittingRequest();
3466 }
3467
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003468 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003469 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003470 submitRequestSuccess = sendRequestsBatch();
3471
Shuzhen Wang686f6442017-06-20 16:16:04 -07003472 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3473 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003474
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003475 if (useFlushLock) {
3476 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003477 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003478
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003479 // Unset as current request
3480 {
3481 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003482 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003483 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003484 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003485
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003486 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003487}
3488
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003489status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3490 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3491 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3492 ANDROID_SCALER_CROP_REGION_SET};
3493 if (request == nullptr) {
3494 ALOGE("%s request metadata nullptr", __FUNCTION__);
3495 return BAD_VALUE;
3496 }
3497 status_t res = OK;
3498 for (const auto &key : kFwkOnlyRegionKeys) {
3499 if (request->exists(key)) {
3500 res = request->erase(key);
3501 if (res != OK) {
3502 return res;
3503 }
3504 }
3505 }
3506 return OK;
3507}
3508
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003509status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003510 ATRACE_CALL();
3511
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003512 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003513 for (size_t i = 0; i < mNextRequests.size(); i++) {
3514 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003515 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003516 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3517 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003518
3519 // Prepare a request to HAL
3520 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3521
3522 // Insert any queued triggers (before metadata is locked)
3523 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003524 if (res < 0) {
3525 SET_ERR("RequestThread: Unable to insert triggers "
3526 "(capture request %d, HAL device: %s (%d)",
3527 halRequest->frame_number, strerror(-res), res);
3528 return INVALID_OPERATION;
3529 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003530
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003531 int triggerCount = res;
3532 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3533 mPrevTriggers = triggerCount;
3534
Emilian Peeve23f1d92021-09-20 14:56:01 -07003535 // Do not override rotate&crop for stream configurations that include
3536 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3537 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3538 bool rotateAndCropChanged = mComposerOutput ? false :
3539 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003540 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003541
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003542 // If the request is the same as last, or we had triggers now or last time or
3543 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003544 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003545 (mPrevRequest != captureRequest || triggersMixedIn ||
3546 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003547 // Request settings are all the same within one batch, so only treat the first
3548 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003549 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003550 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003551 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003552 /**
3553 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003554 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003555 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003556 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003557 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003558 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003559 "(capture request %d, HAL device: %s (%d)",
3560 halRequest->frame_number, strerror(-res), res);
3561 return INVALID_OPERATION;
3562 }
3563
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003564 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003565 sp<Camera3Device> parent = mParent.promote();
3566 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003567 List<PhysicalCameraSettings>::iterator it;
3568 for (it = captureRequest->mSettingsList.begin();
3569 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003570 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3571 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003572 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3573 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3574 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3575 res);
3576 return INVALID_OPERATION;
3577 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003578 continue;
3579 }
3580
3581 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3582 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3583 updateCaptureRequest(&(it->metadata));
3584 if (res != OK) {
3585 SET_ERR("RequestThread: Unable to correct capture requests "
3586 "for scaler crop region and metering regions for request "
3587 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3588 res);
3589 return INVALID_OPERATION;
3590 }
3591 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003592 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3593 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3594 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3595 res);
3596 return INVALID_OPERATION;
3597 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003598 }
3599 }
3600
3601 // Correct metadata regions for distortion correction if enabled
3602 for (it = captureRequest->mSettingsList.begin();
3603 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003604 if (parent->mDistortionMappers.find(it->cameraId) ==
3605 parent->mDistortionMappers.end()) {
3606 continue;
3607 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003608
3609 if (!captureRequest->mDistortionCorrectionUpdated) {
3610 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3611 &(it->metadata));
3612 if (res != OK) {
3613 SET_ERR("RequestThread: Unable to correct capture requests "
3614 "for lens distortion for request %d: %s (%d)",
3615 halRequest->frame_number, strerror(-res), res);
3616 return INVALID_OPERATION;
3617 }
3618 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003619 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003620 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003621
3622 for (it = captureRequest->mSettingsList.begin();
3623 it != captureRequest->mSettingsList.end(); it++) {
3624 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3625 parent->mZoomRatioMappers.end()) {
3626 continue;
3627 }
3628
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003629 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003630 cameraIdsWithZoom.insert(it->cameraId);
3631 }
3632
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003633 if (!captureRequest->mZoomRatioUpdated) {
3634 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3635 &(it->metadata));
3636 if (res != OK) {
3637 SET_ERR("RequestThread: Unable to correct capture requests "
3638 "for zoom ratio for request %d: %s (%d)",
3639 halRequest->frame_number, strerror(-res), res);
3640 return INVALID_OPERATION;
3641 }
3642 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003643 }
3644 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003645 if (captureRequest->mRotateAndCropAuto &&
3646 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003647 for (it = captureRequest->mSettingsList.begin();
3648 it != captureRequest->mSettingsList.end(); it++) {
3649 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3650 if (mapper != parent->mRotateAndCropMappers.end()) {
3651 res = mapper->second.updateCaptureRequest(&(it->metadata));
3652 if (res != OK) {
3653 SET_ERR("RequestThread: Unable to correct capture requests "
3654 "for rotate-and-crop for request %d: %s (%d)",
3655 halRequest->frame_number, strerror(-res), res);
3656 return INVALID_OPERATION;
3657 }
3658 }
3659 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003660 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003661 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003662 }
3663 }
3664
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003665 /**
3666 * The request should be presorted so accesses in HAL
3667 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3668 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003669 captureRequest->mSettingsList.begin()->metadata.sort();
3670 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003671 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003672 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003673 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3674
3675 IF_ALOGV() {
3676 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3677 find_camera_metadata_ro_entry(
3678 halRequest->settings,
3679 ANDROID_CONTROL_AF_TRIGGER,
3680 &e
3681 );
3682 if (e.count > 0) {
3683 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3684 __FUNCTION__,
3685 halRequest->frame_number,
3686 e.data.u8[0]);
3687 }
3688 }
3689 } else {
3690 // leave request.settings NULL to indicate 'reuse latest given'
3691 ALOGVV("%s: Request settings are REUSED",
3692 __FUNCTION__);
3693 }
3694
Emilian Peevaebbe412018-01-15 13:53:24 +00003695 if (captureRequest->mSettingsList.size() > 1) {
3696 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3697 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003698 if (newRequest) {
3699 halRequest->physcam_settings =
3700 new const camera_metadata* [halRequest->num_physcam_settings];
3701 } else {
3702 halRequest->physcam_settings = nullptr;
3703 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003704 auto it = ++captureRequest->mSettingsList.begin();
3705 size_t i = 0;
3706 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3707 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003708 if (newRequest) {
3709 it->metadata.sort();
3710 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3711 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003712 }
3713 }
3714
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003715 uint32_t totalNumBuffers = 0;
3716
3717 // Fill in buffers
3718 if (captureRequest->mInputStream != NULL) {
3719 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003720
3721 halRequest->input_width = captureRequest->mInputBufferSize.width;
3722 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003723 totalNumBuffers += 1;
3724 } else {
3725 halRequest->input_buffer = NULL;
3726 }
3727
Emilian Peevf4816702020-04-03 15:44:51 -07003728 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003729 captureRequest->mOutputStreams.size());
3730 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003731 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003732
3733 sp<Camera3Device> parent = mParent.promote();
3734 if (parent == NULL) {
3735 // Should not happen, and nowhere to send errors to, so just log it
3736 CLOGE("RequestThread: Parent is gone");
3737 return INVALID_OPERATION;
3738 }
3739 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3740
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003741 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003742 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003743 sp<Camera3OutputStreamInterface> outputStream =
3744 captureRequest->mOutputStreams.editItemAt(j);
3745 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003746
3747 // Prepare video buffers for high speed recording on the first video request.
3748 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3749 // Only try to prepare video stream on the first video request.
3750 mPrepareVideoStream = false;
3751
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003752 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3753 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003754 while (res == NOT_ENOUGH_DATA) {
3755 res = outputStream->prepareNextBuffer();
3756 }
3757 if (res != OK) {
3758 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3759 __FUNCTION__, strerror(-res), res);
3760 outputStream->cancelPrepare();
3761 }
3762 }
3763
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003764 std::vector<size_t> uniqueSurfaceIds;
3765 res = outputStream->getUniqueSurfaceIds(
3766 captureRequest->mOutputSurfaces[streamId],
3767 &uniqueSurfaceIds);
3768 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3769 if (res != OK && res != INVALID_OPERATION) {
3770 ALOGE("%s: failed to query stream %d unique surface IDs",
3771 __FUNCTION__, streamId);
3772 return res;
3773 }
3774 if (res == OK) {
3775 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3776 }
3777
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003778 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003779 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003780 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003781 return TIMED_OUT;
3782 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003783 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003784 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003785 buffer.stream = outputStream->asHalStream();
3786 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003787 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003788 buffer.acquire_fence = -1;
3789 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003790 // Mark the output stream as unpreparable to block clients from calling
3791 // 'prepare' after this request reaches CameraHal and before the respective
3792 // buffers are requested.
3793 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003794 } else {
3795 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3796 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003797 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003798 if (res != OK) {
3799 // Can't get output buffer from gralloc queue - this could be due to
3800 // abandoned queue or other consumer misbehavior, so not a fatal
3801 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003802 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003803 " %s (%d)", strerror(-res), res);
3804
3805 return TIMED_OUT;
3806 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003807 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003808
3809 {
3810 sp<Camera3Device> parent = mParent.promote();
3811 if (parent != nullptr) {
3812 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3813 for (const auto& settings : captureRequest->mSettingsList) {
3814 if ((streamCameraId.isEmpty() &&
3815 parent->getId() == settings.cameraId.c_str()) ||
3816 streamCameraId == settings.cameraId.c_str()) {
3817 outputStream->fireBufferRequestForFrameNumber(
3818 captureRequest->mResultExtras.frameNumber,
3819 settings.metadata);
3820 }
3821 }
3822 }
3823 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003824
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003825 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003826 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3827 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3828 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3829 } else if (!physicalCameraId.isEmpty()) {
3830 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003831 }
3832 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003833 }
3834 totalNumBuffers += halRequest->num_output_buffers;
3835
3836 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003837 // If this request list is for constrained high speed recording (not
3838 // preview), and the current request is not the last one in the batch,
3839 // do not send callback to the app.
3840 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003841 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003842 hasCallback = false;
3843 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003844 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003845 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003846 const camera_metadata_t* settings = halRequest->settings;
3847 bool shouldUnlockSettings = false;
3848 if (settings == nullptr) {
3849 shouldUnlockSettings = true;
3850 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3851 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003852 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3853 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003854 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003855 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3856 isStillCapture = true;
3857 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3858 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003859
Emilian Peevaf8416e2021-02-04 17:52:43 -08003860 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003861 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003862 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3863 isZslCapture = true;
3864 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003865 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003866 res = parent->registerInFlight(halRequest->frame_number,
3867 totalNumBuffers, captureRequest->mResultExtras,
3868 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003869 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003870 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003871 requestedPhysicalCameras, isStillCapture, isZslCapture,
3872 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003873 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003874 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003875 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3876 ", burstId = %" PRId32 ".",
3877 __FUNCTION__,
3878 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3879 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003880
3881 if (shouldUnlockSettings) {
3882 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3883 }
3884
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003885 if (res != OK) {
3886 SET_ERR("RequestThread: Unable to register new in-flight request:"
3887 " %s (%d)", strerror(-res), res);
3888 return INVALID_OPERATION;
3889 }
3890 }
3891
3892 return OK;
3893}
3894
Igor Murashkin1e479c02013-09-06 16:55:14 -07003895CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003896 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003897 Mutex::Autolock al(mLatestRequestMutex);
3898
3899 ALOGV("RequestThread::%s", __FUNCTION__);
3900
3901 return mLatestRequest;
3902}
3903
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003904bool Camera3Device::RequestThread::isStreamPending(
3905 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003906 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003907 Mutex::Autolock l(mRequestLock);
3908
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003909 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003910 if (!nextRequest.submitted) {
3911 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3912 if (stream == s) return true;
3913 }
3914 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003915 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003916 }
3917
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003918 for (const auto& request : mRequestQueue) {
3919 for (const auto& s : request->mOutputStreams) {
3920 if (stream == s) return true;
3921 }
3922 if (stream == request->mInputStream) return true;
3923 }
3924
3925 for (const auto& request : mRepeatingRequests) {
3926 for (const auto& s : request->mOutputStreams) {
3927 if (stream == s) return true;
3928 }
3929 if (stream == request->mInputStream) return true;
3930 }
3931
3932 return false;
3933}
Jianing Weicb0652e2014-03-12 18:29:36 -07003934
Emilian Peev40ead602017-09-26 15:46:36 +01003935bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3936 ATRACE_CALL();
3937 Mutex::Autolock l(mRequestLock);
3938
3939 for (const auto& nextRequest : mNextRequests) {
3940 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3941 if (s.first == streamId) {
3942 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3943 if (it != s.second.end()) {
3944 return true;
3945 }
3946 }
3947 }
3948 }
3949
3950 for (const auto& request : mRequestQueue) {
3951 for (const auto& s : request->mOutputSurfaces) {
3952 if (s.first == streamId) {
3953 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3954 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003955 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003956 }
3957 }
3958 }
3959 }
3960
3961 for (const auto& request : mRepeatingRequests) {
3962 for (const auto& s : request->mOutputSurfaces) {
3963 if (s.first == streamId) {
3964 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3965 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003966 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003967 }
3968 }
3969 }
3970 }
3971
3972 return false;
3973}
3974
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003975void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3976 if (!mUseHalBufManager) {
3977 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3978 return;
3979 }
3980
3981 Mutex::Autolock pl(mPauseLock);
3982 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003983 mInterface->signalPipelineDrain(streamIds);
3984 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003985 }
3986 // If request thread is still busy, wait until paused then notify HAL
3987 mNotifyPipelineDrain = true;
3988 mStreamIdsToBeDrained = streamIds;
3989}
3990
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003991void Camera3Device::RequestThread::resetPipelineDrain() {
3992 Mutex::Autolock pl(mPauseLock);
3993 mNotifyPipelineDrain = false;
3994 mStreamIdsToBeDrained.clear();
3995}
3996
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003997void Camera3Device::RequestThread::clearPreviousRequest() {
3998 Mutex::Autolock l(mRequestLock);
3999 mPrevRequest.clear();
4000}
4001
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004002status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4003 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4004 ATRACE_CALL();
4005 Mutex::Autolock l(mTriggerMutex);
4006 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4007 return BAD_VALUE;
4008 }
4009 mRotateAndCropOverride = rotateAndCropValue;
4010 return OK;
4011}
4012
Emilian Peeve23f1d92021-09-20 14:56:01 -07004013status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4014 ATRACE_CALL();
4015 Mutex::Autolock l(mTriggerMutex);
4016 mComposerOutput = composerSurfacePresent;
4017 return OK;
4018}
4019
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004020status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004021 ATRACE_CALL();
4022 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004023 if (muteMode != mCameraMute) {
4024 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004025 mCameraMuteChanged = true;
4026 }
4027 return OK;
4028}
4029
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004030nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004031 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004032 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004033 return mExpectedInflightDuration > kMinInflightDuration ?
4034 mExpectedInflightDuration : kMinInflightDuration;
4035}
4036
Emilian Peevaebbe412018-01-15 13:53:24 +00004037void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004038 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004039 if ((request == nullptr) || (halRequest == nullptr)) {
4040 ALOGE("%s: Invalid request!", __FUNCTION__);
4041 return;
4042 }
4043
4044 if (halRequest->num_physcam_settings > 0) {
4045 if (halRequest->physcam_id != nullptr) {
4046 delete [] halRequest->physcam_id;
4047 halRequest->physcam_id = nullptr;
4048 }
4049 if (halRequest->physcam_settings != nullptr) {
4050 auto it = ++(request->mSettingsList.begin());
4051 size_t i = 0;
4052 for (; it != request->mSettingsList.end(); it++, i++) {
4053 it->metadata.unlock(halRequest->physcam_settings[i]);
4054 }
4055 delete [] halRequest->physcam_settings;
4056 halRequest->physcam_settings = nullptr;
4057 }
4058 }
4059}
4060
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004061void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4062 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004063 return;
4064 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004065
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004066 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004067 // Skip the ones that have been submitted successfully.
4068 if (nextRequest.submitted) {
4069 continue;
4070 }
4071
4072 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004073 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4074 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004075
4076 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004077 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004078 }
4079
Emilian Peevaebbe412018-01-15 13:53:24 +00004080 cleanupPhysicalSettings(captureRequest, halRequest);
4081
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004082 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004083 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004084 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4085 }
4086
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004087 // No output buffer can be returned when using HAL buffer manager
4088 if (!mUseHalBufManager) {
4089 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4090 //Buffers that failed processing could still have
4091 //valid acquire fence.
4092 int acquireFence = (*outputBuffers)[i].acquire_fence;
4093 if (0 <= acquireFence) {
4094 close(acquireFence);
4095 outputBuffers->editItemAt(i).acquire_fence = -1;
4096 }
Emilian Peevf4816702020-04-03 15:44:51 -07004097 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004098 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4099 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004100 /*timestampIncreasing*/true, std::vector<size_t> (),
4101 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004102 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004103 }
4104
4105 if (sendRequestError) {
4106 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004107 sp<NotificationListener> listener = mListener.promote();
4108 if (listener != NULL) {
4109 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004110 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004111 captureRequest->mResultExtras);
4112 }
4113 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004114
4115 // Remove yet-to-be submitted inflight request from inflightMap
4116 {
4117 sp<Camera3Device> parent = mParent.promote();
4118 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004119 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004120 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4121 if (idx >= 0) {
4122 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4123 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4124 parent->removeInFlightMapEntryLocked(idx);
4125 }
4126 }
4127 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004128 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004129
4130 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004131 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004132}
4133
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004134void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004135 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004136 // Optimized a bit for the simple steady-state case (single repeating
4137 // request), to avoid putting that request in the queue temporarily.
4138 Mutex::Autolock l(mRequestLock);
4139
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004140 assert(mNextRequests.empty());
4141
4142 NextRequest nextRequest;
4143 nextRequest.captureRequest = waitForNextRequestLocked();
4144 if (nextRequest.captureRequest == nullptr) {
4145 return;
4146 }
4147
Emilian Peevf4816702020-04-03 15:44:51 -07004148 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004149 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004150 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004151
4152 // Wait for additional requests
4153 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4154
4155 for (size_t i = 1; i < batchSize; i++) {
4156 NextRequest additionalRequest;
4157 additionalRequest.captureRequest = waitForNextRequestLocked();
4158 if (additionalRequest.captureRequest == nullptr) {
4159 break;
4160 }
4161
Emilian Peevf4816702020-04-03 15:44:51 -07004162 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004163 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004164 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004165 }
4166
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004167 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004168 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004169 mNextRequests.size(), batchSize);
4170 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004171 }
4172
4173 return;
4174}
4175
4176sp<Camera3Device::CaptureRequest>
4177 Camera3Device::RequestThread::waitForNextRequestLocked() {
4178 status_t res;
4179 sp<CaptureRequest> nextRequest;
4180
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004181 while (mRequestQueue.empty()) {
4182 if (!mRepeatingRequests.empty()) {
4183 // Always atomically enqueue all requests in a repeating request
4184 // list. Guarantees a complete in-sequence set of captures to
4185 // application.
4186 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004187 if (mFirstRepeating) {
4188 mFirstRepeating = false;
4189 } else {
4190 for (auto& request : requests) {
4191 // For repeating requests, override timestamp request using
4192 // the time a request is inserted into the request queue,
4193 // because the original repeating request will have an old
4194 // fixed timestamp.
4195 request->mRequestTimeNs = systemTime();
4196 }
4197 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004198 RequestList::const_iterator firstRequest =
4199 requests.begin();
4200 nextRequest = *firstRequest;
4201 mRequestQueue.insert(mRequestQueue.end(),
4202 ++firstRequest,
4203 requests.end());
4204 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004205
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004206 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004207
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004208 break;
4209 }
4210
4211 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4212
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004213 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4214 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004215 Mutex::Autolock pl(mPauseLock);
4216 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004217 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004218 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004219 if (mNotifyPipelineDrain) {
4220 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4221 mNotifyPipelineDrain = false;
4222 mStreamIdsToBeDrained.clear();
4223 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004224 // Let the tracker know
4225 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4226 if (statusTracker != 0) {
4227 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4228 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004229 sp<Camera3Device> parent = mParent.promote();
4230 if (parent != nullptr) {
4231 parent->mRequestBufferSM.onRequestThreadPaused();
4232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004233 }
4234 // Stop waiting for now and let thread management happen
4235 return NULL;
4236 }
4237 }
4238
4239 if (nextRequest == NULL) {
4240 // Don't have a repeating request already in hand, so queue
4241 // must have an entry now.
4242 RequestList::iterator firstRequest =
4243 mRequestQueue.begin();
4244 nextRequest = *firstRequest;
4245 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004246 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4247 sp<NotificationListener> listener = mListener.promote();
4248 if (listener != NULL) {
4249 listener->notifyRequestQueueEmpty();
4250 }
4251 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004252 }
4253
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004254 // In case we've been unpaused by setPaused clearing mDoPause, need to
4255 // update internal pause state (capture/setRepeatingRequest unpause
4256 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004257 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004258 if (mPaused) {
4259 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4260 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4261 if (statusTracker != 0) {
4262 statusTracker->markComponentActive(mStatusId);
4263 }
4264 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004265 mPaused = false;
4266
4267 // Check if we've reconfigured since last time, and reset the preview
4268 // request if so. Can't use 'NULL request == repeat' across configure calls.
4269 if (mReconfigured) {
4270 mPrevRequest.clear();
4271 mReconfigured = false;
4272 }
4273
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004274 if (nextRequest != NULL) {
4275 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004276 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4277 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004278
4279 // Since RequestThread::clear() removes buffers from the input stream,
4280 // get the right buffer here before unlocking mRequestLock
4281 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004282 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4283 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004284 if (res != OK) {
4285 // Can't get input buffer from gralloc queue - this could be due to
4286 // disconnected queue or other producer misbehavior, so not a fatal
4287 // error
4288 ALOGE("%s: Can't get input buffer, skipping request:"
4289 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004290
4291 sp<NotificationListener> listener = mListener.promote();
4292 if (listener != NULL) {
4293 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004294 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004295 nextRequest->mResultExtras);
4296 }
4297 return NULL;
4298 }
4299 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004300 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004301
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004302 return nextRequest;
4303}
4304
4305bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004306 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004307 status_t res;
4308 Mutex::Autolock l(mPauseLock);
4309 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 if (mPaused == false) {
4311 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004312 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004313 if (mNotifyPipelineDrain) {
4314 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4315 mNotifyPipelineDrain = false;
4316 mStreamIdsToBeDrained.clear();
4317 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004318 // Let the tracker know
4319 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4320 if (statusTracker != 0) {
4321 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4322 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004323 sp<Camera3Device> parent = mParent.promote();
4324 if (parent != nullptr) {
4325 parent->mRequestBufferSM.onRequestThreadPaused();
4326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004327 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004330 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331 return true;
4332 }
4333 }
4334 // We don't set mPaused to false here, because waitForNextRequest needs
4335 // to further manage the paused state in case of starvation.
4336 return false;
4337}
4338
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004339void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004340 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004341 // With work to do, mark thread as unpaused.
4342 // If paused by request (setPaused), don't resume, to avoid
4343 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004344 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004345 Mutex::Autolock p(mPauseLock);
4346 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004347 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4348 if (mPaused) {
4349 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4350 if (statusTracker != 0) {
4351 statusTracker->markComponentActive(mStatusId);
4352 }
4353 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004354 mPaused = false;
4355 }
4356}
4357
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004358void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4359 sp<Camera3Device> parent = mParent.promote();
4360 if (parent != NULL) {
4361 va_list args;
4362 va_start(args, fmt);
4363
4364 parent->setErrorStateV(fmt, args);
4365
4366 va_end(args);
4367 }
4368}
4369
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004370status_t Camera3Device::RequestThread::insertTriggers(
4371 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004372 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004373 Mutex::Autolock al(mTriggerMutex);
4374
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004375 sp<Camera3Device> parent = mParent.promote();
4376 if (parent == NULL) {
4377 CLOGE("RequestThread: Parent is gone");
4378 return DEAD_OBJECT;
4379 }
4380
Emilian Peevaebbe412018-01-15 13:53:24 +00004381 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004382 size_t count = mTriggerMap.size();
4383
4384 for (size_t i = 0; i < count; ++i) {
4385 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004386 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004387
4388 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4389 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4390 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004391 if (isAeTrigger) {
4392 request->mResultExtras.precaptureTriggerId = triggerId;
4393 mCurrentPreCaptureTriggerId = triggerId;
4394 } else {
4395 request->mResultExtras.afTriggerId = triggerId;
4396 mCurrentAfTriggerId = triggerId;
4397 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004398 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004399 }
4400
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004401 camera_metadata_entry entry = metadata.find(tag);
4402
4403 if (entry.count > 0) {
4404 /**
4405 * Already has an entry for this trigger in the request.
4406 * Rewrite it with our requested trigger value.
4407 */
4408 RequestTrigger oldTrigger = trigger;
4409
4410 oldTrigger.entryValue = entry.data.u8[0];
4411
4412 mTriggerReplacedMap.add(tag, oldTrigger);
4413 } else {
4414 /**
4415 * More typical, no trigger entry, so we just add it
4416 */
4417 mTriggerRemovedMap.add(tag, trigger);
4418 }
4419
4420 status_t res;
4421
4422 switch (trigger.getTagType()) {
4423 case TYPE_BYTE: {
4424 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4425 res = metadata.update(tag,
4426 &entryValue,
4427 /*count*/1);
4428 break;
4429 }
4430 case TYPE_INT32:
4431 res = metadata.update(tag,
4432 &trigger.entryValue,
4433 /*count*/1);
4434 break;
4435 default:
4436 ALOGE("%s: Type not supported: 0x%x",
4437 __FUNCTION__,
4438 trigger.getTagType());
4439 return INVALID_OPERATION;
4440 }
4441
4442 if (res != OK) {
4443 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4444 ", value %d", __FUNCTION__, trigger.getTagName(),
4445 trigger.entryValue);
4446 return res;
4447 }
4448
4449 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4450 trigger.getTagName(),
4451 trigger.entryValue);
4452 }
4453
4454 mTriggerMap.clear();
4455
4456 return count;
4457}
4458
4459status_t Camera3Device::RequestThread::removeTriggers(
4460 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004461 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004462 Mutex::Autolock al(mTriggerMutex);
4463
Emilian Peevaebbe412018-01-15 13:53:24 +00004464 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004465
4466 /**
4467 * Replace all old entries with their old values.
4468 */
4469 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4470 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4471
4472 status_t res;
4473
4474 uint32_t tag = trigger.metadataTag;
4475 switch (trigger.getTagType()) {
4476 case TYPE_BYTE: {
4477 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4478 res = metadata.update(tag,
4479 &entryValue,
4480 /*count*/1);
4481 break;
4482 }
4483 case TYPE_INT32:
4484 res = metadata.update(tag,
4485 &trigger.entryValue,
4486 /*count*/1);
4487 break;
4488 default:
4489 ALOGE("%s: Type not supported: 0x%x",
4490 __FUNCTION__,
4491 trigger.getTagType());
4492 return INVALID_OPERATION;
4493 }
4494
4495 if (res != OK) {
4496 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4497 ", trigger value %d", __FUNCTION__,
4498 trigger.getTagName(), trigger.entryValue);
4499 return res;
4500 }
4501 }
4502 mTriggerReplacedMap.clear();
4503
4504 /**
4505 * Remove all new entries.
4506 */
4507 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4508 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4509 status_t res = metadata.erase(trigger.metadataTag);
4510
4511 if (res != OK) {
4512 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4513 ", trigger value %d", __FUNCTION__,
4514 trigger.getTagName(), trigger.entryValue);
4515 return res;
4516 }
4517 }
4518 mTriggerRemovedMap.clear();
4519
4520 return OK;
4521}
4522
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004523status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004524 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004525 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004526 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004527 status_t res;
4528
Emilian Peevaebbe412018-01-15 13:53:24 +00004529 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004530
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004531 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004532 // exists
4533 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4534 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4535 if (afTrigger.count > 0 &&
4536 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4537 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004538 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004539 if (res != OK) return res;
4540 }
4541
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004542 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004543 // if none already exists
4544 camera_metadata_entry pcTrigger =
4545 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4546 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4547 if (pcTrigger.count > 0 &&
4548 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4549 pcId.count == 0) {
4550 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004551 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004552 if (res != OK) return res;
4553 }
4554
4555 return OK;
4556}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004557
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004558bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4559 const sp<CaptureRequest> &request) {
4560 ATRACE_CALL();
4561
4562 if (request->mRotateAndCropAuto) {
4563 Mutex::Autolock l(mTriggerMutex);
4564 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4565
4566 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4567 if (rotateAndCropEntry.count > 0) {
4568 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4569 return false;
4570 } else {
4571 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4572 return true;
4573 }
4574 } else {
4575 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4576 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4577 &rotateAndCrop_u8, 1);
4578 return true;
4579 }
4580 }
4581 return false;
4582}
4583
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004584bool Camera3Device::RequestThread::overrideTestPattern(
4585 const sp<CaptureRequest> &request) {
4586 ATRACE_CALL();
4587
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004588 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004589
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004590 Mutex::Autolock l(mTriggerMutex);
4591
4592 bool changed = false;
4593
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004594 // For a multi-camera, the physical cameras support the same set of
4595 // test pattern modes as the logical camera.
4596 for (auto& settings : request->mSettingsList) {
4597 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004598
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004599 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4600 int32_t testPatternData[4] = {
4601 settings.mOriginalTestPatternData[0],
4602 settings.mOriginalTestPatternData[1],
4603 settings.mOriginalTestPatternData[2],
4604 settings.mOriginalTestPatternData[3]
4605 };
4606 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4607 testPatternMode = mCameraMute;
4608 testPatternData[0] = 0;
4609 testPatternData[1] = 0;
4610 testPatternData[2] = 0;
4611 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004612 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004613
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004614 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4615 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4616 if (testPatternEntry.count > 0) {
4617 if (testPatternEntry.data.i32[0] != testPatternMode) {
4618 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004619 changed = true;
4620 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004621 } else if (supportTestPatternModeKey) {
4622 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4623 &testPatternMode, 1);
4624 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004625 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004626
4627 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4628 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4629 if (testPatternColor.count >= 4) {
4630 for (size_t i = 0; i < 4; i++) {
4631 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4632 testPatternColor.data.i32[i] = testPatternData[i];
4633 changed = true;
4634 }
4635 }
4636 } else if (supportTestPatternDataKey) {
4637 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4638 testPatternData, 4);
4639 changed = true;
4640 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004641 }
4642
4643 return changed;
4644}
4645
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004646status_t Camera3Device::RequestThread::setHalInterface(
4647 sp<HalInterface> newHalInterface) {
4648 if (newHalInterface.get() == nullptr) {
4649 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4650 return DEAD_OBJECT;
4651 }
4652
4653 mInterface = newHalInterface;
4654
4655 return OK;
4656}
4657
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004658/**
4659 * PreparerThread inner class methods
4660 */
4661
4662Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004663 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004664 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004665}
4666
4667Camera3Device::PreparerThread::~PreparerThread() {
4668 Thread::requestExitAndWait();
4669 if (mCurrentStream != nullptr) {
4670 mCurrentStream->cancelPrepare();
4671 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4672 mCurrentStream.clear();
4673 }
4674 clear();
4675}
4676
Ruben Brunkc78ac262015-08-13 17:58:46 -07004677status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004678 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004679 status_t res;
4680
4681 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004682 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004683
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004684 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004685 if (res == OK) {
4686 // No preparation needed, fire listener right off
4687 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004688 if (listener != NULL) {
4689 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004690 }
4691 return OK;
4692 } else if (res != NOT_ENOUGH_DATA) {
4693 return res;
4694 }
4695
4696 // Need to prepare, start up thread if necessary
4697 if (!mActive) {
4698 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4699 // isn't running
4700 Thread::requestExitAndWait();
4701 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4702 if (res != OK) {
4703 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004704 if (listener != NULL) {
4705 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004706 }
4707 return res;
4708 }
4709 mCancelNow = false;
4710 mActive = true;
4711 ALOGV("%s: Preparer stream started", __FUNCTION__);
4712 }
4713
4714 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004715 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004716 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4717
4718 return OK;
4719}
4720
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004721void Camera3Device::PreparerThread::pause() {
4722 ATRACE_CALL();
4723
4724 Mutex::Autolock l(mLock);
4725
4726 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4727 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4728 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4729 int currentMaxCount = mCurrentMaxCount;
4730 mPendingStreams.clear();
4731 mCancelNow = true;
4732 while (mActive) {
4733 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4734 if (res == TIMED_OUT) {
4735 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4736 return;
4737 } else if (res != OK) {
4738 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4739 return;
4740 }
4741 }
4742
4743 //Check whether the prepare thread was able to complete the current
4744 //stream. In case work is still pending emplace it along with the rest
4745 //of the streams in the pending list.
4746 if (currentStream != nullptr) {
4747 if (!mCurrentPrepareComplete) {
4748 pendingStreams.emplace(currentMaxCount, currentStream);
4749 }
4750 }
4751
4752 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4753 for (const auto& it : mPendingStreams) {
4754 it.second->cancelPrepare();
4755 }
4756}
4757
4758status_t Camera3Device::PreparerThread::resume() {
4759 ATRACE_CALL();
4760 status_t res;
4761
4762 Mutex::Autolock l(mLock);
4763 sp<NotificationListener> listener = mListener.promote();
4764
4765 if (mActive) {
4766 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4767 return NO_INIT;
4768 }
4769
4770 auto it = mPendingStreams.begin();
4771 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004772 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004773 if (res == OK) {
4774 if (listener != NULL) {
4775 listener->notifyPrepared(it->second->getId());
4776 }
4777 it = mPendingStreams.erase(it);
4778 } else if (res != NOT_ENOUGH_DATA) {
4779 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4780 res, strerror(-res));
4781 it = mPendingStreams.erase(it);
4782 } else {
4783 it++;
4784 }
4785 }
4786
4787 if (mPendingStreams.empty()) {
4788 return OK;
4789 }
4790
4791 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4792 if (res != OK) {
4793 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4794 __FUNCTION__, res, strerror(-res));
4795 return res;
4796 }
4797 mCancelNow = false;
4798 mActive = true;
4799 ALOGV("%s: Preparer stream started", __FUNCTION__);
4800
4801 return OK;
4802}
4803
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004804status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004805 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004806 Mutex::Autolock l(mLock);
4807
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004808 for (const auto& it : mPendingStreams) {
4809 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004810 }
4811 mPendingStreams.clear();
4812 mCancelNow = true;
4813
4814 return OK;
4815}
4816
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004817void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004818 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004819 Mutex::Autolock l(mLock);
4820 mListener = listener;
4821}
4822
4823bool Camera3Device::PreparerThread::threadLoop() {
4824 status_t res;
4825 {
4826 Mutex::Autolock l(mLock);
4827 if (mCurrentStream == nullptr) {
4828 // End thread if done with work
4829 if (mPendingStreams.empty()) {
4830 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4831 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4832 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4833 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004834 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004835 return false;
4836 }
4837
4838 // Get next stream to prepare
4839 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004840 mCurrentStream = it->second;
4841 mCurrentMaxCount = it->first;
4842 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004843 mPendingStreams.erase(it);
4844 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4845 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4846 } else if (mCancelNow) {
4847 mCurrentStream->cancelPrepare();
4848 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4849 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4850 mCurrentStream.clear();
4851 mCancelNow = false;
4852 return true;
4853 }
4854 }
4855
4856 res = mCurrentStream->prepareNextBuffer();
4857 if (res == NOT_ENOUGH_DATA) return true;
4858 if (res != OK) {
4859 // Something bad happened; try to recover by cancelling prepare and
4860 // signalling listener anyway
4861 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4862 mCurrentStream->getId(), res, strerror(-res));
4863 mCurrentStream->cancelPrepare();
4864 }
4865
4866 // This stream has finished, notify listener
4867 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004868 sp<NotificationListener> listener = mListener.promote();
4869 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004870 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4871 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004872 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004873 }
4874
4875 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4876 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004877 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004878
4879 return true;
4880}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004881
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004882status_t Camera3Device::RequestBufferStateMachine::initialize(
4883 sp<camera3::StatusTracker> statusTracker) {
4884 if (statusTracker == nullptr) {
4885 ALOGE("%s: statusTracker is null", __FUNCTION__);
4886 return BAD_VALUE;
4887 }
4888
4889 std::lock_guard<std::mutex> lock(mLock);
4890 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004891 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004892 return OK;
4893}
4894
4895bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4896 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004897 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004898 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004899 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004900 return true;
4901 }
4902 return false;
4903}
4904
4905void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4906 std::lock_guard<std::mutex> lock(mLock);
4907 if (!mRequestBufferOngoing) {
4908 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4909 return;
4910 }
4911 mRequestBufferOngoing = false;
4912 if (mStatus == RB_STATUS_PENDING_STOP) {
4913 checkSwitchToStopLocked();
4914 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004915 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004916}
4917
4918void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4919 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004920 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004921 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004922 return;
4923}
4924
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004925void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004926 std::lock_guard<std::mutex> lock(mLock);
4927 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004928 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4929 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004930 mInflightMapEmpty = false;
4931 if (mStatus == RB_STATUS_STOPPED) {
4932 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004933 }
4934 return;
4935}
4936
4937void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4938 std::lock_guard<std::mutex> lock(mLock);
4939 mRequestThreadPaused = true;
4940 if (mStatus == RB_STATUS_PENDING_STOP) {
4941 checkSwitchToStopLocked();
4942 }
4943 return;
4944}
4945
4946void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4947 std::lock_guard<std::mutex> lock(mLock);
4948 mInflightMapEmpty = true;
4949 if (mStatus == RB_STATUS_PENDING_STOP) {
4950 checkSwitchToStopLocked();
4951 }
4952 return;
4953}
4954
4955void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4956 std::lock_guard<std::mutex> lock(mLock);
4957 if (!checkSwitchToStopLocked()) {
4958 mStatus = RB_STATUS_PENDING_STOP;
4959 }
4960 return;
4961}
4962
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004963bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4964 std::lock_guard<std::mutex> lock(mLock);
4965 if (mRequestBufferOngoing) {
4966 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4967 __FUNCTION__);
4968 return false;
4969 }
4970 mSwitchedToOffline = true;
4971 mInflightMapEmpty = true;
4972 mRequestThreadPaused = true;
4973 mStatus = RB_STATUS_STOPPED;
4974 return true;
4975}
4976
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004977void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4978 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4979 if (statusTracker != nullptr) {
4980 if (active) {
4981 statusTracker->markComponentActive(mRequestBufferStatusId);
4982 } else {
4983 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4984 }
4985 }
4986}
4987
4988bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4989 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4990 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004991 return true;
4992 }
4993 return false;
4994}
4995
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004996bool Camera3Device::startRequestBuffer() {
4997 return mRequestBufferSM.startRequestBuffer();
4998}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004999
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005000void Camera3Device::endRequestBuffer() {
5001 mRequestBufferSM.endRequestBuffer();
5002}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005003
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005004nsecs_t Camera3Device::getWaitDuration() {
5005 return kBaseGetBufferWait + getExpectedInFlightDuration();
5006}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005007
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005008void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5009 mInterface->getInflightBufferKeys(out);
5010}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005011
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005012void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5013 mInterface->getInflightRequestBufferKeys(out);
5014}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005015
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005016std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5017 std::vector<sp<Camera3StreamInterface>> ret;
5018 bool hasInputStream = mInputStream != nullptr;
5019 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5020 if (hasInputStream) {
5021 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005022 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005023 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5024 ret.push_back(mOutputStreams[i]);
5025 }
5026 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5027 ret.push_back(mDeletedStreams[i]);
5028 }
5029 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005030}
5031
Emilian Peevcc0b7952020-01-07 13:54:47 -08005032void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5033 ATRACE_CALL();
5034
5035 if (offlineStreamIds == nullptr) {
5036 return;
5037 }
5038
5039 Mutex::Autolock il(mInterfaceLock);
5040
5041 auto streamIds = mOutputStreams.getStreamIds();
5042 bool hasInputStream = mInputStream != nullptr;
5043 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5044 offlineStreamIds->push_back(mInputStream->getId());
5045 }
5046
5047 for (const auto & streamId : streamIds) {
5048 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5049 // Streams that use the camera buffer manager are currently not supported in
5050 // offline mode
5051 if (stream->getOfflineProcessingSupport() &&
5052 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5053 offlineStreamIds->push_back(streamId);
5054 }
5055 }
5056}
5057
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005058status_t Camera3Device::setRotateAndCropAutoBehavior(
5059 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5060 ATRACE_CALL();
5061 Mutex::Autolock il(mInterfaceLock);
5062 Mutex::Autolock l(mLock);
5063 if (mRequestThread == nullptr) {
5064 return INVALID_OPERATION;
5065 }
5066 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5067}
5068
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005069bool Camera3Device::supportsCameraMute() {
5070 Mutex::Autolock il(mInterfaceLock);
5071 Mutex::Autolock l(mLock);
5072
5073 return mSupportCameraMute;
5074}
5075
5076status_t Camera3Device::setCameraMute(bool enabled) {
5077 ATRACE_CALL();
5078 Mutex::Autolock il(mInterfaceLock);
5079 Mutex::Autolock l(mLock);
5080
5081 if (mRequestThread == nullptr || !mSupportCameraMute) {
5082 return INVALID_OPERATION;
5083 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005084 int32_t muteMode =
5085 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5086 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5087 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5088 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005089}
5090
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005091status_t Camera3Device::injectCamera(const String8& injectedCamId,
5092 sp<CameraProviderManager> manager) {
5093 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5094 ATRACE_CALL();
5095 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005096 // When the camera device is active, injectCamera() and stopInjection() will call
5097 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5098 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5099 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5100 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5101 // waitUntilStateThenRelock().
5102 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005103
5104 status_t res = NO_ERROR;
5105 if (mInjectionMethods->isInjecting()) {
5106 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5107 return OK;
5108 } else {
5109 res = mInjectionMethods->stopInjection();
5110 if (res != OK) {
5111 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5112 __FUNCTION__, res);
5113 return res;
5114 }
5115 }
5116 }
5117
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005118 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005119 if (res != OK) {
5120 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5121 __FUNCTION__, res);
5122 return res;
5123 }
5124
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005125 // When the second display of android is cast to the remote device, and the opened camera is
5126 // also cast to the second display, in this case, because the camera has configured the streams
5127 // at this time, we can directly call injectCamera() to replace the internal camera with
5128 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005129 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5130 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5131
5132 camera3::camera_stream_configuration injectionConfig;
5133 std::vector<uint32_t> injectionBufferSizes;
5134 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5135 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5136 || injectionBufferSizes.size() <= 0) {
5137 ALOGE("Failed to inject camera due to abandoned configuration! "
5138 "mOperatingMode: %d injectionConfig.num_streams: %d "
5139 "injectionBufferSizes.size(): %zu", mOperatingMode,
5140 injectionConfig.num_streams, injectionBufferSizes.size());
5141 return DEAD_OBJECT;
5142 }
5143
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005144 res = mInjectionMethods->injectCamera(
5145 injectionConfig, injectionBufferSizes);
5146 if (res != OK) {
5147 ALOGE("Can't finish inject camera process!");
5148 return res;
5149 }
5150 }
5151
5152 return OK;
5153}
5154
5155status_t Camera3Device::stopInjection() {
5156 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5157 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005158 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005159 return mInjectionMethods->stopInjection();
5160}
5161
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005162}; // namespace android