blob: d033395345a95e0f53376d937482562c8b158838 [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;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080073
74namespace android {
75
Austin Borger3560b7e2022-10-27 12:20:29 -070076Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool overrideToPortrait,
77 bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080078 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070079 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080086 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
Austin Borger3560b7e2022-10-27 12:20:29 -070098 mOverrideForPerfClass(overrideForPerfClass),
Austin Borgerc8099762023-01-12 17:08:46 -080099 mOverrideToPortrait(overrideToPortrait),
100 mActivePhysicalId("")
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
106Camera3Device::~Camera3Device()
107{
108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700110 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111}
112
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800113const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800114 return mId;
115}
116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117status_t Camera3Device::initializeCommonLocked() {
118
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700119 /** Start up status tracker thread */
120 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800121 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700122 if (res != OK) {
123 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
124 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700126 mStatusTracker.clear();
127 return res;
128 }
129
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700130 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700131 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700132
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700133 if (mUseHalBufManager) {
134 res = mRequestBufferSM.initialize(mStatusTracker);
135 if (res != OK) {
136 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
137 strerror(-res), res);
138 mInterface->close();
139 mStatusTracker.clear();
140 return res;
141 }
142 }
143
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800144 /** Create buffer manager */
145 mBufferManager = new Camera3BufferManager();
146
147 Vector<int32_t> sessionParamKeys;
148 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
149 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
150 if (sessionKeysEntry.count > 0) {
151 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
152 }
153
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700154 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
155 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
156 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
157 if (availableTestPatternModes.data.i32[i] ==
158 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
159 mSupportCameraMute = true;
160 mSupportTestPatternSolidColor = true;
161 break;
162 } else if (availableTestPatternModes.data.i32[i] ==
163 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
164 mSupportCameraMute = true;
165 mSupportTestPatternSolidColor = false;
166 }
167 }
168
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700169 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800170 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700171 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger3560b7e2022-10-27 12:20:29 -0700172 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800174 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700175 SET_ERR_L("Unable to start request queue thread: %s (%d)",
176 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800177 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800178 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800179 return res;
180 }
181
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700182 mPreparerThread = new PreparerThread();
183
Ruben Brunk183f0562015-08-12 12:55:02 -0700184 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800185 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400186 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700187 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700188 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800189 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800190
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800191 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800192 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800193 camera_metadata_entry timestampSource =
194 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
195 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
196 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800197 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800198 }
199
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700200 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100201 camera_metadata_entry partialResultsCount =
202 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
203 if (partialResultsCount.count > 0) {
204 mNumPartialResults = partialResultsCount.data.i32[0];
205 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700206 }
207
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800208 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
209 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700210 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700211 if (res != OK) {
212 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
213 return res;
214 }
215 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800216
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800217 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700220 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
221 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
222 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
223 }
224
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800225 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
226 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
227 }
228
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800229 // Hidl/AidlCamera3DeviceInjectionMethods
230 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800231
Ravneet74cd3732022-03-30 05:33:03 +0000232 /** Start watchdog thread */
233 mCameraServiceWatchdog = new CameraServiceWatchdog();
234 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
235 if (res != OK) {
236 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
237 strerror(-res), res);
238 return res;
239 }
240
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800241 return OK;
242}
243
244status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700245 return disconnectImpl();
246}
247
248status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800249 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700250 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800251
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700252 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700253 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 Mutex::Autolock il(mInterfaceLock);
256 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
257 {
258 Mutex::Autolock l(mLock);
259 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800261 if (mStatus == STATUS_ACTIVE ||
262 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
263 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800265 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700266 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 } else {
268 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
269 if (res != OK) {
270 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
271 maxExpectedDuration);
272 // Continue to close device even in case of error
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700275 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800276
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800277 if (mStatus == STATUS_ERROR) {
278 CLOGE("Shutting down in an error state");
279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700280
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800281 if (mStatusTracker != NULL) {
282 mStatusTracker->requestExit();
283 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700284
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800285 if (mRequestThread != NULL) {
286 mRequestThread->requestExit();
287 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700288
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800289 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
290 for (size_t i = 0; i < mOutputStreams.size(); i++) {
291 streams.push_back(mOutputStreams[i]);
292 }
293 if (mInputStream != nullptr) {
294 streams.push_back(mInputStream);
295 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700296 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800298 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
299 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
301 // HAL may be in a bad state, so waiting for request thread
302 // (which may be stuck in the HAL processCaptureRequest call)
303 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800304 // give up mInterfaceLock here and then lock it again. Could this lead
305 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 mRequestThread->join();
307 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800309 Mutex::Autolock il(mInterfaceLock);
310 if (mStatusTracker != NULL) {
311 mStatusTracker->join();
312 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800313
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800314 if (mInjectionMethods->isInjecting()) {
315 mInjectionMethods->stopInjection();
316 }
317
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800318 HalInterface* interface;
319 {
320 Mutex::Autolock l(mLock);
321 mRequestThread.clear();
322 Mutex::Autolock stLock(mTrackerLock);
323 mStatusTracker.clear();
324 interface = mInterface.get();
325 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700326
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800327 // Call close without internal mutex held, as the HAL close may need to
328 // wait on assorted callbacks,etc, to complete before it can return.
Ravneet98ffa752022-03-02 07:22:46 +0000329 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700330
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800331 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800332
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800333 {
334 Mutex::Autolock l(mLock);
335 mInterface->clear();
336 mOutputStreams.clear();
337 mInputStream.clear();
338 mDeletedStreams.clear();
339 mBufferManager.clear();
340 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
341 }
342
343 for (auto& weakStream : streams) {
344 sp<Camera3StreamInterface> stream = weakStream.promote();
345 if (stream != nullptr) {
346 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
347 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
348 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700349 }
350 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700351 ALOGI("%s: X", __FUNCTION__);
Ravneet98ffa752022-03-02 07:22:46 +0000352
353 if (mCameraServiceWatchdog != NULL) {
354 mCameraServiceWatchdog->requestExit();
355 mCameraServiceWatchdog.clear();
356 }
357
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700358 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800359}
360
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700361// For dumping/debugging only -
362// try to acquire a lock a few times, eventually give up to proceed with
363// debug/dump operations
364bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
365 bool gotLock = false;
366 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
367 if (lock.tryLock() == NO_ERROR) {
368 gotLock = true;
369 break;
370 } else {
371 usleep(kDumpSleepDuration);
372 }
373 }
374 return gotLock;
375}
376
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800377nsecs_t Camera3Device::getMonoToBoottimeOffset() {
378 // try three times to get the clock offset, choose the one
379 // with the minimum gap in measurements.
380 const int tries = 3;
381 nsecs_t bestGap, measured;
382 for (int i = 0; i < tries; ++i) {
383 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
384 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
385 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
386 const nsecs_t gap = tmono2 - tmono;
387 if (i == 0 || gap < bestGap) {
388 bestGap = gap;
389 measured = tbase - ((tmono + tmono2) >> 1);
390 }
391 }
392 return measured;
393}
394
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800395ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
396 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700397 // Get max jpeg size (area-wise) for default sensor pixel mode
398 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800399 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700400 /*isUltraHighResolutionSensor*/false);
401 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
402 // not ultra high res sensor
403 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700405 /*isUltraHighResolution*/true);
406 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800407 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
408 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700409 return BAD_VALUE;
410 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411 bool useMaxSensorPixelModeThreshold = false;
412 if (uhrMaxJpegResolution.width != 0 &&
413 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
414 // Use the ultra high res max jpeg size and max jpeg buffer size
415 useMaxSensorPixelModeThreshold = true;
416 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700417
Zhijun Hef7da0962014-04-24 13:27:56 -0700418 // Get max jpeg buffer size
419 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800420 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700421 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800422 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
423 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700424 return BAD_VALUE;
425 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700426 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700427
428 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
429 if (useMaxSensorPixelModeThreshold) {
430 maxJpegBufferSize =
431 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
432 maxDefaultJpegResolution, maxJpegBufferSize);
433 chosenMaxJpegResolution = uhrMaxJpegResolution;
434 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800435 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700436
437 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700438 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700439 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800440 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
441 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700442 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800443 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
444 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700445 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700446 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700447 return jpegBufferSize;
448}
449
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800450ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700451 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800452 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700453 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800454 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
455 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700456 return BAD_VALUE;
457 }
458 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
459 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
460 return maxBytesForPointCloud;
461}
462
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800463ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
464 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800465 const int PER_CONFIGURATION_SIZE = 3;
466 const int WIDTH_OFFSET = 0;
467 const int HEIGHT_OFFSET = 1;
468 const int SIZE_OFFSET = 2;
469 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800470 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800471 camera3::SessionConfigurationUtils::getAppropriateModeTag(
472 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
473 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800474 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800475 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800476 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
477 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800478 return BAD_VALUE;
479 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700480
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800481 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
482 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
483 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
484 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
485 }
486 }
487
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
489 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800490 return BAD_VALUE;
491}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700492
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800493status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
494 ATRACE_CALL();
495 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700496
497 // Try to lock, but continue in case of failure (to avoid blocking in
498 // deadlocks)
499 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
500 bool gotLock = tryLockSpinRightRound(mLock);
501
502 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800503 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
504 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700505 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800506 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
507 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700508
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800509 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700510
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800511 String16 templatesOption("-t");
512 int n = args.size();
513 for (int i = 0; i < n; i++) {
514 if (args[i] == templatesOption) {
515 dumpTemplates = true;
516 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000517 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700518 if (i + 1 < n) {
519 String8 monitorTags = String8(args[i + 1]);
520 if (monitorTags == "off") {
521 mTagMonitor.disableMonitoring();
522 } else {
523 mTagMonitor.parseTagsToMonitor(monitorTags);
524 }
525 } else {
526 mTagMonitor.disableMonitoring();
527 }
528 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800529 }
530
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800531 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800532
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800533 const char *status =
534 mStatus == STATUS_ERROR ? "ERROR" :
535 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700536 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
537 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800538 mStatus == STATUS_ACTIVE ? "ACTIVE" :
539 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700540
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800541 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700542 if (mStatus == STATUS_ERROR) {
543 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
544 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800545 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800546 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000547 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
548 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
549 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800550 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800551
552 if (mInputStream != NULL) {
553 write(fd, lines.string(), lines.size());
554 mInputStream->dump(fd, args);
555 } else {
556 lines.appendFormat(" No input stream.\n");
557 write(fd, lines.string(), lines.size());
558 }
559 for (size_t i = 0; i < mOutputStreams.size(); i++) {
560 mOutputStreams[i]->dump(fd,args);
561 }
562
Zhijun He431503c2016-03-07 17:30:16 -0800563 if (mBufferManager != NULL) {
564 lines = String8(" Camera3 Buffer Manager:\n");
565 write(fd, lines.string(), lines.size());
566 mBufferManager->dump(fd, args);
567 }
Zhijun He125684a2015-12-26 15:07:30 -0800568
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700569 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700570 if (mInFlightLock.try_lock()) {
571 if (mInFlightMap.size() == 0) {
572 lines.append(" None\n");
573 } else {
574 for (size_t i = 0; i < mInFlightMap.size(); i++) {
575 InFlightRequest r = mInFlightMap.valueAt(i);
576 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
577 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
578 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
579 r.numBuffersLeft);
580 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700581 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700582 mInFlightLock.unlock();
583 } else {
584 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700585 }
586 write(fd, lines.string(), lines.size());
587
Shuzhen Wang686f6442017-06-20 16:16:04 -0700588 if (mRequestThread != NULL) {
589 mRequestThread->dumpCaptureRequestLatency(fd,
590 " ProcessCaptureRequest latency histogram:");
591 }
592
Igor Murashkin1e479c02013-09-06 16:55:14 -0700593 {
594 lines = String8(" Last request sent:\n");
595 write(fd, lines.string(), lines.size());
596
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700597 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700598 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
599 }
600
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800601 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700602 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800603 "TEMPLATE_PREVIEW",
604 "TEMPLATE_STILL_CAPTURE",
605 "TEMPLATE_VIDEO_RECORD",
606 "TEMPLATE_VIDEO_SNAPSHOT",
607 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800608 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800609 };
610
Emilian Peevf4816702020-04-03 15:44:51 -0700611 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800612 camera_metadata_t *templateRequest = nullptr;
613 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700614 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800615 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800617 lines.append(" Not supported\n");
618 write(fd, lines.string(), lines.size());
619 } else {
620 write(fd, lines.string(), lines.size());
621 dump_indented_camera_metadata(templateRequest,
622 fd, /*verbosity*/2, /*indentation*/8);
623 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800624 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800625 }
626 }
627
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700628 mTagMonitor.dumpMonitoredMetadata(fd);
629
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800630 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800631 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800632 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800633 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800634 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800635
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700636 if (gotLock) mLock.unlock();
637 if (gotInterfaceLock) mInterfaceLock.unlock();
638
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800639 return OK;
640}
641
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700642status_t Camera3Device::startWatchingTags(const String8 &tags) {
643 mTagMonitor.parseTagsToMonitor(tags);
644 return OK;
645}
646
647status_t Camera3Device::stopWatchingTags() {
648 mTagMonitor.disableMonitoring();
649 return OK;
650}
651
652status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
653 mTagMonitor.getLatestMonitoredTagEvents(out);
654 return OK;
655}
656
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800657const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800658 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800659 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
660 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700661 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800662 mStatus == STATUS_ERROR ?
663 "when in error state" : "before init");
664 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700665 if (physicalId.isEmpty()) {
666 return mDeviceInfo;
667 } else {
668 std::string id(physicalId.c_str());
669 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
670 return mPhysicalDeviceInfoMap.at(id);
671 } else {
672 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
673 return mDeviceInfo;
674 }
675 }
676}
677
678const CameraMetadata& Camera3Device::info() const {
679 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800680 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800681}
682
Jianing Wei90e59c92014-03-12 18:29:36 -0700683status_t Camera3Device::checkStatusOkToCaptureLocked() {
684 switch (mStatus) {
685 case STATUS_ERROR:
686 CLOGE("Device has encountered a serious error");
687 return INVALID_OPERATION;
688 case STATUS_UNINITIALIZED:
689 CLOGE("Device not initialized");
690 return INVALID_OPERATION;
691 case STATUS_UNCONFIGURED:
692 case STATUS_CONFIGURED:
693 case STATUS_ACTIVE:
694 // OK
695 break;
696 default:
697 SET_ERR_L("Unexpected status: %d", mStatus);
698 return INVALID_OPERATION;
699 }
700 return OK;
701}
702
703status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000704 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700705 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700706 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700707 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700708 if (requestList == NULL) {
709 CLOGE("requestList cannot be NULL.");
710 return BAD_VALUE;
711 }
712
Jianing Weicb0652e2014-03-12 18:29:36 -0700713 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000714 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700715 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
716 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
717 ++metadataIt, ++surfaceMapIt) {
718 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700719 if (newRequest == 0) {
720 CLOGE("Can't create capture request");
721 return BAD_VALUE;
722 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700723
Shuzhen Wang9d066012016-09-30 11:30:20 -0700724 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700725 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700726
Jianing Weicb0652e2014-03-12 18:29:36 -0700727 // Setup burst Id and request Id
728 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800729 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
730 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700731 CLOGE("RequestID does not exist in metadata");
732 return BAD_VALUE;
733 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800734 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700735
Jianing Wei90e59c92014-03-12 18:29:36 -0700736 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700737
738 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700739 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700740 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
741 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
742 return BAD_VALUE;
743 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700744
745 // Setup batch size if this is a high speed video recording request.
746 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
747 auto firstRequest = requestList->begin();
748 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
749 if (outputStream->isVideoStream()) {
750 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800751 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700752 break;
753 }
754 }
755 }
756
Jianing Wei90e59c92014-03-12 18:29:36 -0700757 return OK;
758}
759
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800760status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800762
Emilian Peevaebbe412018-01-15 13:53:24 +0000763 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700764 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000765 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700766
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800767 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700768}
769
Emilian Peevaebbe412018-01-15 13:53:24 +0000770void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700771 std::list<const SurfaceMap>& surfaceMaps,
772 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 PhysicalCameraSettingsList requestList;
774 requestList.push_back({std::string(getId().string()), request});
775 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700776
777 SurfaceMap surfaceMap;
778 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
779 // With no surface list passed in, stream and surface will have 1-to-1
780 // mapping. So the surface index is 0 for each stream in the surfaceMap.
781 for (size_t i = 0; i < streams.count; i++) {
782 surfaceMap[streams.data.i32[i]].push_back(0);
783 }
784 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800785}
786
Jianing Wei90e59c92014-03-12 18:29:36 -0700787status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000788 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700789 const std::list<const SurfaceMap> &surfaceMaps,
790 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700791 /*out*/
792 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700793 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700794 nsecs_t requestTimeNs = systemTime();
795
Jianing Wei90e59c92014-03-12 18:29:36 -0700796 Mutex::Autolock il(mInterfaceLock);
797 Mutex::Autolock l(mLock);
798
799 status_t res = checkStatusOkToCaptureLocked();
800 if (res != OK) {
801 // error logged by previous call
802 return res;
803 }
804
805 RequestList requestList;
806
Shuzhen Wang0129d522016-10-30 22:43:41 -0700807 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700808 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700809 if (res != OK) {
810 // error logged by previous call
811 return res;
812 }
813
814 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700815 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700816 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700817 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700818 }
819
820 if (res == OK) {
821 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
822 if (res != OK) {
823 SET_ERR_L("Can't transition to active in %f seconds!",
824 kActiveTimeout/1e9);
825 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800826 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700827 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700828 } else {
829 CLOGE("Cannot queue request. Impossible.");
830 return BAD_VALUE;
831 }
832
833 return res;
834}
835
Emilian Peevaebbe412018-01-15 13:53:24 +0000836status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700837 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700838 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700839 ATRACE_CALL();
840
Emilian Peevaebbe412018-01-15 13:53:24 +0000841 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700842}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800843
Jianing Weicb0652e2014-03-12 18:29:36 -0700844status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
845 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800847
Emilian Peevaebbe412018-01-15 13:53:24 +0000848 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700849 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851
Emilian Peevaebbe412018-01-15 13:53:24 +0000852 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700853 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800854}
855
Emilian Peevaebbe412018-01-15 13:53:24 +0000856status_t Camera3Device::setStreamingRequestList(
857 const List<const PhysicalCameraSettingsList> &requestsList,
858 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 ATRACE_CALL();
860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700862}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863
864sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000865 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800866 status_t res;
867
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700868 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800869 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
870 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700872 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700873 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800874 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700875 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700877 } else if (mStatus == STATUS_UNCONFIGURED) {
878 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700879 CLOGE("No streams configured");
880 return NULL;
881 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800882 }
883
Shuzhen Wang0129d522016-10-30 22:43:41 -0700884 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800885 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800886}
887
Jianing Weicb0652e2014-03-12 18:29:36 -0700888status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800889 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700890 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800892
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800893 switch (mStatus) {
894 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700895 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800896 return INVALID_OPERATION;
897 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700898 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800899 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700900 case STATUS_UNCONFIGURED:
901 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 case STATUS_ACTIVE:
903 // OK
904 break;
905 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700906 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800907 return INVALID_OPERATION;
908 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800909 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700910
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700911 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800912}
913
914status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
915 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700916 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800917
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700918 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800919}
920
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700921status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800922 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700923 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700924 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700925 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700926 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800927 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
928 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700929
930 status_t res;
931 bool wasActive = false;
932
933 switch (mStatus) {
934 case STATUS_ERROR:
935 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
936 return INVALID_OPERATION;
937 case STATUS_UNINITIALIZED:
938 ALOGE("%s: Device not initialized", __FUNCTION__);
939 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700940 case STATUS_UNCONFIGURED:
941 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942 // OK
943 break;
944 case STATUS_ACTIVE:
945 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700946 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700947 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700948 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700949 return res;
950 }
951 wasActive = true;
952 break;
953 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700954 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955 return INVALID_OPERATION;
956 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700957 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700958
959 if (mInputStream != 0) {
960 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
961 return INVALID_OPERATION;
962 }
963
964 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
965 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700966 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700967
968 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800969 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700970
971 *id = mNextStreamId++;
972
973 // Continue captures if active at start
974 if (wasActive) {
975 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100976 // Reuse current operating mode and session parameters for new stream config
977 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700978 if (res != OK) {
979 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
980 __FUNCTION__, mNextStreamId, strerror(-res), res);
981 return res;
982 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700983 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700984 }
985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700987 return OK;
988}
989
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700990status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700991 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700992 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800993 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800994 const std::unordered_set<int32_t> &sensorPixelModesUsed,
995 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800996 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800997 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700998 ATRACE_CALL();
999
1000 if (consumer == nullptr) {
1001 ALOGE("%s: consumer must not be null", __FUNCTION__);
1002 return BAD_VALUE;
1003 }
1004
1005 std::vector<sp<Surface>> consumers;
1006 consumers.push_back(consumer);
1007
1008 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001009 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001010 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001011 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001012}
1013
1014static bool isRawFormat(int format) {
1015 switch (format) {
1016 case HAL_PIXEL_FORMAT_RAW16:
1017 case HAL_PIXEL_FORMAT_RAW12:
1018 case HAL_PIXEL_FORMAT_RAW10:
1019 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1020 return true;
1021 default:
1022 return false;
1023 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001024}
1025
1026status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1027 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001028 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001029 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001030 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001031 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1032 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001033 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001034
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001035 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001036 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001037 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001038 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001039 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001040 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1041 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001042 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001043 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001044 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001045
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001046 status_t res;
1047 bool wasActive = false;
1048
1049 switch (mStatus) {
1050 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001051 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001052 return INVALID_OPERATION;
1053 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001054 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001055 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001056 case STATUS_UNCONFIGURED:
1057 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058 // OK
1059 break;
1060 case STATUS_ACTIVE:
1061 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001062 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001063 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001064 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001065 return res;
1066 }
1067 wasActive = true;
1068 break;
1069 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001070 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001071 return INVALID_OPERATION;
1072 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001073 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001074
1075 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001076
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 if (consumers.size() == 0 && !hasDeferredConsumer) {
1078 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1079 return BAD_VALUE;
1080 }
Zhijun He5d677d12016-05-29 16:52:39 -07001081
Shuzhen Wang0129d522016-10-30 22:43:41 -07001082 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001083 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1084 return BAD_VALUE;
1085 }
1086
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001087 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1088 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1089 // be found in only one sensor pixel mode.
1090 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1091 return BAD_VALUE;
1092 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001093 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001094 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001095 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001096 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001097 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001098 if (blobBufferSize <= 0) {
1099 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1100 return BAD_VALUE;
1101 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001102 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1103 blobBufferSize = width * height;
1104 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001105 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001106 if (blobBufferSize <= 0) {
1107 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1108 return BAD_VALUE;
1109 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001110 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001111 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001112 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001113 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001114 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001115 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001116 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001117 bool maxResolution =
1118 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1119 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001120 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1121 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001122 if (rawOpaqueBufferSize <= 0) {
1123 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1124 return BAD_VALUE;
1125 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001126 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001127 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001128 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001129 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001130 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001131 } else if (isShared) {
1132 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1133 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001134 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001135 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001136 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001137 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001138 newStream = new Camera3OutputStream(mNextStreamId,
1139 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001140 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001141 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001142 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001144 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001145 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001146 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001147 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001148 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149 }
Emilian Peev40ead602017-09-26 15:46:36 +01001150
1151 size_t consumerCount = consumers.size();
1152 for (size_t i = 0; i < consumerCount; i++) {
1153 int id = newStream->getSurfaceId(consumers[i]);
1154 if (id < 0) {
1155 SET_ERR_L("Invalid surface id");
1156 return BAD_VALUE;
1157 }
1158 if (surfaceIds != nullptr) {
1159 surfaceIds->push_back(id);
1160 }
1161 }
1162
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001164
Emilian Peev08dd2452017-04-06 16:55:14 +01001165 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001166
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001167 newStream->setImageDumpMask(mImageDumpMask);
1168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001169 res = mOutputStreams.add(mNextStreamId, newStream);
1170 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001171 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001172 return res;
1173 }
1174
Shuzhen Wang316781a2020-08-18 18:11:01 -07001175 mSessionStatsBuilder.addStream(mNextStreamId);
1176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001178 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179
1180 // Continue captures if active at start
1181 if (wasActive) {
1182 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001183 // Reuse current operating mode and session parameters for new stream config
1184 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001186 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1187 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188 return res;
1189 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001190 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001192 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001194}
1195
Emilian Peev710c1422017-08-30 11:19:38 +01001196status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001197 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001198 if (nullptr == streamInfo) {
1199 return BAD_VALUE;
1200 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001201 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001203
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 switch (mStatus) {
1205 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001206 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 return INVALID_OPERATION;
1208 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001209 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001211 case STATUS_UNCONFIGURED:
1212 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213 case STATUS_ACTIVE:
1214 // OK
1215 break;
1216 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001217 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 return INVALID_OPERATION;
1219 }
1220
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001221 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1222 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001223 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001224 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 }
1226
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001227 streamInfo->width = stream->getWidth();
1228 streamInfo->height = stream->getHeight();
1229 streamInfo->format = stream->getFormat();
1230 streamInfo->dataSpace = stream->getDataSpace();
1231 streamInfo->formatOverridden = stream->isFormatOverridden();
1232 streamInfo->originalFormat = stream->getOriginalFormat();
1233 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1234 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001235 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001237}
1238
1239status_t Camera3Device::setStreamTransform(int id,
1240 int transform) {
1241 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 switch (mStatus) {
1246 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001247 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return INVALID_OPERATION;
1249 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001250 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001252 case STATUS_UNCONFIGURED:
1253 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 case STATUS_ACTIVE:
1255 // OK
1256 break;
1257 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 }
1261
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001262 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1263 if (stream == nullptr) {
1264 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return BAD_VALUE;
1266 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001267 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001268}
1269
1270status_t Camera3Device::deleteStream(int id) {
1271 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001272 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 Mutex::Autolock l(mLock);
1274 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001276 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001277
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 // CameraDevice semantics require device to already be idle before
1279 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001281 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001282 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001283 }
1284
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001285 if (mStatus == STATUS_ERROR) {
1286 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1287 __FUNCTION__, mId.string());
1288 return -EBUSY;
1289 }
1290
Igor Murashkin2fba5842013-04-22 14:03:54 -07001291 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001292 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 if (mInputStream != NULL && id == mInputStream->getId()) {
1294 deletedStream = mInputStream;
1295 mInputStream.clear();
1296 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001297 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001298 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 return BAD_VALUE;
1300 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001301 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001302 }
1303
1304 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001305 if (stream != nullptr) {
1306 deletedStream = stream;
1307 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 }
1309
1310 // Free up the stream endpoint so that it can be used by some other stream
1311 res = deletedStream->disconnect();
1312 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001313 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001314 // fall through since we want to still list the stream as deleted.
1315 }
1316 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001317 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001318
1319 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001320}
1321
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001322status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001323 ATRACE_CALL();
1324 ALOGV("%s: E", __FUNCTION__);
1325
1326 Mutex::Autolock il(mInterfaceLock);
1327 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001328
Emilian Peev811d2952018-05-25 11:08:40 +01001329 // In case the client doesn't include any session parameter, try a
1330 // speculative configuration using the values from the last cached
1331 // default request.
1332 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001333 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001334 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1335 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1336 mLastTemplateId);
1337 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1338 operatingMode);
1339 }
1340
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001341 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1342}
1343
1344status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1345 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001346 //Filter out any incoming session parameters
1347 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001348 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1349 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001350 CameraMetadata filteredParams(availableSessionKeys.count);
1351 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1352 filteredParams.getAndLock());
1353 set_camera_metadata_vendor_id(meta, mVendorTagId);
1354 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001355 if (availableSessionKeys.count > 0) {
1356 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1357 camera_metadata_ro_entry entry = params.find(
1358 availableSessionKeys.data.i32[i]);
1359 if (entry.count > 0) {
1360 filteredParams.update(entry);
1361 }
1362 }
1363 }
1364
1365 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001366}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001367
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001368status_t Camera3Device::getInputBufferProducer(
1369 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001370 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001371 Mutex::Autolock il(mInterfaceLock);
1372 Mutex::Autolock l(mLock);
1373
1374 if (producer == NULL) {
1375 return BAD_VALUE;
1376 } else if (mInputStream == NULL) {
1377 return INVALID_OPERATION;
1378 }
1379
1380 return mInputStream->getInputBufferProducer(producer);
1381}
1382
Emilian Peevf4816702020-04-03 15:44:51 -07001383status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001384 CameraMetadata *request) {
1385 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001386 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001387
Emilian Peevf4816702020-04-03 15:44:51 -07001388 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001389 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001390 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001391 return BAD_VALUE;
1392 }
1393
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001394 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001396 {
1397 Mutex::Autolock l(mLock);
1398 switch (mStatus) {
1399 case STATUS_ERROR:
1400 CLOGE("Device has encountered a serious error");
1401 return INVALID_OPERATION;
1402 case STATUS_UNINITIALIZED:
1403 CLOGE("Device is not initialized!");
1404 return INVALID_OPERATION;
1405 case STATUS_UNCONFIGURED:
1406 case STATUS_CONFIGURED:
1407 case STATUS_ACTIVE:
1408 // OK
1409 break;
1410 default:
1411 SET_ERR_L("Unexpected status: %d", mStatus);
1412 return INVALID_OPERATION;
1413 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001414
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001415 if (!mRequestTemplateCache[templateId].isEmpty()) {
1416 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001417 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001418 return OK;
1419 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001420 }
1421
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001422 camera_metadata_t *rawRequest;
1423 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001424 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001425
1426 {
1427 Mutex::Autolock l(mLock);
1428 if (res == BAD_VALUE) {
1429 ALOGI("%s: template %d is not supported on this camera device",
1430 __FUNCTION__, templateId);
1431 return res;
1432 } else if (res != OK) {
1433 CLOGE("Unable to construct request template %d: %s (%d)",
1434 templateId, strerror(-res), res);
1435 return res;
1436 }
1437
1438 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1439 mRequestTemplateCache[templateId].acquire(rawRequest);
1440
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001441 // Override the template request with zoomRatioMapper
1442 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1443 &mRequestTemplateCache[templateId]);
1444 if (res != OK) {
1445 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1446 templateId, strerror(-res), res);
1447 return res;
1448 }
1449
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001450 // Fill in JPEG_QUALITY if not available
1451 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1452 static const uint8_t kDefaultJpegQuality = 95;
1453 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1454 &kDefaultJpegQuality, 1);
1455 }
1456
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001457 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001458 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001460 return OK;
1461}
1462
1463status_t Camera3Device::waitUntilDrained() {
1464 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001465 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001466 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001468
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001469 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001470}
1471
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001472status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 switch (mStatus) {
1474 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001475 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 ALOGV("%s: Already idle", __FUNCTION__);
1477 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478 case STATUS_CONFIGURED:
1479 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 case STATUS_ERROR:
1481 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 break;
1484 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001485 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 return INVALID_OPERATION;
1487 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001488 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1489 maxExpectedDuration);
1490 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001491 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001492 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001493 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1494 res);
1495 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 return res;
1497}
1498
Ruben Brunk183f0562015-08-12 12:55:02 -07001499void Camera3Device::internalUpdateStatusLocked(Status status) {
1500 mStatus = status;
1501 mRecentStatusUpdates.add(mStatus);
1502 mStatusChanged.broadcast();
1503}
1504
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001506status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001507 if (mRequestThread.get() != nullptr) {
1508 mRequestThread->setPaused(true);
1509 } else {
1510 return NO_INIT;
1511 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001512
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001513 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1514 maxExpectedDuration);
1515 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 if (res != OK) {
1517 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001518 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 }
1520
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 return res;
1522}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524// Resume after internalPauseAndWaitLocked
1525status_t Camera3Device::internalResumeLocked() {
1526 status_t res;
1527
1528 mRequestThread->setPaused(false);
1529
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001530 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1531 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1533 if (res != OK) {
1534 SET_ERR_L("Can't transition to active in %f seconds!",
1535 kActiveTimeout/1e9);
1536 }
1537 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001539}
1540
Ruben Brunk183f0562015-08-12 12:55:02 -07001541status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001543
1544 size_t startIndex = 0;
1545 if (mStatusWaiters == 0) {
1546 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1547 // this status list
1548 mRecentStatusUpdates.clear();
1549 } else {
1550 // If other threads are waiting on updates to this status list, set the position of the
1551 // first element that this list will check rather than clearing the list.
1552 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 }
1554
Ruben Brunk183f0562015-08-12 12:55:02 -07001555 mStatusWaiters++;
1556
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001557 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001558 if (!active && mUseHalBufManager) {
1559 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001560 if (mStatus == STATUS_ACTIVE) {
1561 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001562 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001563 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001564 mRequestBufferSM.onWaitUntilIdle();
1565 }
1566
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001568 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001570 if (active == (mStatus == STATUS_ACTIVE)) {
1571 // Desired state is current
1572 break;
1573 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001575 nsecs_t timeElapsed = systemTime() - startTime;
1576 nsecs_t timeToWait = timeout - timeElapsed;
1577 if (timeToWait <= 0) {
1578 // Thread woke up spuriously but has timed out since.
1579 // Force out of loop with TIMED_OUT result.
1580 res = TIMED_OUT;
1581 break;
1582 }
1583 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 if (res != OK) break;
1585
Ruben Brunk183f0562015-08-12 12:55:02 -07001586 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1587 // transitions.
1588 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1589 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1590 __FUNCTION__);
1591
1592 // Encountered desired state since we began waiting
1593 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1595 stateSeen = true;
1596 break;
1597 }
1598 }
1599 } while (!stateSeen);
1600
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001601 if (signalPipelineDrain) {
1602 mRequestThread->resetPipelineDrain();
1603 }
1604
Ruben Brunk183f0562015-08-12 12:55:02 -07001605 mStatusWaiters--;
1606
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001607 return res;
1608}
1609
1610
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001611status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001612 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001613 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001615 if (listener != NULL && mListener != NULL) {
1616 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1617 }
1618 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001619 mRequestThread->setNotificationListener(listener);
1620 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001621
1622 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001623}
1624
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001625bool Camera3Device::willNotify3A() {
1626 return false;
1627}
1628
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001629status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001630 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001631 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001633 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001634 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1635 if (st == std::cv_status::timeout) {
1636 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001637 }
1638 }
1639 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001640}
1641
Jianing Weicb0652e2014-03-12 18:29:36 -07001642status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001644 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001645
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001646 if (mResultQueue.empty()) {
1647 return NOT_ENOUGH_DATA;
1648 }
1649
Jianing Weicb0652e2014-03-12 18:29:36 -07001650 if (frame == NULL) {
1651 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1652 return BAD_VALUE;
1653 }
1654
1655 CaptureResult &result = *(mResultQueue.begin());
1656 frame->mResultExtras = result.mResultExtras;
1657 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001658 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001659 mResultQueue.erase(mResultQueue.begin());
1660
1661 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662}
1663
1664status_t Camera3Device::triggerAutofocus(uint32_t id) {
1665 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001666 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001667
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001668 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1669 // Mix-in this trigger into the next request and only the next request.
1670 RequestTrigger trigger[] = {
1671 {
1672 ANDROID_CONTROL_AF_TRIGGER,
1673 ANDROID_CONTROL_AF_TRIGGER_START
1674 },
1675 {
1676 ANDROID_CONTROL_AF_TRIGGER_ID,
1677 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001678 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001679 };
1680
1681 return mRequestThread->queueTrigger(trigger,
1682 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001683}
1684
1685status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1686 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001687 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001688
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001689 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1690 // Mix-in this trigger into the next request and only the next request.
1691 RequestTrigger trigger[] = {
1692 {
1693 ANDROID_CONTROL_AF_TRIGGER,
1694 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1695 },
1696 {
1697 ANDROID_CONTROL_AF_TRIGGER_ID,
1698 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001699 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001700 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001701
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001702 return mRequestThread->queueTrigger(trigger,
1703 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001704}
1705
1706status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1707 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001708 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001709
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001710 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1711 // Mix-in this trigger into the next request and only the next request.
1712 RequestTrigger trigger[] = {
1713 {
1714 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1715 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1716 },
1717 {
1718 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1719 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001720 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001721 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001722
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001723 return mRequestThread->queueTrigger(trigger,
1724 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001725}
1726
Jianing Weicb0652e2014-03-12 18:29:36 -07001727status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001728 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001729 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001730 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001731
Zhijun He7ef20392014-04-21 16:04:17 -07001732 {
1733 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001734
1735 // b/116514106 "disconnect()" can get called twice for the same device. The
1736 // camera device will not be initialized during the second run.
1737 if (mStatus == STATUS_UNINITIALIZED) {
1738 return OK;
1739 }
1740
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001741 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001742
1743 // Stop session and stream counter
1744 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001745 }
1746
Ravneet98ffa752022-03-02 07:22:46 +00001747 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal72c96652022-06-29 01:34:01 +00001748 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneet98ffa752022-03-02 07:22:46 +00001749 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1750 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1751
1752 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001753}
1754
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001755status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001756 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1757}
1758
1759status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001760 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001761 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001762 Mutex::Autolock il(mInterfaceLock);
1763 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001764
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001765 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1766 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001767 CLOGE("Stream %d does not exist", streamId);
1768 return BAD_VALUE;
1769 }
1770
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001771 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001772 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001773 return BAD_VALUE;
1774 }
1775
1776 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001777 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001778 return BAD_VALUE;
1779 }
1780
Ruben Brunkc78ac262015-08-13 17:58:46 -07001781 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001782}
1783
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001784status_t Camera3Device::tearDown(int streamId) {
1785 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001786 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001787 Mutex::Autolock il(mInterfaceLock);
1788 Mutex::Autolock l(mLock);
1789
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001790 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1791 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001792 CLOGE("Stream %d does not exist", streamId);
1793 return BAD_VALUE;
1794 }
1795
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001796 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1797 CLOGE("Stream %d is a target of a in-progress request", streamId);
1798 return BAD_VALUE;
1799 }
1800
1801 return stream->tearDown();
1802}
1803
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001804status_t Camera3Device::addBufferListenerForStream(int streamId,
1805 wp<Camera3StreamBufferListener> listener) {
1806 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001807 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001808 Mutex::Autolock il(mInterfaceLock);
1809 Mutex::Autolock l(mLock);
1810
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001811 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1812 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001813 CLOGE("Stream %d does not exist", streamId);
1814 return BAD_VALUE;
1815 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001816 stream->addBufferListener(listener);
1817
1818 return OK;
1819}
1820
Austin Borger4a870a32022-02-25 01:48:41 +00001821float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1822 camera_metadata_entry minDurations =
1823 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1824 for (size_t i = 0; i < minDurations.count; i += 4) {
1825 if (minDurations.data.i64[i] == stream->getFormat()
1826 && minDurations.data.i64[i+1] == stream->getWidth()
1827 && minDurations.data.i64[i+2] == stream->getHeight()) {
1828 int64_t minFrameDuration = minDurations.data.i64[i+3];
1829 return 1e9f / minFrameDuration;
1830 }
1831 }
1832 return 0.0f;
1833}
1834
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001836 * Methods called by subclasses
1837 */
1838
1839void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001840 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001841 std::vector<int> streamIds;
1842 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001843 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001844
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845 {
1846 // Need mLock to safely update state and synchronize to current
1847 // state of methods in flight.
1848 Mutex::Autolock l(mLock);
1849 // We can get various system-idle notices from the status tracker
1850 // while starting up. Only care about them if we've actually sent
1851 // in some requests recently.
1852 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1853 return;
1854 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001855 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1856 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001857 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858
1859 // Skip notifying listener if we're doing some user-transparent
1860 // state changes
1861 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001862
Austin Borger4a870a32022-02-25 01:48:41 +00001863 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1864 auto stream = mOutputStreams[i];
1865 if (stream.get() == nullptr) continue;
1866
1867 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1868 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1869
1870 // Populate stream statistics in case of Idle
1871 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001872 streamIds.push_back(stream->getId());
1873 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1874 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001875 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001876 if (camera3Stream != nullptr) {
1877 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001878 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001879 }
1880 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001881 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001882 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001883 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001884 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001885 }
1886 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001887 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001888
1889 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001891 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001892 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001893 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001894 status_t res = OK;
1895 if (listener != nullptr) {
1896 if (idle) {
1897 // Get session stats from the builder, and notify the listener.
1898 int64_t requestCount, resultErrorCount;
1899 bool deviceError;
1900 std::map<int, StreamStats> streamStatsMap;
1901 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1902 &deviceError, &streamStatsMap);
1903 for (size_t i = 0; i < streamIds.size(); i++) {
1904 int streamId = streamIds[i];
1905 auto stats = streamStatsMap.find(streamId);
1906 if (stats != streamStatsMap.end()) {
1907 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1908 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1909 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1910 streamStats[i].mHistogramType =
1911 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1912 streamStats[i].mHistogramBins.assign(
1913 stats->second.mCaptureLatencyBins.begin(),
1914 stats->second.mCaptureLatencyBins.end());
1915 streamStats[i].mHistogramCounts.assign(
1916 stats->second.mCaptureLatencyHistogram.begin(),
1917 stats->second.mCaptureLatencyHistogram.end());
1918 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001919 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001920 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1921 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001922 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001923 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001924 }
1925 if (res != OK) {
1926 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1927 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001928 }
1929}
1930
Shuzhen Wang758c2152017-01-10 18:26:18 -08001931status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001932 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001933 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001934 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1935 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001936
1937 if (surfaceIds == nullptr) {
1938 return BAD_VALUE;
1939 }
1940
Zhijun He5d677d12016-05-29 16:52:39 -07001941 Mutex::Autolock il(mInterfaceLock);
1942 Mutex::Autolock l(mLock);
1943
Shuzhen Wang758c2152017-01-10 18:26:18 -08001944 if (consumers.size() == 0) {
1945 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001946 return BAD_VALUE;
1947 }
1948
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001949 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1950 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001951 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001952 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001953 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001954
1955 // isConsumerConfigurationDeferred will be off after setConsumers
1956 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001957 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001958 if (res != OK) {
1959 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1960 return res;
1961 }
1962
Emilian Peev40ead602017-09-26 15:46:36 +01001963 for (auto &consumer : consumers) {
1964 int id = stream->getSurfaceId(consumer);
1965 if (id < 0) {
1966 CLOGE("Invalid surface id!");
1967 return BAD_VALUE;
1968 }
1969 surfaceIds->push_back(id);
1970 }
1971
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001972 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001973 if (!stream->isConfiguring()) {
1974 CLOGE("Stream %d was already fully configured.", streamId);
1975 return INVALID_OPERATION;
1976 }
Zhijun He5d677d12016-05-29 16:52:39 -07001977
Shuzhen Wang0129d522016-10-30 22:43:41 -07001978 res = stream->finishConfiguration();
1979 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001980 // If finishConfiguration fails due to abandoned surface, do not set
1981 // device to error state.
1982 bool isSurfaceAbandoned =
1983 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1984 if (!isSurfaceAbandoned) {
1985 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1986 stream->getId(), strerror(-res), res);
1987 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001988 return res;
1989 }
Zhijun He5d677d12016-05-29 16:52:39 -07001990 }
1991
1992 return OK;
1993}
1994
Emilian Peev40ead602017-09-26 15:46:36 +01001995status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1996 const std::vector<OutputStreamInfo> &outputInfo,
1997 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
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) {
Emilian Peev40ead602017-09-26 15:46:36 +01002003 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002004 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002005 }
2006
2007 for (const auto &it : removedSurfaceIds) {
2008 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2009 CLOGE("Shared surface still part of a pending request!");
2010 return -EBUSY;
2011 }
2012 }
2013
Emilian Peev40ead602017-09-26 15:46:36 +01002014 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2015 if (res != OK) {
2016 CLOGE("Stream %d failed to update stream (error %d %s) ",
2017 streamId, res, strerror(-res));
2018 if (res == UNKNOWN_ERROR) {
2019 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2020 __FUNCTION__);
2021 }
2022 return res;
2023 }
2024
2025 return res;
2026}
2027
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002028status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2029 Mutex::Autolock il(mInterfaceLock);
2030 Mutex::Autolock l(mLock);
2031
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002032 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2033 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002034 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2035 return BAD_VALUE;
2036 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002037
2038 if (dropping) {
2039 mSessionStatsBuilder.stopCounter(streamId);
2040 } else {
2041 mSessionStatsBuilder.startCounter(streamId);
2042 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002043 return stream->dropBuffers(dropping);
2044}
2045
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002046/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002047 * Camera3Device private methods
2048 */
2049
2050sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002051 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002054 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002055 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056
2057 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002058 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002059 if (inputStreams.count > 0) {
2060 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002061 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002062 CLOGE("Request references unknown input stream %d",
2063 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 return NULL;
2065 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002066
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002068 SET_ERR_L("%s: input stream %d is not configured!",
2069 __FUNCTION__, mInputStream->getId());
2070 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002072 // Check if stream prepare is blocking requests.
2073 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002074 CLOGE("Request references an input stream that's being prepared!");
2075 return NULL;
2076 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002077
2078 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002079 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080 }
2081
2082 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002083 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002085 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002086 return NULL;
2087 }
2088
2089 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002090 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2091 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002092 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002093 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094 return NULL;
2095 }
Zhijun He5d677d12016-05-29 16:52:39 -07002096 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002097 auto iter = surfaceMap.find(streams.data.i32[i]);
2098 if (iter != surfaceMap.end()) {
2099 const std::vector<size_t>& surfaces = iter->second;
2100 for (const auto& surface : surfaces) {
2101 if (stream->isConsumerConfigurationDeferred(surface)) {
2102 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2103 "due to deferred consumer", stream->getId(), surface);
2104 return NULL;
2105 }
2106 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002107 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002108 }
2109
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002111 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2112 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002114 // Check if stream prepare is blocking requests.
2115 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002116 CLOGE("Request references an output stream that's being prepared!");
2117 return NULL;
2118 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119
2120 newRequest->mOutputStreams.push(stream);
2121 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002122 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002123 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002124
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002125 auto rotateAndCropEntry =
2126 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2127 if (rotateAndCropEntry.count > 0 &&
2128 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2129 newRequest->mRotateAndCropAuto = true;
2130 } else {
2131 newRequest->mRotateAndCropAuto = false;
2132 }
2133
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002134 auto zoomRatioEntry =
2135 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2136 if (zoomRatioEntry.count > 0 &&
2137 zoomRatioEntry.data.f[0] == 1.0f) {
2138 newRequest->mZoomRatioIs1x = true;
2139 } else {
2140 newRequest->mZoomRatioIs1x = false;
2141 }
2142
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002143 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002144 for (auto& settings : newRequest->mSettingsList) {
2145 auto testPatternModeEntry =
2146 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2147 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2148 testPatternModeEntry.data.i32[0] :
2149 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002150
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002151 auto testPatternDataEntry =
2152 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2153 if (testPatternDataEntry.count >= 4) {
2154 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2155 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2156 } else {
2157 settings.mOriginalTestPatternData[0] = 0;
2158 settings.mOriginalTestPatternData[1] = 0;
2159 settings.mOriginalTestPatternData[2] = 0;
2160 settings.mOriginalTestPatternData[3] = 0;
2161 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002162 }
2163 }
2164
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002165 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002166}
2167
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002168void Camera3Device::cancelStreamsConfigurationLocked() {
2169 int res = OK;
2170 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2171 res = mInputStream->cancelConfiguration();
2172 if (res != OK) {
2173 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2174 mInputStream->getId(), strerror(-res), res);
2175 }
2176 }
2177
2178 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002179 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002180 if (outputStream->isConfiguring()) {
2181 res = outputStream->cancelConfiguration();
2182 if (res != OK) {
2183 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2184 outputStream->getId(), strerror(-res), res);
2185 }
2186 }
2187 }
2188
2189 // Return state to that at start of call, so that future configures
2190 // properly clean things up
2191 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2192 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002193
2194 res = mPreparerThread->resume();
2195 if (res != OK) {
2196 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2197 }
2198}
2199
Emilian Peev0d0191e2020-04-21 17:01:18 -07002200bool Camera3Device::checkAbandonedStreamsLocked() {
2201 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2202 return true;
2203 }
2204
2205 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2206 auto stream = mOutputStreams[i];
2207 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2208 return true;
2209 }
2210 }
2211
2212 return false;
2213}
2214
Emilian Peev3bead5f2020-05-28 17:29:08 -07002215bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002216 ATRACE_CALL();
2217 bool ret = false;
2218
Shuzhen Wang316781a2020-08-18 18:11:01 -07002219 nsecs_t startTime = systemTime();
2220
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002221 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002222 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2223
2224 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002225 if (checkAbandonedStreamsLocked()) {
2226 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2227 __FUNCTION__);
2228 return true;
2229 }
2230
Emilian Peev3bead5f2020-05-28 17:29:08 -07002231 status_t rc = NO_ERROR;
2232 bool markClientActive = false;
2233 if (mStatus == STATUS_ACTIVE) {
2234 markClientActive = true;
2235 mPauseStateNotify = true;
2236 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2237
2238 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2239 }
2240
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002241 if (rc == NO_ERROR) {
2242 mNeedConfig = true;
2243 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2244 if (rc == NO_ERROR) {
2245 ret = true;
2246 mPauseStateNotify = false;
2247 //Moving to active state while holding 'mLock' is important.
2248 //There could be pending calls to 'create-/deleteStream' which
2249 //will trigger another stream configuration while the already
2250 //present streams end up with outstanding buffers that will
2251 //not get drained.
2252 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002253 } else if (rc == DEAD_OBJECT) {
2254 // DEAD_OBJECT can be returned if either the consumer surface is
2255 // abandoned, or the HAL has died.
2256 // - If the HAL has died, configureStreamsLocked call will set
2257 // device to error state,
2258 // - If surface is abandoned, we should not set device to error
2259 // state.
2260 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002261 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002262 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002263 }
2264 } else {
2265 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2266 }
2267
Shuzhen Wang316781a2020-08-18 18:11:01 -07002268 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2269 ns2ms(systemTime() - startTime));
2270
Emilian Peev3bead5f2020-05-28 17:29:08 -07002271 if (markClientActive) {
2272 mStatusTracker->markComponentActive(clientStatusId);
2273 }
2274
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002275 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002276}
2277
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002278status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002279 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002280 ATRACE_CALL();
2281 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002282
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002283 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002284 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002285 return INVALID_OPERATION;
2286 }
2287
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002288 if (operatingMode < 0) {
2289 CLOGE("Invalid operating mode: %d", operatingMode);
2290 return BAD_VALUE;
2291 }
2292
2293 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002294 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002295
2296 if (mOperatingMode != operatingMode) {
2297 mNeedConfig = true;
2298 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2299 mOperatingMode = operatingMode;
2300 }
2301
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002302 // Reset min expected duration when session is reconfigured.
2303 mMinExpectedDuration = 0;
2304
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002305 // In case called from configureStreams, abort queued input buffers not belonging to
2306 // any pending requests.
2307 if (mInputStream != NULL && notifyRequestThread) {
2308 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002309 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002310 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002311 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002312 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002313 if (res != OK) {
2314 // Exhausted acquiring all input buffers.
2315 break;
2316 }
2317
Emilian Peevf4816702020-04-03 15:44:51 -07002318 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002319 res = mInputStream->returnInputBuffer(inputBuffer);
2320 if (res != OK) {
2321 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2322 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2323 }
2324 }
2325 }
2326
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002327 if (!mNeedConfig) {
2328 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2329 return OK;
2330 }
2331
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002332 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002333 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002334 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2335 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002336 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002337 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002338 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002339 }
2340
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08002341 // Override stream use case based on "adb shell command"
2342 overrideStreamUseCaseLocked();
2343
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002344 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002345 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002346
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002347 mPreparerThread->pause();
2348
Emilian Peevf4816702020-04-03 15:44:51 -07002349 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002350 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002352 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002353
Emilian Peevf4816702020-04-03 15:44:51 -07002354 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002355 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002356 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002358
2359 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002360 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 inputStream = mInputStream->startConfiguration();
2362 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002363 CLOGE("Can't start input stream configuration");
2364 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365 return INVALID_OPERATION;
2366 }
2367 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002368
2369 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002370 }
2371
Shuzhen Wang99080502021-03-07 21:08:20 -08002372 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002373 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002375
2376 // Don't configure bidi streams twice, nor add them twice to the list
2377 if (mOutputStreams[i].get() ==
2378 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2379
2380 config.num_streams--;
2381 continue;
2382 }
2383
Emilian Peevf4816702020-04-03 15:44:51 -07002384 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002385 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002387 CLOGE("Can't start output stream configuration");
2388 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002389 return INVALID_OPERATION;
2390 }
2391 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002392
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002393 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002394 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2395 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002396 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2397 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002398 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2399 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002400 } else if (outputStream->data_space ==
2401 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2402 bufferSizes[k] = outputStream->width * outputStream->height;
2403 } else {
2404 ALOGW("%s: Blob dataSpace %d not supported",
2405 __FUNCTION__, outputStream->data_space);
2406 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002407 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002408
2409 if (mOutputStreams[i]->isMultiResolution()) {
2410 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2411 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2412 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2413 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002414
2415 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2416 composerSurfacePresent = true;
2417 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002418 }
2419
2420 config.streams = streams.editArray();
2421
2422 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002423 // max_buffers, usage, and priv fields, as well as data_space and format
2424 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002425
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002426 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002427 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002428 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002429
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002430 if (res == BAD_VALUE) {
2431 // HAL rejected this set of streams as unsupported, clean up config
2432 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002433 CLOGE("Set of requested inputs/outputs not supported by HAL");
2434 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002435 return BAD_VALUE;
2436 } else if (res != OK) {
2437 // Some other kind of error from configure_streams - this is not
2438 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002439 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2440 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441 return res;
2442 }
2443
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002444 // Finish all stream configuration immediately.
2445 // TODO: Try to relax this later back to lazy completion, which should be
2446 // faster
2447
Igor Murashkin073f8572013-05-02 14:59:28 -07002448 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002449 bool streamReConfigured = false;
2450 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002451 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002452 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002453 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002454 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002455 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2456 return DEAD_OBJECT;
2457 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002458 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002459 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002460 if (streamReConfigured) {
2461 mInterface->onStreamReConfigured(mInputStream->getId());
2462 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002463 }
2464
2465 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002466 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002467 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002468 bool streamReConfigured = false;
2469 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002470 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002471 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002472 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002473 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002474 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2475 return DEAD_OBJECT;
2476 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002477 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002478 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002479 if (streamReConfigured) {
2480 mInterface->onStreamReConfigured(outputStream->getId());
2481 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002482 }
2483 }
2484
Emilian Peeve23f1d92021-09-20 14:56:01 -07002485 mRequestThread->setComposerSurface(composerSurfacePresent);
2486
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002487 // Request thread needs to know to avoid using repeat-last-settings protocol
2488 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002489 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002490 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2491 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002492 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002493
Zhijun He90f7c372016-08-16 16:19:43 -07002494 char value[PROPERTY_VALUE_MAX];
2495 property_get("camera.fifo.disable", value, "0");
2496 int32_t disableFifo = atoi(value);
2497 if (disableFifo != 1) {
2498 // Boost priority of request thread to SCHED_FIFO.
2499 pid_t requestThreadTid = mRequestThread->getTid();
2500 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002501 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002502 if (res != OK) {
2503 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2504 strerror(-res), res);
2505 } else {
2506 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2507 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002508 }
2509
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002510 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002511 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2512 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2513 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2514 sessionParams.unlock(newSessionParams);
2515 mSessionParams.unlock(currentSessionParams);
2516 if (updateSessionParams) {
2517 mSessionParams = sessionParams;
2518 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002519
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002520 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002521
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002522 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002523 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002524
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002525 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002526
Zhijun He0a210512014-07-24 13:45:15 -07002527 // tear down the deleted streams after configure streams.
2528 mDeletedStreams.clear();
2529
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002530 auto rc = mPreparerThread->resume();
2531 if (rc != OK) {
2532 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2533 return rc;
2534 }
2535
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002536 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002537 mRequestBufferSM.onStreamsConfigured();
2538 }
2539
Cliff Wu3b268182021-07-06 15:44:43 +08002540 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002541 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002542 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002543 // configure the injection streams.
2544 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002545 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002546 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2547 res = mInjectionMethods->injectCamera(config, bufferSizes);
2548 if (res != OK) {
2549 ALOGE("Can't finish inject camera process!");
2550 return res;
2551 }
Cliff Wu3b268182021-07-06 15:44:43 +08002552 } else {
2553 // First run configureStreamsLocked() and then call injectCamera() case:
2554 // If the stream configuration has been completed and camera deive is active, but the
2555 // injection camera has not been injected yet, we need to store the stream configuration of
2556 // the internal camera (because the stream configuration of the injection camera is based
2557 // on the internal camera). When injecting occurs later, this configuration can be used by
2558 // the injection camera.
2559 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2560 " injection camera has not been injected yet.", __FUNCTION__);
2561 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002562 }
2563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002565}
2566
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002567status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002568 ATRACE_CALL();
2569 status_t res;
2570
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002571 if (mFakeStreamId != NO_STREAM) {
2572 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002573 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002574 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002575 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002576 return INVALID_OPERATION;
2577 }
2578
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002579 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002580
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002581 sp<Camera3OutputStreamInterface> fakeStream =
2582 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002583
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002584 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002585 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002586 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002587 return res;
2588 }
2589
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002590 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002591 mNextStreamId++;
2592
2593 return OK;
2594}
2595
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002596status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002597 ATRACE_CALL();
2598 status_t res;
2599
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002600 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002601 if (mOutputStreams.size() == 1) return OK;
2602
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002603 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002604
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002605 // Ok, have a fake stream and there's at least one other output stream,
2606 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002607
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002608 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002609 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002610 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002611 return INVALID_OPERATION;
2612 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002613 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002614
2615 // Free up the stream endpoint so that it can be used by some other stream
2616 res = deletedStream->disconnect();
2617 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002618 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619 // fall through since we want to still list the stream as deleted.
2620 }
2621 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002622 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002623
2624 return res;
2625}
2626
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002627void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002628 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002629 Mutex::Autolock l(mLock);
2630 va_list args;
2631 va_start(args, fmt);
2632
2633 setErrorStateLockedV(fmt, args);
2634
2635 va_end(args);
2636}
2637
2638void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002639 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002640 Mutex::Autolock l(mLock);
2641 setErrorStateLockedV(fmt, args);
2642}
2643
2644void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2645 va_list args;
2646 va_start(args, fmt);
2647
2648 setErrorStateLockedV(fmt, args);
2649
2650 va_end(args);
2651}
2652
2653void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002654 // Print out all error messages to log
2655 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002656 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002657
2658 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002659 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002660
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002661 mErrorCause = errorCause;
2662
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002663 if (mRequestThread != nullptr) {
2664 mRequestThread->setPaused(true);
2665 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002666 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002667
2668 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002669 sp<NotificationListener> listener = mListener.promote();
2670 if (listener != NULL) {
2671 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002672 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002673 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002674 }
2675
2676 // Save stack trace. View by dumping it later.
2677 CameraTraces::saveTrace();
2678 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002679}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680
2681/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002682 * In-flight request management
2683 */
2684
Jianing Weicb0652e2014-03-12 18:29:36 -07002685status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002686 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002687 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002688 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002689 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2690 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002691 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002692 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002693 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002694
2695 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002696 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002697 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002698 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2699 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002700 if (res < 0) return res;
2701
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002702 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002703 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2704 // avoid a deadlock during reprocess requests.
2705 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002706 if (mStatusTracker != nullptr) {
2707 mStatusTracker->markComponentActive(mInFlightStatusId);
2708 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002709 }
2710
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002711 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002712 return OK;
2713}
2714
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002715void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002716 // Indicate idle inFlightMap to the status tracker
2717 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002718 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002719 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2720 // avoid a deadlock during reprocess requests.
2721 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002722 if (mStatusTracker != nullptr) {
2723 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2724 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002725 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002726 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002727}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002728
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002729void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002730 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002731 // something has likely gone wrong. This might still be legit only if application send in
2732 // a long burst of long exposure requests.
2733 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2734 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2735 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2736 mInFlightMap.size(), mExpectedInflightDuration);
2737 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2738 kInFlightWarnLimitHighSpeed) {
2739 CLOGW("In-flight list too large for high speed configuration: %zu,"
2740 "total inflight duration %" PRIu64,
2741 mInFlightMap.size(), mExpectedInflightDuration);
2742 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002743 }
2744}
2745
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002746void Camera3Device::onInflightMapFlushedLocked() {
2747 mExpectedInflightDuration = 0;
2748}
2749
2750void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002751 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002752 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2753 mInFlightMap.removeItemsAt(idx, 1);
2754
2755 onInflightEntryRemovedLocked(duration);
2756}
2757
2758
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002759void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002760 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002761 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002762 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002763 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002764 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002765 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002766
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002767 FlushInflightReqStates states {
2768 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002769 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002770
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002771 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002772}
2773
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002774CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002775 ALOGV("%s", __FUNCTION__);
2776
Igor Murashkin1e479c02013-09-06 16:55:14 -07002777 CameraMetadata retVal;
2778
2779 if (mRequestThread != NULL) {
2780 retVal = mRequestThread->getLatestRequest();
2781 }
2782
Igor Murashkin1e479c02013-09-06 16:55:14 -07002783 return retVal;
2784}
2785
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002786void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002787 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002788 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002789 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2790 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002791
2792 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002793 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002794}
2795
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002796void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002797 std::vector<native_handle_t*> *handles, bool closeFd) {
2798 if (handles == nullptr) {
2799 return;
2800 }
2801 if (closeFd) {
2802 for (auto& handle : *handles) {
2803 native_handle_close(handle);
2804 }
2805 }
2806 for (auto& handle : *handles) {
2807 native_handle_delete(handle);
2808 }
2809 handles->clear();
2810 return;
2811}
2812
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002813/**
2814 * HalInterface inner class methods
2815 */
2816
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002817void Camera3Device::HalInterface::getInflightBufferKeys(
2818 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002819 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002820 return;
2821}
2822
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002823void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2824 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002825 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002826 return;
2827}
2828
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002829bool Camera3Device::HalInterface::verifyBufferIds(
2830 int32_t streamId, std::vector<uint64_t>& bufIds) {
2831 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002832}
2833
2834status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002835 int32_t frameNumber, int32_t streamId,
2836 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002837 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002838}
2839
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002840status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002841 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002842 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002843}
2844
2845// Find and pop a buffer_handle_t based on bufferId
2846status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002847 uint64_t bufferId,
2848 /*out*/ buffer_handle_t** buffer,
2849 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002850 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002851}
2852
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002853std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2854 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002855 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002856}
2857
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002858uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2859 const native_handle_t* handle) {
2860 return mBufferRecords.removeOneBufferCache(streamId, handle);
2861}
2862
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002863void Camera3Device::HalInterface::onBufferFreed(
2864 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002865 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2866 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2867 if (bufferId != BUFFER_ID_NO_BUFFER) {
2868 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002869 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002870}
2871
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002872void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002873 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2874 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2875 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002876 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2877 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002878}
2879
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002880/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002881 * RequestThread inner class methods
2882 */
2883
2884Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002885 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002886 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002887 bool useHalBufManager,
Austin Borger3560b7e2022-10-27 12:20:29 -07002888 bool supportCameraMute,
2889 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002890 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002891 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002892 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002893 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002894 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002895 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002896 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002897 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002898 mReconfigured(false),
2899 mDoPause(false),
2900 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002901 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002902 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002903 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002904 mCurrentAfTriggerId(0),
2905 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002906 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002907 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002908 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002909 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910 mRepeatingLastFrameNumber(
2911 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002912 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002913 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002914 mRequestLatency(kRequestLatencyBinSize),
2915 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002916 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002917 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002918 mSupportCameraMute(supportCameraMute),
2919 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002920 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002921}
2922
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002923Camera3Device::RequestThread::~RequestThread() {}
2924
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002925void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002926 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002927 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002928 Mutex::Autolock l(mRequestLock);
2929 mListener = listener;
2930}
2931
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002932void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002933 const CameraMetadata& sessionParams,
2934 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002935 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002936 Mutex::Autolock l(mRequestLock);
2937 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002938 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002939 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002940 // Prepare video stream for high speed recording.
2941 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002942 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002943}
2944
Jianing Wei90e59c92014-03-12 18:29:36 -07002945status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002946 List<sp<CaptureRequest> > &requests,
2947 /*out*/
2948 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002949 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002950 Mutex::Autolock l(mRequestLock);
2951 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2952 ++it) {
2953 mRequestQueue.push_back(*it);
2954 }
2955
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002956 if (lastFrameNumber != NULL) {
2957 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2958 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2959 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2960 *lastFrameNumber);
2961 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002962
Jianing Wei90e59c92014-03-12 18:29:36 -07002963 unpauseForNewRequests();
2964
2965 return OK;
2966}
2967
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002968
2969status_t Camera3Device::RequestThread::queueTrigger(
2970 RequestTrigger trigger[],
2971 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002972 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002973 Mutex::Autolock l(mTriggerMutex);
2974 status_t ret;
2975
2976 for (size_t i = 0; i < count; ++i) {
2977 ret = queueTriggerLocked(trigger[i]);
2978
2979 if (ret != OK) {
2980 return ret;
2981 }
2982 }
2983
2984 return OK;
2985}
2986
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002987const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2988 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 if (d != nullptr) return d->mId;
2991 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002992}
2993
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002994status_t Camera3Device::RequestThread::queueTriggerLocked(
2995 RequestTrigger trigger) {
2996
2997 uint32_t tag = trigger.metadataTag;
2998 ssize_t index = mTriggerMap.indexOfKey(tag);
2999
3000 switch (trigger.getTagType()) {
3001 case TYPE_BYTE:
3002 // fall-through
3003 case TYPE_INT32:
3004 break;
3005 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003006 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3007 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003008 return INVALID_OPERATION;
3009 }
3010
3011 /**
3012 * Collect only the latest trigger, since we only have 1 field
3013 * in the request settings per trigger tag, and can't send more than 1
3014 * trigger per request.
3015 */
3016 if (index != NAME_NOT_FOUND) {
3017 mTriggerMap.editValueAt(index) = trigger;
3018 } else {
3019 mTriggerMap.add(tag, trigger);
3020 }
3021
3022 return OK;
3023}
3024
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003025status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003026 const RequestList &requests,
3027 /*out*/
3028 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003029 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003030 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003031 if (lastFrameNumber != NULL) {
3032 *lastFrameNumber = mRepeatingLastFrameNumber;
3033 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003034 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003035 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003036 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3037 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003038
3039 unpauseForNewRequests();
3040
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003042 return OK;
3043}
3044
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003045bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003046 if (mRepeatingRequests.empty()) {
3047 return false;
3048 }
3049 int32_t requestId = requestIn->mResultExtras.requestId;
3050 const RequestList &repeatRequests = mRepeatingRequests;
3051 // All repeating requests are guaranteed to have same id so only check first quest
3052 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3053 return (firstRequest->mResultExtras.requestId == requestId);
3054}
3055
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003056status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003057 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003058 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003059 return clearRepeatingRequestsLocked(lastFrameNumber);
3060
3061}
3062
3063status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003064 std::vector<int32_t> streamIds;
3065 for (const auto& request : mRepeatingRequests) {
3066 for (const auto& stream : request->mOutputStreams) {
3067 streamIds.push_back(stream->getId());
3068 }
3069 }
3070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003071 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003072 if (lastFrameNumber != NULL) {
3073 *lastFrameNumber = mRepeatingLastFrameNumber;
3074 }
Emilian Peev2295df72021-11-12 18:14:10 -08003075
3076 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3077
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003078 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003079 return OK;
3080}
3081
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003082status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003083 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003084 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003085 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003086 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003087
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003088 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003089
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003090 // Send errors for all requests pending in the request queue, including
3091 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003092 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003093 if (listener != NULL) {
3094 for (RequestList::iterator it = mRequestQueue.begin();
3095 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003096 // Abort the input buffers for reprocess requests.
3097 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003098 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003099 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003100 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003101 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003102 if (res != OK) {
3103 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3104 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3105 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003106 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003107 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3108 if (res != OK) {
3109 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3110 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3111 }
3112 }
3113 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003114 // Set the frame number this request would have had, if it
3115 // had been submitted; this frame number will not be reused.
3116 // The requestId and burstId fields were set when the request was
3117 // submitted originally (in convertMetadataListToRequestListLocked)
3118 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003119 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003120 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003121 }
3122 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003123 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003124
3125 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003126 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003127 if (lastFrameNumber != NULL) {
3128 *lastFrameNumber = mRepeatingLastFrameNumber;
3129 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003130 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003131 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003132 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003133 return OK;
3134}
3135
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003136status_t Camera3Device::RequestThread::flush() {
3137 ATRACE_CALL();
3138 Mutex::Autolock l(mFlushLock);
3139
Emilian Peev08dd2452017-04-06 16:55:14 +01003140 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003141}
3142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003143void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003144 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003145 Mutex::Autolock l(mPauseLock);
3146 mDoPause = paused;
3147 mDoPauseSignal.signal();
3148}
3149
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003150status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3151 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003152 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003153 Mutex::Autolock l(mLatestRequestMutex);
3154 status_t res;
3155 while (mLatestRequestId != requestId) {
3156 nsecs_t startTime = systemTime();
3157
3158 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3159 if (res != OK) return res;
3160
3161 timeout -= (systemTime() - startTime);
3162 }
3163
3164 return OK;
3165}
3166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003167void Camera3Device::RequestThread::requestExit() {
3168 // Call parent to set up shutdown
3169 Thread::requestExit();
3170 // The exit from any possible waits
3171 mDoPauseSignal.signal();
3172 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003173
3174 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3175 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003176}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003177
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003178void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003179 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003180 bool surfaceAbandoned = false;
3181 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003182 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003183 {
3184 Mutex::Autolock l(mRequestLock);
3185 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3186 // repeating requests.
3187 for (const auto& request : mRepeatingRequests) {
3188 for (const auto& s : request->mOutputStreams) {
3189 if (s->isAbandoned()) {
3190 surfaceAbandoned = true;
3191 clearRepeatingRequestsLocked(&lastFrameNumber);
3192 break;
3193 }
3194 }
3195 if (surfaceAbandoned) {
3196 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003197 }
3198 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003199 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003200 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003201
3202 if (listener != NULL && surfaceAbandoned) {
3203 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003204 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003205}
3206
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003207bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003208 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003209 status_t res;
3210 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003211 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003212 uint32_t numRequestProcessed = 0;
3213 for (size_t i = 0; i < batchSize; i++) {
3214 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003215 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003216 }
3217
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003218 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3219
3220 bool triggerRemoveFailed = false;
3221 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3222 for (size_t i = 0; i < numRequestProcessed; i++) {
3223 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3224 nextRequest.submitted = true;
3225
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003226 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003227
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003228 if (!triggerRemoveFailed) {
3229 // Remove any previously queued triggers (after unlock)
3230 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3231 if (removeTriggerRes != OK) {
3232 triggerRemoveFailed = true;
3233 triggerFailedRequest = nextRequest;
3234 }
3235 }
3236 }
3237
3238 if (triggerRemoveFailed) {
3239 SET_ERR("RequestThread: Unable to remove triggers "
3240 "(capture request %d, HAL device: %s (%d)",
3241 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3242 cleanUpFailedRequests(/*sendRequestError*/ false);
3243 return false;
3244 }
3245
3246 if (res != OK) {
3247 // Should only get a failure here for malformed requests or device-level
3248 // errors, so consider all errors fatal. Bad metadata failures should
3249 // come through notify.
3250 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3251 mNextRequests[numRequestProcessed].halRequest.frame_number,
3252 strerror(-res), res);
3253 cleanUpFailedRequests(/*sendRequestError*/ false);
3254 return false;
3255 }
3256 return true;
3257}
3258
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003259Camera3Device::RequestThread::ExpectedDurationInfo
3260 Camera3Device::RequestThread::calculateExpectedDurationRange(
3261 const camera_metadata_t *request) {
3262 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003263 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003264 InFlightRequest::kDefaultMaxExpectedDuration,
3265 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003266 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3267 find_camera_metadata_ro_entry(request,
3268 ANDROID_CONTROL_AE_MODE,
3269 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003270 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003271
3272 switch (e.data.u8[0]) {
3273 case ANDROID_CONTROL_AE_MODE_OFF:
3274 find_camera_metadata_ro_entry(request,
3275 ANDROID_SENSOR_EXPOSURE_TIME,
3276 &e);
3277 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003278 expectedDurationInfo.minDuration = e.data.i64[0];
3279 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003280 }
3281 find_camera_metadata_ro_entry(request,
3282 ANDROID_SENSOR_FRAME_DURATION,
3283 &e);
3284 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003285 expectedDurationInfo.minDuration =
3286 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3287 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003288 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003289 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003290 break;
3291 default:
3292 find_camera_metadata_ro_entry(request,
3293 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3294 &e);
3295 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003296 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3297 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003298 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003299 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003300 break;
3301 }
3302
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003303 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003304}
3305
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003306bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3307 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3308 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3309 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3310 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3311 return true;
3312 }
3313
3314 return false;
3315}
3316
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003317void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3318 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003319 camera_capture_request_t& halRequest = nextRequest.halRequest;
3320 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003321 Mutex::Autolock al(mLatestRequestMutex);
3322
Shuzhen Wang83bff122020-11-20 15:51:39 -08003323 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003324 mLatestRequest.acquire(cloned);
3325
3326 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003327 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3328 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3329 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003330 CameraMetadata(cloned));
3331 }
3332
3333 sp<Camera3Device> parent = mParent.promote();
3334 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003335 int32_t inputStreamId = -1;
3336 if (halRequest.input_buffer != nullptr) {
3337 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3338 }
3339
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003340 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003341 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003342 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3343 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003344 }
3345 }
3346
Shuzhen Wang83bff122020-11-20 15:51:39 -08003347 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003348 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003349 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003350 }
3351
Shuzhen Wang83bff122020-11-20 15:51:39 -08003352 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003353}
3354
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003355bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3356 ATRACE_CALL();
3357 bool updatesDetected = false;
3358
Emilian Peev4ec17882019-01-24 17:16:58 -08003359 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003360 for (auto tag : mSessionParamKeys) {
3361 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003362 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003363
3364 if (entry.count > 0) {
3365 bool isDifferent = false;
3366 if (lastEntry.count > 0) {
3367 // Have a last value, compare to see if changed
3368 if (lastEntry.type == entry.type &&
3369 lastEntry.count == entry.count) {
3370 // Same type and count, compare values
3371 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3372 size_t entryBytes = bytesPerValue * lastEntry.count;
3373 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3374 if (cmp != 0) {
3375 isDifferent = true;
3376 }
3377 } else {
3378 // Count or type has changed
3379 isDifferent = true;
3380 }
3381 } else {
3382 // No last entry, so always consider to be different
3383 isDifferent = true;
3384 }
3385
3386 if (isDifferent) {
3387 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003388 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3389 updatesDetected = true;
3390 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003391 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003392 }
3393 } else if (lastEntry.count > 0) {
3394 // Value has been removed
3395 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003396 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003397 updatesDetected = true;
3398 }
3399 }
3400
Emilian Peev4ec17882019-01-24 17:16:58 -08003401 bool reconfigureRequired;
3402 if (updatesDetected) {
3403 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3404 updatedParams);
3405 mLatestSessionParams = updatedParams;
3406 } else {
3407 reconfigureRequired = false;
3408 }
3409
3410 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003411}
3412
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003413bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003414 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003415 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003416 // Any function called from threadLoop() must not hold mInterfaceLock since
3417 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3418 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003419
3420 // Handle paused state.
3421 if (waitIfPaused()) {
3422 return true;
3423 }
3424
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003425 // Wait for the next batch of requests.
3426 waitForNextRequestBatch();
3427 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003428 return true;
3429 }
3430
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003431 // Get the latest request ID, if any
3432 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003433 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003434 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003435 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003436 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003437 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003438 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3439 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003440 }
3441
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003442 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3443 // or a single request from streaming or burst. In either case the first element
3444 // should contain the latest camera settings that we need to check for any session
3445 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003446 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003447 res = OK;
3448
3449 //Input stream buffers are already acquired at this point so an input stream
3450 //will not be able to move to idle state unless we force it.
3451 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3452 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3453 if (res != OK) {
3454 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3455 cleanUpFailedRequests(/*sendRequestError*/ false);
3456 return false;
3457 }
3458 }
3459
3460 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003461 sp<Camera3Device> parent = mParent.promote();
3462 if (parent != nullptr) {
3463 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003464 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003465 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003466
3467 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3468 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3469 if (res != OK) {
3470 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3471 cleanUpFailedRequests(/*sendRequestError*/ false);
3472 return false;
3473 }
3474 }
3475 }
3476 }
3477
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003478 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003479 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003480 if (res == TIMED_OUT) {
3481 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003482 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003483 // Check if any stream is abandoned.
3484 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003485 return true;
3486 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003487 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003488 return false;
3489 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003490
Zhijun Hecc27e112013-10-03 16:12:43 -07003491 // Inform waitUntilRequestProcessed thread of a new request ID
3492 {
3493 Mutex::Autolock al(mLatestRequestMutex);
3494
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003495 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003496 mLatestRequestSignal.signal();
3497 }
3498
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003499 // Submit a batch of requests to HAL.
3500 // Use flush lock only when submitting multilple requests in a batch.
3501 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3502 // which may take a long time to finish so synchronizing flush() and
3503 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3504 // For now, only synchronize for high speed recording and we should figure something out for
3505 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003506 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003507
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003508 if (useFlushLock) {
3509 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003510 }
3511
Zhijun Hef0645c12016-08-02 00:58:11 -07003512 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003513 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003514
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003515 sp<Camera3Device> parent = mParent.promote();
3516 if (parent != nullptr) {
3517 parent->mRequestBufferSM.onSubmittingRequest();
3518 }
3519
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003520 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003521 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003522 submitRequestSuccess = sendRequestsBatch();
3523
Shuzhen Wang686f6442017-06-20 16:16:04 -07003524 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3525 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003526
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003527 if (useFlushLock) {
3528 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003529 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003530
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003531 // Unset as current request
3532 {
3533 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003534 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003535 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003536 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003537
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003538 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003539}
3540
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003541status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3542 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3543 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3544 ANDROID_SCALER_CROP_REGION_SET};
3545 if (request == nullptr) {
3546 ALOGE("%s request metadata nullptr", __FUNCTION__);
3547 return BAD_VALUE;
3548 }
3549 status_t res = OK;
3550 for (const auto &key : kFwkOnlyRegionKeys) {
3551 if (request->exists(key)) {
3552 res = request->erase(key);
3553 if (res != OK) {
3554 return res;
3555 }
3556 }
3557 }
3558 return OK;
3559}
3560
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003561status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003562 ATRACE_CALL();
3563
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003564 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003565 for (size_t i = 0; i < mNextRequests.size(); i++) {
3566 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003567 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003568 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3569 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003570
3571 // Prepare a request to HAL
3572 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3573
3574 // Insert any queued triggers (before metadata is locked)
3575 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003576 if (res < 0) {
3577 SET_ERR("RequestThread: Unable to insert triggers "
3578 "(capture request %d, HAL device: %s (%d)",
3579 halRequest->frame_number, strerror(-res), res);
3580 return INVALID_OPERATION;
3581 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003582
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003583 int triggerCount = res;
3584 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3585 mPrevTriggers = triggerCount;
3586
Emilian Peeve23f1d92021-09-20 14:56:01 -07003587 // Do not override rotate&crop for stream configurations that include
Austin Borger3560b7e2022-10-27 12:20:29 -07003588 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3589 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3590 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003591 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003592 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003593
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003594 // If the request is the same as last, or we had triggers now or last time or
3595 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003596 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003597 (mPrevRequest != captureRequest || triggersMixedIn ||
3598 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003599 // Request settings are all the same within one batch, so only treat the first
3600 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003601 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003602 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003603 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003604 /**
3605 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003606 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003607 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003608 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003609 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003610 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003611 "(capture request %d, HAL device: %s (%d)",
3612 halRequest->frame_number, strerror(-res), res);
3613 return INVALID_OPERATION;
3614 }
3615
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003616 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003617 sp<Camera3Device> parent = mParent.promote();
3618 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003619 List<PhysicalCameraSettings>::iterator it;
3620 for (it = captureRequest->mSettingsList.begin();
3621 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003622 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3623 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003624 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3625 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3626 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3627 res);
3628 return INVALID_OPERATION;
3629 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003630 continue;
3631 }
3632
3633 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3634 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3635 updateCaptureRequest(&(it->metadata));
3636 if (res != OK) {
3637 SET_ERR("RequestThread: Unable to correct capture requests "
3638 "for scaler crop region and metering regions for request "
3639 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3640 res);
3641 return INVALID_OPERATION;
3642 }
3643 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003644 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3645 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3646 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3647 res);
3648 return INVALID_OPERATION;
3649 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003650 }
3651 }
3652
3653 // Correct metadata regions for distortion correction if enabled
3654 for (it = captureRequest->mSettingsList.begin();
3655 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003656 if (parent->mDistortionMappers.find(it->cameraId) ==
3657 parent->mDistortionMappers.end()) {
3658 continue;
3659 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003660
3661 if (!captureRequest->mDistortionCorrectionUpdated) {
3662 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3663 &(it->metadata));
3664 if (res != OK) {
3665 SET_ERR("RequestThread: Unable to correct capture requests "
3666 "for lens distortion for request %d: %s (%d)",
3667 halRequest->frame_number, strerror(-res), res);
3668 return INVALID_OPERATION;
3669 }
3670 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003671 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003672 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003673
3674 for (it = captureRequest->mSettingsList.begin();
3675 it != captureRequest->mSettingsList.end(); it++) {
3676 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3677 parent->mZoomRatioMappers.end()) {
3678 continue;
3679 }
3680
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003681 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003682 cameraIdsWithZoom.insert(it->cameraId);
3683 }
3684
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003685 if (!captureRequest->mZoomRatioUpdated) {
3686 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3687 &(it->metadata));
3688 if (res != OK) {
3689 SET_ERR("RequestThread: Unable to correct capture requests "
3690 "for zoom ratio for request %d: %s (%d)",
3691 halRequest->frame_number, strerror(-res), res);
3692 return INVALID_OPERATION;
3693 }
3694 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003695 }
3696 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003697 if (captureRequest->mRotateAndCropAuto &&
3698 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003699 for (it = captureRequest->mSettingsList.begin();
3700 it != captureRequest->mSettingsList.end(); it++) {
3701 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3702 if (mapper != parent->mRotateAndCropMappers.end()) {
3703 res = mapper->second.updateCaptureRequest(&(it->metadata));
3704 if (res != OK) {
3705 SET_ERR("RequestThread: Unable to correct capture requests "
3706 "for rotate-and-crop for request %d: %s (%d)",
3707 halRequest->frame_number, strerror(-res), res);
3708 return INVALID_OPERATION;
3709 }
3710 }
3711 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003712 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003713 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003714 }
3715 }
3716
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003717 /**
3718 * The request should be presorted so accesses in HAL
3719 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3720 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003721 captureRequest->mSettingsList.begin()->metadata.sort();
3722 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003723 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003724 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003725 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3726
3727 IF_ALOGV() {
3728 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3729 find_camera_metadata_ro_entry(
3730 halRequest->settings,
3731 ANDROID_CONTROL_AF_TRIGGER,
3732 &e
3733 );
3734 if (e.count > 0) {
3735 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3736 __FUNCTION__,
3737 halRequest->frame_number,
3738 e.data.u8[0]);
3739 }
3740 }
3741 } else {
3742 // leave request.settings NULL to indicate 'reuse latest given'
3743 ALOGVV("%s: Request settings are REUSED",
3744 __FUNCTION__);
3745 }
3746
Emilian Peevaebbe412018-01-15 13:53:24 +00003747 if (captureRequest->mSettingsList.size() > 1) {
3748 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3749 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003750 if (newRequest) {
3751 halRequest->physcam_settings =
3752 new const camera_metadata* [halRequest->num_physcam_settings];
3753 } else {
3754 halRequest->physcam_settings = nullptr;
3755 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003756 auto it = ++captureRequest->mSettingsList.begin();
3757 size_t i = 0;
3758 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3759 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003760 if (newRequest) {
3761 it->metadata.sort();
3762 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3763 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003764 }
3765 }
3766
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003767 uint32_t totalNumBuffers = 0;
3768
3769 // Fill in buffers
3770 if (captureRequest->mInputStream != NULL) {
3771 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003772
3773 halRequest->input_width = captureRequest->mInputBufferSize.width;
3774 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003775 totalNumBuffers += 1;
3776 } else {
3777 halRequest->input_buffer = NULL;
3778 }
3779
Emilian Peevf4816702020-04-03 15:44:51 -07003780 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003781 captureRequest->mOutputStreams.size());
3782 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003783 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003784
3785 sp<Camera3Device> parent = mParent.promote();
3786 if (parent == NULL) {
3787 // Should not happen, and nowhere to send errors to, so just log it
3788 CLOGE("RequestThread: Parent is gone");
3789 return INVALID_OPERATION;
3790 }
3791 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3792
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003793 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003794 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003795 sp<Camera3OutputStreamInterface> outputStream =
3796 captureRequest->mOutputStreams.editItemAt(j);
3797 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003798
3799 // Prepare video buffers for high speed recording on the first video request.
3800 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3801 // Only try to prepare video stream on the first video request.
3802 mPrepareVideoStream = false;
3803
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003804 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3805 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003806 while (res == NOT_ENOUGH_DATA) {
3807 res = outputStream->prepareNextBuffer();
3808 }
3809 if (res != OK) {
3810 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3811 __FUNCTION__, strerror(-res), res);
3812 outputStream->cancelPrepare();
3813 }
3814 }
3815
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003816 std::vector<size_t> uniqueSurfaceIds;
3817 res = outputStream->getUniqueSurfaceIds(
3818 captureRequest->mOutputSurfaces[streamId],
3819 &uniqueSurfaceIds);
3820 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3821 if (res != OK && res != INVALID_OPERATION) {
3822 ALOGE("%s: failed to query stream %d unique surface IDs",
3823 __FUNCTION__, streamId);
3824 return res;
3825 }
3826 if (res == OK) {
3827 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3828 }
3829
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003830 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003831 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003832 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003833 return TIMED_OUT;
3834 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003835 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003836 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003837 buffer.stream = outputStream->asHalStream();
3838 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003839 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003840 buffer.acquire_fence = -1;
3841 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003842 // Mark the output stream as unpreparable to block clients from calling
3843 // 'prepare' after this request reaches CameraHal and before the respective
3844 // buffers are requested.
3845 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003846 } else {
3847 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3848 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003849 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003850 if (res != OK) {
3851 // Can't get output buffer from gralloc queue - this could be due to
3852 // abandoned queue or other consumer misbehavior, so not a fatal
3853 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003854 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003855 " %s (%d)", strerror(-res), res);
3856
3857 return TIMED_OUT;
3858 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003859 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003860
3861 {
3862 sp<Camera3Device> parent = mParent.promote();
3863 if (parent != nullptr) {
3864 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3865 for (const auto& settings : captureRequest->mSettingsList) {
3866 if ((streamCameraId.isEmpty() &&
3867 parent->getId() == settings.cameraId.c_str()) ||
3868 streamCameraId == settings.cameraId.c_str()) {
3869 outputStream->fireBufferRequestForFrameNumber(
3870 captureRequest->mResultExtras.frameNumber,
3871 settings.metadata);
3872 }
3873 }
3874 }
3875 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003876
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003877 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003878 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3879 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3880 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3881 } else if (!physicalCameraId.isEmpty()) {
3882 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003883 }
3884 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003885 }
3886 totalNumBuffers += halRequest->num_output_buffers;
3887
3888 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003889 // If this request list is for constrained high speed recording (not
3890 // preview), and the current request is not the last one in the batch,
3891 // do not send callback to the app.
3892 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003893 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003894 hasCallback = false;
3895 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003896 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003897 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003898 const camera_metadata_t* settings = halRequest->settings;
3899 bool shouldUnlockSettings = false;
3900 if (settings == nullptr) {
3901 shouldUnlockSettings = true;
3902 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3903 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003904 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3905 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003906 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003907 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3908 isStillCapture = true;
3909 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3910 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003911
Emilian Peevaf8416e2021-02-04 17:52:43 -08003912 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003913 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003914 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3915 isZslCapture = true;
3916 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003917 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003918 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003919 res = parent->registerInFlight(halRequest->frame_number,
3920 totalNumBuffers, captureRequest->mResultExtras,
3921 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003922 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003923 expectedDurationInfo.minDuration,
3924 expectedDurationInfo.maxDuration,
3925 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003926 requestedPhysicalCameras, isStillCapture, isZslCapture,
3927 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003928 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003929 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003930 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3931 ", burstId = %" PRId32 ".",
3932 __FUNCTION__,
3933 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3934 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003935
3936 if (shouldUnlockSettings) {
3937 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3938 }
3939
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003940 if (res != OK) {
3941 SET_ERR("RequestThread: Unable to register new in-flight request:"
3942 " %s (%d)", strerror(-res), res);
3943 return INVALID_OPERATION;
3944 }
3945 }
3946
3947 return OK;
3948}
3949
Igor Murashkin1e479c02013-09-06 16:55:14 -07003950CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003951 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003952 Mutex::Autolock al(mLatestRequestMutex);
3953
3954 ALOGV("RequestThread::%s", __FUNCTION__);
3955
3956 return mLatestRequest;
3957}
3958
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003959bool Camera3Device::RequestThread::isStreamPending(
3960 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003961 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003962 Mutex::Autolock l(mRequestLock);
3963
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003964 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003965 if (!nextRequest.submitted) {
3966 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3967 if (stream == s) return true;
3968 }
3969 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003970 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003971 }
3972
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003973 for (const auto& request : mRequestQueue) {
3974 for (const auto& s : request->mOutputStreams) {
3975 if (stream == s) return true;
3976 }
3977 if (stream == request->mInputStream) return true;
3978 }
3979
3980 for (const auto& request : mRepeatingRequests) {
3981 for (const auto& s : request->mOutputStreams) {
3982 if (stream == s) return true;
3983 }
3984 if (stream == request->mInputStream) return true;
3985 }
3986
3987 return false;
3988}
Jianing Weicb0652e2014-03-12 18:29:36 -07003989
Emilian Peev40ead602017-09-26 15:46:36 +01003990bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3991 ATRACE_CALL();
3992 Mutex::Autolock l(mRequestLock);
3993
3994 for (const auto& nextRequest : mNextRequests) {
3995 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3996 if (s.first == streamId) {
3997 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3998 if (it != s.second.end()) {
3999 return true;
4000 }
4001 }
4002 }
4003 }
4004
4005 for (const auto& request : mRequestQueue) {
4006 for (const auto& s : request->mOutputSurfaces) {
4007 if (s.first == streamId) {
4008 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4009 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004010 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004011 }
4012 }
4013 }
4014 }
4015
4016 for (const auto& request : mRepeatingRequests) {
4017 for (const auto& s : request->mOutputSurfaces) {
4018 if (s.first == streamId) {
4019 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4020 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004021 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004022 }
4023 }
4024 }
4025 }
4026
4027 return false;
4028}
4029
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004030void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4031 if (!mUseHalBufManager) {
4032 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4033 return;
4034 }
4035
4036 Mutex::Autolock pl(mPauseLock);
4037 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004038 mInterface->signalPipelineDrain(streamIds);
4039 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004040 }
4041 // If request thread is still busy, wait until paused then notify HAL
4042 mNotifyPipelineDrain = true;
4043 mStreamIdsToBeDrained = streamIds;
4044}
4045
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004046void Camera3Device::RequestThread::resetPipelineDrain() {
4047 Mutex::Autolock pl(mPauseLock);
4048 mNotifyPipelineDrain = false;
4049 mStreamIdsToBeDrained.clear();
4050}
4051
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004052void Camera3Device::RequestThread::clearPreviousRequest() {
4053 Mutex::Autolock l(mRequestLock);
4054 mPrevRequest.clear();
4055}
4056
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004057status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4058 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4059 ATRACE_CALL();
4060 Mutex::Autolock l(mTriggerMutex);
4061 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4062 return BAD_VALUE;
4063 }
4064 mRotateAndCropOverride = rotateAndCropValue;
4065 return OK;
4066}
4067
Emilian Peeve23f1d92021-09-20 14:56:01 -07004068status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4069 ATRACE_CALL();
4070 Mutex::Autolock l(mTriggerMutex);
4071 mComposerOutput = composerSurfacePresent;
4072 return OK;
4073}
4074
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004075status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004076 ATRACE_CALL();
4077 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004078 if (muteMode != mCameraMute) {
4079 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004080 mCameraMuteChanged = true;
4081 }
4082 return OK;
4083}
4084
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004085nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004086 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004087 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004088 return mExpectedInflightDuration > kMinInflightDuration ?
4089 mExpectedInflightDuration : kMinInflightDuration;
4090}
4091
Emilian Peevaebbe412018-01-15 13:53:24 +00004092void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004093 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004094 if ((request == nullptr) || (halRequest == nullptr)) {
4095 ALOGE("%s: Invalid request!", __FUNCTION__);
4096 return;
4097 }
4098
4099 if (halRequest->num_physcam_settings > 0) {
4100 if (halRequest->physcam_id != nullptr) {
4101 delete [] halRequest->physcam_id;
4102 halRequest->physcam_id = nullptr;
4103 }
4104 if (halRequest->physcam_settings != nullptr) {
4105 auto it = ++(request->mSettingsList.begin());
4106 size_t i = 0;
4107 for (; it != request->mSettingsList.end(); it++, i++) {
4108 it->metadata.unlock(halRequest->physcam_settings[i]);
4109 }
4110 delete [] halRequest->physcam_settings;
4111 halRequest->physcam_settings = nullptr;
4112 }
4113 }
4114}
4115
Ravneet74cd3732022-03-30 05:33:03 +00004116status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4117 Mutex::Autolock il(mInterfaceLock);
4118 Mutex::Autolock l(mLock);
4119
4120 if (mCameraServiceWatchdog != NULL) {
4121 mCameraServiceWatchdog->setEnabled(enabled);
4122 }
4123
4124 return OK;
4125}
4126
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004127void Camera3Device::setStreamUseCaseOverrides(
4128 const std::vector<int64_t>& useCaseOverrides) {
4129 Mutex::Autolock il(mInterfaceLock);
4130 Mutex::Autolock l(mLock);
4131 mStreamUseCaseOverrides = useCaseOverrides;
4132}
4133
4134void Camera3Device::clearStreamUseCaseOverrides() {
4135 Mutex::Autolock il(mInterfaceLock);
4136 Mutex::Autolock l(mLock);
4137 mStreamUseCaseOverrides.clear();
4138}
4139
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004140void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4141 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004142 return;
4143 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004144
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004145 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004146 // Skip the ones that have been submitted successfully.
4147 if (nextRequest.submitted) {
4148 continue;
4149 }
4150
4151 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004152 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4153 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004154
4155 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004156 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004157 }
4158
Emilian Peevaebbe412018-01-15 13:53:24 +00004159 cleanupPhysicalSettings(captureRequest, halRequest);
4160
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004161 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004162 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004163 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4164 }
4165
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004166 // No output buffer can be returned when using HAL buffer manager
4167 if (!mUseHalBufManager) {
4168 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4169 //Buffers that failed processing could still have
4170 //valid acquire fence.
4171 int acquireFence = (*outputBuffers)[i].acquire_fence;
4172 if (0 <= acquireFence) {
4173 close(acquireFence);
4174 outputBuffers->editItemAt(i).acquire_fence = -1;
4175 }
Emilian Peevf4816702020-04-03 15:44:51 -07004176 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004177 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4178 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004179 /*timestampIncreasing*/true, std::vector<size_t> (),
4180 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004181 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004182 }
4183
4184 if (sendRequestError) {
4185 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004186 sp<NotificationListener> listener = mListener.promote();
4187 if (listener != NULL) {
4188 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004189 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004190 captureRequest->mResultExtras);
4191 }
4192 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004193
4194 // Remove yet-to-be submitted inflight request from inflightMap
4195 {
4196 sp<Camera3Device> parent = mParent.promote();
4197 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004198 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004199 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4200 if (idx >= 0) {
4201 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4202 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4203 parent->removeInFlightMapEntryLocked(idx);
4204 }
4205 }
4206 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004207 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004208
4209 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004210 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004211}
4212
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004213void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004214 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004215 // Optimized a bit for the simple steady-state case (single repeating
4216 // request), to avoid putting that request in the queue temporarily.
4217 Mutex::Autolock l(mRequestLock);
4218
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004219 assert(mNextRequests.empty());
4220
4221 NextRequest nextRequest;
4222 nextRequest.captureRequest = waitForNextRequestLocked();
4223 if (nextRequest.captureRequest == nullptr) {
4224 return;
4225 }
4226
Emilian Peevf4816702020-04-03 15:44:51 -07004227 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004228 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004229 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004230
4231 // Wait for additional requests
4232 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4233
4234 for (size_t i = 1; i < batchSize; i++) {
4235 NextRequest additionalRequest;
4236 additionalRequest.captureRequest = waitForNextRequestLocked();
4237 if (additionalRequest.captureRequest == nullptr) {
4238 break;
4239 }
4240
Emilian Peevf4816702020-04-03 15:44:51 -07004241 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004242 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004243 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004244 }
4245
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004246 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004247 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004248 mNextRequests.size(), batchSize);
4249 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004250 }
4251
4252 return;
4253}
4254
4255sp<Camera3Device::CaptureRequest>
4256 Camera3Device::RequestThread::waitForNextRequestLocked() {
4257 status_t res;
4258 sp<CaptureRequest> nextRequest;
4259
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 while (mRequestQueue.empty()) {
4261 if (!mRepeatingRequests.empty()) {
4262 // Always atomically enqueue all requests in a repeating request
4263 // list. Guarantees a complete in-sequence set of captures to
4264 // application.
4265 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004266 if (mFirstRepeating) {
4267 mFirstRepeating = false;
4268 } else {
4269 for (auto& request : requests) {
4270 // For repeating requests, override timestamp request using
4271 // the time a request is inserted into the request queue,
4272 // because the original repeating request will have an old
4273 // fixed timestamp.
4274 request->mRequestTimeNs = systemTime();
4275 }
4276 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004277 RequestList::const_iterator firstRequest =
4278 requests.begin();
4279 nextRequest = *firstRequest;
4280 mRequestQueue.insert(mRequestQueue.end(),
4281 ++firstRequest,
4282 requests.end());
4283 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004284
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004285 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004286
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004287 break;
4288 }
4289
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004290 if (!mRequestClearing) {
4291 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4292 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004293
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004294 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4295 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004296 Mutex::Autolock pl(mPauseLock);
4297 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004298 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004300 if (mNotifyPipelineDrain) {
4301 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4302 mNotifyPipelineDrain = false;
4303 mStreamIdsToBeDrained.clear();
4304 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004305 // Let the tracker know
4306 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4307 if (statusTracker != 0) {
4308 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4309 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004310 sp<Camera3Device> parent = mParent.promote();
4311 if (parent != nullptr) {
4312 parent->mRequestBufferSM.onRequestThreadPaused();
4313 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004315 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004316 // Stop waiting for now and let thread management happen
4317 return NULL;
4318 }
4319 }
4320
4321 if (nextRequest == NULL) {
4322 // Don't have a repeating request already in hand, so queue
4323 // must have an entry now.
4324 RequestList::iterator firstRequest =
4325 mRequestQueue.begin();
4326 nextRequest = *firstRequest;
4327 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004328 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4329 sp<NotificationListener> listener = mListener.promote();
4330 if (listener != NULL) {
4331 listener->notifyRequestQueueEmpty();
4332 }
4333 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 }
4335
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004336 // In case we've been unpaused by setPaused clearing mDoPause, need to
4337 // update internal pause state (capture/setRepeatingRequest unpause
4338 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004339 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004340 if (mPaused) {
4341 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4342 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4343 if (statusTracker != 0) {
4344 statusTracker->markComponentActive(mStatusId);
4345 }
4346 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 mPaused = false;
4348
4349 // Check if we've reconfigured since last time, and reset the preview
4350 // request if so. Can't use 'NULL request == repeat' across configure calls.
4351 if (mReconfigured) {
4352 mPrevRequest.clear();
4353 mReconfigured = false;
4354 }
4355
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004356 if (nextRequest != NULL) {
4357 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004358 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4359 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004360
4361 // Since RequestThread::clear() removes buffers from the input stream,
4362 // get the right buffer here before unlocking mRequestLock
4363 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004364 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4365 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004366 if (res != OK) {
4367 // Can't get input buffer from gralloc queue - this could be due to
4368 // disconnected queue or other producer misbehavior, so not a fatal
4369 // error
4370 ALOGE("%s: Can't get input buffer, skipping request:"
4371 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004372
4373 sp<NotificationListener> listener = mListener.promote();
4374 if (listener != NULL) {
4375 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004376 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004377 nextRequest->mResultExtras);
4378 }
4379 return NULL;
4380 }
4381 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004382 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004383
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004384 return nextRequest;
4385}
4386
4387bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004388 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004389 status_t res;
4390 Mutex::Autolock l(mPauseLock);
4391 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004392 if (mPaused == false) {
4393 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004394 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004395 if (mNotifyPipelineDrain) {
4396 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4397 mNotifyPipelineDrain = false;
4398 mStreamIdsToBeDrained.clear();
4399 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004400 // Let the tracker know
4401 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4402 if (statusTracker != 0) {
4403 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4404 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004405 sp<Camera3Device> parent = mParent.promote();
4406 if (parent != nullptr) {
4407 parent->mRequestBufferSM.onRequestThreadPaused();
4408 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004409 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004410
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004411 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004412 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 return true;
4414 }
4415 }
4416 // We don't set mPaused to false here, because waitForNextRequest needs
4417 // to further manage the paused state in case of starvation.
4418 return false;
4419}
4420
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004421void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004422 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004423 // With work to do, mark thread as unpaused.
4424 // If paused by request (setPaused), don't resume, to avoid
4425 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004426 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004427 Mutex::Autolock p(mPauseLock);
4428 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004429 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4430 if (mPaused) {
4431 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4432 if (statusTracker != 0) {
4433 statusTracker->markComponentActive(mStatusId);
4434 }
4435 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004436 mPaused = false;
4437 }
4438}
4439
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004440void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4441 sp<Camera3Device> parent = mParent.promote();
4442 if (parent != NULL) {
4443 va_list args;
4444 va_start(args, fmt);
4445
4446 parent->setErrorStateV(fmt, args);
4447
4448 va_end(args);
4449 }
4450}
4451
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004452status_t Camera3Device::RequestThread::insertTriggers(
4453 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004454 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004455 Mutex::Autolock al(mTriggerMutex);
4456
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004457 sp<Camera3Device> parent = mParent.promote();
4458 if (parent == NULL) {
4459 CLOGE("RequestThread: Parent is gone");
4460 return DEAD_OBJECT;
4461 }
4462
Emilian Peevaebbe412018-01-15 13:53:24 +00004463 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004464 size_t count = mTriggerMap.size();
4465
4466 for (size_t i = 0; i < count; ++i) {
4467 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004468 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004469
4470 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4471 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4472 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004473 if (isAeTrigger) {
4474 request->mResultExtras.precaptureTriggerId = triggerId;
4475 mCurrentPreCaptureTriggerId = triggerId;
4476 } else {
4477 request->mResultExtras.afTriggerId = triggerId;
4478 mCurrentAfTriggerId = triggerId;
4479 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004480 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004481 }
4482
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004483 camera_metadata_entry entry = metadata.find(tag);
4484
4485 if (entry.count > 0) {
4486 /**
4487 * Already has an entry for this trigger in the request.
4488 * Rewrite it with our requested trigger value.
4489 */
4490 RequestTrigger oldTrigger = trigger;
4491
4492 oldTrigger.entryValue = entry.data.u8[0];
4493
4494 mTriggerReplacedMap.add(tag, oldTrigger);
4495 } else {
4496 /**
4497 * More typical, no trigger entry, so we just add it
4498 */
4499 mTriggerRemovedMap.add(tag, trigger);
4500 }
4501
4502 status_t res;
4503
4504 switch (trigger.getTagType()) {
4505 case TYPE_BYTE: {
4506 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4507 res = metadata.update(tag,
4508 &entryValue,
4509 /*count*/1);
4510 break;
4511 }
4512 case TYPE_INT32:
4513 res = metadata.update(tag,
4514 &trigger.entryValue,
4515 /*count*/1);
4516 break;
4517 default:
4518 ALOGE("%s: Type not supported: 0x%x",
4519 __FUNCTION__,
4520 trigger.getTagType());
4521 return INVALID_OPERATION;
4522 }
4523
4524 if (res != OK) {
4525 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4526 ", value %d", __FUNCTION__, trigger.getTagName(),
4527 trigger.entryValue);
4528 return res;
4529 }
4530
4531 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4532 trigger.getTagName(),
4533 trigger.entryValue);
4534 }
4535
4536 mTriggerMap.clear();
4537
4538 return count;
4539}
4540
4541status_t Camera3Device::RequestThread::removeTriggers(
4542 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004543 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004544 Mutex::Autolock al(mTriggerMutex);
4545
Emilian Peevaebbe412018-01-15 13:53:24 +00004546 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004547
4548 /**
4549 * Replace all old entries with their old values.
4550 */
4551 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4552 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4553
4554 status_t res;
4555
4556 uint32_t tag = trigger.metadataTag;
4557 switch (trigger.getTagType()) {
4558 case TYPE_BYTE: {
4559 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4560 res = metadata.update(tag,
4561 &entryValue,
4562 /*count*/1);
4563 break;
4564 }
4565 case TYPE_INT32:
4566 res = metadata.update(tag,
4567 &trigger.entryValue,
4568 /*count*/1);
4569 break;
4570 default:
4571 ALOGE("%s: Type not supported: 0x%x",
4572 __FUNCTION__,
4573 trigger.getTagType());
4574 return INVALID_OPERATION;
4575 }
4576
4577 if (res != OK) {
4578 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4579 ", trigger value %d", __FUNCTION__,
4580 trigger.getTagName(), trigger.entryValue);
4581 return res;
4582 }
4583 }
4584 mTriggerReplacedMap.clear();
4585
4586 /**
4587 * Remove all new entries.
4588 */
4589 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4590 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4591 status_t res = metadata.erase(trigger.metadataTag);
4592
4593 if (res != OK) {
4594 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4595 ", trigger value %d", __FUNCTION__,
4596 trigger.getTagName(), trigger.entryValue);
4597 return res;
4598 }
4599 }
4600 mTriggerRemovedMap.clear();
4601
4602 return OK;
4603}
4604
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004605status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004606 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004607 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004608 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004609 status_t res;
4610
Emilian Peevaebbe412018-01-15 13:53:24 +00004611 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004612
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004613 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004614 // exists
4615 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4616 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4617 if (afTrigger.count > 0 &&
4618 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4619 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004620 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004621 if (res != OK) return res;
4622 }
4623
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004624 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004625 // if none already exists
4626 camera_metadata_entry pcTrigger =
4627 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4628 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4629 if (pcTrigger.count > 0 &&
4630 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4631 pcId.count == 0) {
4632 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004633 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004634 if (res != OK) return res;
4635 }
4636
4637 return OK;
4638}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004639
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004640bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4641 const sp<CaptureRequest> &request) {
4642 ATRACE_CALL();
4643
Austin Borger3560b7e2022-10-27 12:20:29 -07004644 if (mOverrideToPortrait) {
4645 Mutex::Autolock l(mTriggerMutex);
4646 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4647 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4648 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4649 &rotateAndCrop_u8, 1);
4650 return true;
4651 }
4652
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004653 if (request->mRotateAndCropAuto) {
4654 Mutex::Autolock l(mTriggerMutex);
4655 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4656
4657 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4658 if (rotateAndCropEntry.count > 0) {
4659 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4660 return false;
4661 } else {
4662 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4663 return true;
4664 }
4665 } else {
4666 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4667 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4668 &rotateAndCrop_u8, 1);
4669 return true;
4670 }
4671 }
4672 return false;
4673}
4674
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004675bool Camera3Device::RequestThread::overrideTestPattern(
4676 const sp<CaptureRequest> &request) {
4677 ATRACE_CALL();
4678
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004679 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004680
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004681 Mutex::Autolock l(mTriggerMutex);
4682
4683 bool changed = false;
4684
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004685 // For a multi-camera, the physical cameras support the same set of
4686 // test pattern modes as the logical camera.
4687 for (auto& settings : request->mSettingsList) {
4688 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004689
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004690 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4691 int32_t testPatternData[4] = {
4692 settings.mOriginalTestPatternData[0],
4693 settings.mOriginalTestPatternData[1],
4694 settings.mOriginalTestPatternData[2],
4695 settings.mOriginalTestPatternData[3]
4696 };
4697 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4698 testPatternMode = mCameraMute;
4699 testPatternData[0] = 0;
4700 testPatternData[1] = 0;
4701 testPatternData[2] = 0;
4702 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004703 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004704
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004705 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4706 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4707 if (testPatternEntry.count > 0) {
4708 if (testPatternEntry.data.i32[0] != testPatternMode) {
4709 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004710 changed = true;
4711 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004712 } else if (supportTestPatternModeKey) {
4713 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4714 &testPatternMode, 1);
4715 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004716 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004717
4718 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4719 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4720 if (testPatternColor.count >= 4) {
4721 for (size_t i = 0; i < 4; i++) {
4722 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4723 testPatternColor.data.i32[i] = testPatternData[i];
4724 changed = true;
4725 }
4726 }
4727 } else if (supportTestPatternDataKey) {
4728 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4729 testPatternData, 4);
4730 changed = true;
4731 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004732 }
4733
4734 return changed;
4735}
4736
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004737status_t Camera3Device::RequestThread::setHalInterface(
4738 sp<HalInterface> newHalInterface) {
4739 if (newHalInterface.get() == nullptr) {
4740 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4741 return DEAD_OBJECT;
4742 }
4743
4744 mInterface = newHalInterface;
4745
4746 return OK;
4747}
4748
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004749/**
4750 * PreparerThread inner class methods
4751 */
4752
4753Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004754 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004755 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004756}
4757
4758Camera3Device::PreparerThread::~PreparerThread() {
4759 Thread::requestExitAndWait();
4760 if (mCurrentStream != nullptr) {
4761 mCurrentStream->cancelPrepare();
4762 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4763 mCurrentStream.clear();
4764 }
4765 clear();
4766}
4767
Ruben Brunkc78ac262015-08-13 17:58:46 -07004768status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004769 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004770 status_t res;
4771
4772 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004773 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004774
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004775 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776 if (res == OK) {
4777 // No preparation needed, fire listener right off
4778 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004779 if (listener != NULL) {
4780 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004781 }
4782 return OK;
4783 } else if (res != NOT_ENOUGH_DATA) {
4784 return res;
4785 }
4786
4787 // Need to prepare, start up thread if necessary
4788 if (!mActive) {
4789 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4790 // isn't running
4791 Thread::requestExitAndWait();
4792 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4793 if (res != OK) {
4794 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004795 if (listener != NULL) {
4796 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004797 }
4798 return res;
4799 }
4800 mCancelNow = false;
4801 mActive = true;
4802 ALOGV("%s: Preparer stream started", __FUNCTION__);
4803 }
4804
4805 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004806 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004807 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4808
4809 return OK;
4810}
4811
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004812void Camera3Device::PreparerThread::pause() {
4813 ATRACE_CALL();
4814
4815 Mutex::Autolock l(mLock);
4816
4817 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4818 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4819 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4820 int currentMaxCount = mCurrentMaxCount;
4821 mPendingStreams.clear();
4822 mCancelNow = true;
4823 while (mActive) {
4824 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4825 if (res == TIMED_OUT) {
4826 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4827 return;
4828 } else if (res != OK) {
4829 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4830 return;
4831 }
4832 }
4833
4834 //Check whether the prepare thread was able to complete the current
4835 //stream. In case work is still pending emplace it along with the rest
4836 //of the streams in the pending list.
4837 if (currentStream != nullptr) {
4838 if (!mCurrentPrepareComplete) {
4839 pendingStreams.emplace(currentMaxCount, currentStream);
4840 }
4841 }
4842
4843 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4844 for (const auto& it : mPendingStreams) {
4845 it.second->cancelPrepare();
4846 }
4847}
4848
4849status_t Camera3Device::PreparerThread::resume() {
4850 ATRACE_CALL();
4851 status_t res;
4852
4853 Mutex::Autolock l(mLock);
4854 sp<NotificationListener> listener = mListener.promote();
4855
4856 if (mActive) {
4857 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4858 return NO_INIT;
4859 }
4860
4861 auto it = mPendingStreams.begin();
4862 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004863 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004864 if (res == OK) {
4865 if (listener != NULL) {
4866 listener->notifyPrepared(it->second->getId());
4867 }
4868 it = mPendingStreams.erase(it);
4869 } else if (res != NOT_ENOUGH_DATA) {
4870 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4871 res, strerror(-res));
4872 it = mPendingStreams.erase(it);
4873 } else {
4874 it++;
4875 }
4876 }
4877
4878 if (mPendingStreams.empty()) {
4879 return OK;
4880 }
4881
4882 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4883 if (res != OK) {
4884 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4885 __FUNCTION__, res, strerror(-res));
4886 return res;
4887 }
4888 mCancelNow = false;
4889 mActive = true;
4890 ALOGV("%s: Preparer stream started", __FUNCTION__);
4891
4892 return OK;
4893}
4894
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004895status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004896 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004897 Mutex::Autolock l(mLock);
4898
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004899 for (const auto& it : mPendingStreams) {
4900 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004901 }
4902 mPendingStreams.clear();
4903 mCancelNow = true;
4904
4905 return OK;
4906}
4907
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004908void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004909 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004910 Mutex::Autolock l(mLock);
4911 mListener = listener;
4912}
4913
4914bool Camera3Device::PreparerThread::threadLoop() {
4915 status_t res;
4916 {
4917 Mutex::Autolock l(mLock);
4918 if (mCurrentStream == nullptr) {
4919 // End thread if done with work
4920 if (mPendingStreams.empty()) {
4921 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4922 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4923 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4924 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004925 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004926 return false;
4927 }
4928
4929 // Get next stream to prepare
4930 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004931 mCurrentStream = it->second;
4932 mCurrentMaxCount = it->first;
4933 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004934 mPendingStreams.erase(it);
4935 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4936 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4937 } else if (mCancelNow) {
4938 mCurrentStream->cancelPrepare();
4939 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4940 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4941 mCurrentStream.clear();
4942 mCancelNow = false;
4943 return true;
4944 }
4945 }
4946
4947 res = mCurrentStream->prepareNextBuffer();
4948 if (res == NOT_ENOUGH_DATA) return true;
4949 if (res != OK) {
4950 // Something bad happened; try to recover by cancelling prepare and
4951 // signalling listener anyway
4952 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4953 mCurrentStream->getId(), res, strerror(-res));
4954 mCurrentStream->cancelPrepare();
4955 }
4956
4957 // This stream has finished, notify listener
4958 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004959 sp<NotificationListener> listener = mListener.promote();
4960 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004961 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4962 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004963 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004964 }
4965
4966 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4967 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004968 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004969
4970 return true;
4971}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004972
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004973status_t Camera3Device::RequestBufferStateMachine::initialize(
4974 sp<camera3::StatusTracker> statusTracker) {
4975 if (statusTracker == nullptr) {
4976 ALOGE("%s: statusTracker is null", __FUNCTION__);
4977 return BAD_VALUE;
4978 }
4979
4980 std::lock_guard<std::mutex> lock(mLock);
4981 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004982 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004983 return OK;
4984}
4985
4986bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4987 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004988 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004989 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004990 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004991 return true;
4992 }
4993 return false;
4994}
4995
4996void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4997 std::lock_guard<std::mutex> lock(mLock);
4998 if (!mRequestBufferOngoing) {
4999 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5000 return;
5001 }
5002 mRequestBufferOngoing = false;
5003 if (mStatus == RB_STATUS_PENDING_STOP) {
5004 checkSwitchToStopLocked();
5005 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005006 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005007}
5008
5009void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5010 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005011 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005012 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005013 return;
5014}
5015
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005016void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005017 std::lock_guard<std::mutex> lock(mLock);
5018 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005019 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5020 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005021 mInflightMapEmpty = false;
5022 if (mStatus == RB_STATUS_STOPPED) {
5023 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005024 }
5025 return;
5026}
5027
5028void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5029 std::lock_guard<std::mutex> lock(mLock);
5030 mRequestThreadPaused = true;
5031 if (mStatus == RB_STATUS_PENDING_STOP) {
5032 checkSwitchToStopLocked();
5033 }
5034 return;
5035}
5036
5037void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5038 std::lock_guard<std::mutex> lock(mLock);
5039 mInflightMapEmpty = true;
5040 if (mStatus == RB_STATUS_PENDING_STOP) {
5041 checkSwitchToStopLocked();
5042 }
5043 return;
5044}
5045
5046void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5047 std::lock_guard<std::mutex> lock(mLock);
5048 if (!checkSwitchToStopLocked()) {
5049 mStatus = RB_STATUS_PENDING_STOP;
5050 }
5051 return;
5052}
5053
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005054bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5055 std::lock_guard<std::mutex> lock(mLock);
5056 if (mRequestBufferOngoing) {
5057 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5058 __FUNCTION__);
5059 return false;
5060 }
5061 mSwitchedToOffline = true;
5062 mInflightMapEmpty = true;
5063 mRequestThreadPaused = true;
5064 mStatus = RB_STATUS_STOPPED;
5065 return true;
5066}
5067
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005068void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5069 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5070 if (statusTracker != nullptr) {
5071 if (active) {
5072 statusTracker->markComponentActive(mRequestBufferStatusId);
5073 } else {
5074 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5075 }
5076 }
5077}
5078
5079bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5080 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5081 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005082 return true;
5083 }
5084 return false;
5085}
5086
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005087bool Camera3Device::startRequestBuffer() {
5088 return mRequestBufferSM.startRequestBuffer();
5089}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005090
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005091void Camera3Device::endRequestBuffer() {
5092 mRequestBufferSM.endRequestBuffer();
5093}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005094
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005095nsecs_t Camera3Device::getWaitDuration() {
5096 return kBaseGetBufferWait + getExpectedInFlightDuration();
5097}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005098
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005099void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5100 mInterface->getInflightBufferKeys(out);
5101}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005102
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005103void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5104 mInterface->getInflightRequestBufferKeys(out);
5105}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005106
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005107std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5108 std::vector<sp<Camera3StreamInterface>> ret;
5109 bool hasInputStream = mInputStream != nullptr;
5110 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5111 if (hasInputStream) {
5112 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005113 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005114 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5115 ret.push_back(mOutputStreams[i]);
5116 }
5117 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5118 ret.push_back(mDeletedStreams[i]);
5119 }
5120 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005121}
5122
Emilian Peevcc0b7952020-01-07 13:54:47 -08005123void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5124 ATRACE_CALL();
5125
5126 if (offlineStreamIds == nullptr) {
5127 return;
5128 }
5129
5130 Mutex::Autolock il(mInterfaceLock);
5131
5132 auto streamIds = mOutputStreams.getStreamIds();
5133 bool hasInputStream = mInputStream != nullptr;
5134 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5135 offlineStreamIds->push_back(mInputStream->getId());
5136 }
5137
5138 for (const auto & streamId : streamIds) {
5139 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5140 // Streams that use the camera buffer manager are currently not supported in
5141 // offline mode
5142 if (stream->getOfflineProcessingSupport() &&
5143 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5144 offlineStreamIds->push_back(streamId);
5145 }
5146 }
5147}
5148
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005149status_t Camera3Device::setRotateAndCropAutoBehavior(
5150 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5151 ATRACE_CALL();
5152 Mutex::Autolock il(mInterfaceLock);
5153 Mutex::Autolock l(mLock);
5154 if (mRequestThread == nullptr) {
5155 return INVALID_OPERATION;
5156 }
5157 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5158}
5159
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005160bool Camera3Device::supportsCameraMute() {
5161 Mutex::Autolock il(mInterfaceLock);
5162 Mutex::Autolock l(mLock);
5163
5164 return mSupportCameraMute;
5165}
5166
5167status_t Camera3Device::setCameraMute(bool enabled) {
5168 ATRACE_CALL();
5169 Mutex::Autolock il(mInterfaceLock);
5170 Mutex::Autolock l(mLock);
5171
5172 if (mRequestThread == nullptr || !mSupportCameraMute) {
5173 return INVALID_OPERATION;
5174 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005175 int32_t muteMode =
5176 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5177 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5178 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5179 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005180}
5181
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005182status_t Camera3Device::injectCamera(const String8& injectedCamId,
5183 sp<CameraProviderManager> manager) {
5184 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5185 ATRACE_CALL();
5186 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005187 // When the camera device is active, injectCamera() and stopInjection() will call
5188 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5189 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5190 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5191 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5192 // waitUntilStateThenRelock().
5193 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005194
5195 status_t res = NO_ERROR;
5196 if (mInjectionMethods->isInjecting()) {
5197 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5198 return OK;
5199 } else {
5200 res = mInjectionMethods->stopInjection();
5201 if (res != OK) {
5202 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5203 __FUNCTION__, res);
5204 return res;
5205 }
5206 }
5207 }
5208
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005209 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005210 if (res != OK) {
5211 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5212 __FUNCTION__, res);
5213 return res;
5214 }
5215
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005216 // When the second display of android is cast to the remote device, and the opened camera is
5217 // also cast to the second display, in this case, because the camera has configured the streams
5218 // at this time, we can directly call injectCamera() to replace the internal camera with
5219 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005220 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5221 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5222
5223 camera3::camera_stream_configuration injectionConfig;
5224 std::vector<uint32_t> injectionBufferSizes;
5225 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5226 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5227 || injectionBufferSizes.size() <= 0) {
5228 ALOGE("Failed to inject camera due to abandoned configuration! "
5229 "mOperatingMode: %d injectionConfig.num_streams: %d "
5230 "injectionBufferSizes.size(): %zu", mOperatingMode,
5231 injectionConfig.num_streams, injectionBufferSizes.size());
5232 return DEAD_OBJECT;
5233 }
5234
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005235 res = mInjectionMethods->injectCamera(
5236 injectionConfig, injectionBufferSizes);
5237 if (res != OK) {
5238 ALOGE("Can't finish inject camera process!");
5239 return res;
5240 }
5241 }
5242
5243 return OK;
5244}
5245
5246status_t Camera3Device::stopInjection() {
5247 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5248 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005249 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005250 return mInjectionMethods->stopInjection();
5251}
5252
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005253void Camera3Device::overrideStreamUseCaseLocked() {
5254 if (mStreamUseCaseOverrides.size() == 0) {
5255 return;
5256 }
5257
5258 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5259 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5260 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5261 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5262 outputStreamsIndices[i] = i;
5263 }
5264
5265 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5266 [&](int a, int b) -> bool {
5267
5268 auto formatScore = [](int format) {
5269 switch (format) {
5270 case HAL_PIXEL_FORMAT_BLOB:
5271 return 4;
5272 case HAL_PIXEL_FORMAT_RAW16:
5273 case HAL_PIXEL_FORMAT_RAW10:
5274 case HAL_PIXEL_FORMAT_RAW12:
5275 return 3;
5276 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5277 return 2;
5278 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5279 return 1;
5280 default:
5281 return 0;
5282 }
5283 };
5284
5285 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5286 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5287 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5288 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5289 if (sizeA > sizeB ||
5290 (sizeA == sizeB && formatAScore >= formatBScore)) {
5291 return true;
5292 } else {
5293 return false;
5294 }
5295 });
5296
5297 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5298 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5299 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5300 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5301 }
5302}
5303
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005304}; // namespace android