blob: 4cc09f4d21916a12809386e31a85f7cee4fdab5b [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
73using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080074using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080075
76namespace android {
77
Emilian Peev5104fe92021-10-21 14:27:09 -070078Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080079 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070080 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080081 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070082 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070083 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070084 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070085 mUsePartialResult(false),
86 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080087 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080088 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070089 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070090 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070091 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070092 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070093 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070094 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000095 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010096 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070097 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070098 mNeedFixupMonochromeTags(false),
99 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
105Camera3Device::~Camera3Device()
106{
107 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700109 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800113 return mId;
114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116status_t Camera3Device::initializeCommonLocked() {
117
Ravneetdbd5b242022-03-02 07:22:46 +0000118 /** Start watchdog thread */
119 mCameraServiceWatchdog = new CameraServiceWatchdog();
120 mCameraServiceWatchdog->run("CameraServiceWatchdog");
121
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700122 /** Start up status tracker thread */
123 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 if (res != OK) {
126 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
127 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800128 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700129 mStatusTracker.clear();
130 return res;
131 }
132
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700133 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700134 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700135
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700136 if (mUseHalBufManager) {
137 res = mRequestBufferSM.initialize(mStatusTracker);
138 if (res != OK) {
139 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
140 strerror(-res), res);
141 mInterface->close();
142 mStatusTracker.clear();
143 return res;
144 }
145 }
146
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800147 /** Create buffer manager */
148 mBufferManager = new Camera3BufferManager();
149
150 Vector<int32_t> sessionParamKeys;
151 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
152 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
153 if (sessionKeysEntry.count > 0) {
154 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
155 }
156
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700157 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
158 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
159 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
160 if (availableTestPatternModes.data.i32[i] ==
161 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
162 mSupportCameraMute = true;
163 mSupportTestPatternSolidColor = true;
164 break;
165 } else if (availableTestPatternModes.data.i32[i] ==
166 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
167 mSupportCameraMute = true;
168 mSupportTestPatternSolidColor = false;
169 }
170 }
171
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700172 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800173 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700174 this, mStatusTracker, mInterface, sessionParamKeys,
175 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800177 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700178 SET_ERR_L("Unable to start request queue thread: %s (%d)",
179 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800180 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800181 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800182 return res;
183 }
184
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700185 mPreparerThread = new PreparerThread();
186
Ruben Brunk183f0562015-08-12 12:55:02 -0700187 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800188 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400189 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700190 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700191 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800192 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800193
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800194 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800195 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800196 camera_metadata_entry timestampSource =
197 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
198 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
199 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800200 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800201 }
202
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700203 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100204 camera_metadata_entry partialResultsCount =
205 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
206 if (partialResultsCount.count > 0) {
207 mNumPartialResults = partialResultsCount.data.i32[0];
208 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700209 }
210
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800211 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
212 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700213 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700214 if (res != OK) {
215 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
216 return res;
217 }
218 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800220 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800221 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800222
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700223 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
224 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
225 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
226 }
227
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800228 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
229 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
230 }
231
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800232 // Hidl/AidlCamera3DeviceInjectionMethods
233 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800234
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800235 return OK;
236}
237
238status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700239 return disconnectImpl();
240}
241
242status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800243 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700244 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800245
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700246 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700247 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700248 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800249 Mutex::Autolock il(mInterfaceLock);
250 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
251 {
252 Mutex::Autolock l(mLock);
253 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 if (mStatus == STATUS_ACTIVE ||
256 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
257 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700258 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800259 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800261 } else {
262 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
263 if (res != OK) {
264 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
265 maxExpectedDuration);
266 // Continue to close device even in case of error
267 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700269 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatus == STATUS_ERROR) {
272 CLOGE("Shutting down in an error state");
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mStatusTracker != NULL) {
276 mStatusTracker->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 if (mRequestThread != NULL) {
280 mRequestThread->requestExit();
281 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700282
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800283 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
284 for (size_t i = 0; i < mOutputStreams.size(); i++) {
285 streams.push_back(mOutputStreams[i]);
286 }
287 if (mInputStream != nullptr) {
288 streams.push_back(mInputStream);
289 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700291 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800292 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
293 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
295 // HAL may be in a bad state, so waiting for request thread
296 // (which may be stuck in the HAL processCaptureRequest call)
297 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800298 // give up mInterfaceLock here and then lock it again. Could this lead
299 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 mRequestThread->join();
301 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800303 Mutex::Autolock il(mInterfaceLock);
304 if (mStatusTracker != NULL) {
305 mStatusTracker->join();
306 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800307
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800308 if (mInjectionMethods->isInjecting()) {
309 mInjectionMethods->stopInjection();
310 }
311
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800312 HalInterface* interface;
313 {
314 Mutex::Autolock l(mLock);
315 mRequestThread.clear();
316 Mutex::Autolock stLock(mTrackerLock);
317 mStatusTracker.clear();
318 interface = mInterface.get();
319 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 // Call close without internal mutex held, as the HAL close may need to
322 // wait on assorted callbacks,etc, to complete before it can return.
Ravneetdbd5b242022-03-02 07:22:46 +0000323 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700324
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800325 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800327 {
328 Mutex::Autolock l(mLock);
329 mInterface->clear();
330 mOutputStreams.clear();
331 mInputStream.clear();
332 mDeletedStreams.clear();
333 mBufferManager.clear();
334 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
335 }
336
337 for (auto& weakStream : streams) {
338 sp<Camera3StreamInterface> stream = weakStream.promote();
339 if (stream != nullptr) {
340 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
341 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
342 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700343 }
344 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700345 ALOGI("%s: X", __FUNCTION__);
Ravneetdbd5b242022-03-02 07:22:46 +0000346
347 if (mCameraServiceWatchdog != NULL) {
348 mCameraServiceWatchdog->requestExit();
349 mCameraServiceWatchdog.clear();
350 }
351
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700352 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800353}
354
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700355// For dumping/debugging only -
356// try to acquire a lock a few times, eventually give up to proceed with
357// debug/dump operations
358bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
359 bool gotLock = false;
360 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
361 if (lock.tryLock() == NO_ERROR) {
362 gotLock = true;
363 break;
364 } else {
365 usleep(kDumpSleepDuration);
366 }
367 }
368 return gotLock;
369}
370
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800371nsecs_t Camera3Device::getMonoToBoottimeOffset() {
372 // try three times to get the clock offset, choose the one
373 // with the minimum gap in measurements.
374 const int tries = 3;
375 nsecs_t bestGap, measured;
376 for (int i = 0; i < tries; ++i) {
377 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
378 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
379 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
380 const nsecs_t gap = tmono2 - tmono;
381 if (i == 0 || gap < bestGap) {
382 bestGap = gap;
383 measured = tbase - ((tmono + tmono2) >> 1);
384 }
385 }
386 return measured;
387}
388
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800389ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
390 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700391 // Get max jpeg size (area-wise) for default sensor pixel mode
392 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800393 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700394 /*isUltraHighResolutionSensor*/false);
395 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
396 // not ultra high res sensor
397 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800398 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700399 /*isUltraHighResolution*/true);
400 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800401 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
402 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700403 return BAD_VALUE;
404 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700405 bool useMaxSensorPixelModeThreshold = false;
406 if (uhrMaxJpegResolution.width != 0 &&
407 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
408 // Use the ultra high res max jpeg size and max jpeg buffer size
409 useMaxSensorPixelModeThreshold = true;
410 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700411
Zhijun Hef7da0962014-04-24 13:27:56 -0700412 // Get max jpeg buffer size
413 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800414 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700415 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800416 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
417 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700418 return BAD_VALUE;
419 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700421
422 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
423 if (useMaxSensorPixelModeThreshold) {
424 maxJpegBufferSize =
425 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
426 maxDefaultJpegResolution, maxJpegBufferSize);
427 chosenMaxJpegResolution = uhrMaxJpegResolution;
428 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800429 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700430
431 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700433 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800434 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
435 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700436 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800437 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
438 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700439 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700440 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700441 return jpegBufferSize;
442}
443
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800444ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700445 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800446 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700447 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800448 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
449 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700450 return BAD_VALUE;
451 }
452 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
453 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
454 return maxBytesForPointCloud;
455}
456
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800457ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
458 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 const int PER_CONFIGURATION_SIZE = 3;
460 const int WIDTH_OFFSET = 0;
461 const int HEIGHT_OFFSET = 1;
462 const int SIZE_OFFSET = 2;
463 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800464 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800465 camera3::SessionConfigurationUtils::getAppropriateModeTag(
466 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
467 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800468 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800469 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800470 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
471 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800472 return BAD_VALUE;
473 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700474
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800475 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
476 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
477 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
478 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
479 }
480 }
481
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800482 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
483 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800484 return BAD_VALUE;
485}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700486
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800487status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
488 ATRACE_CALL();
489 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700490
491 // Try to lock, but continue in case of failure (to avoid blocking in
492 // deadlocks)
493 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
494 bool gotLock = tryLockSpinRightRound(mLock);
495
496 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800497 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
498 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700499 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
501 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700502
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800503 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700504
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800505 String16 templatesOption("-t");
506 int n = args.size();
507 for (int i = 0; i < n; i++) {
508 if (args[i] == templatesOption) {
509 dumpTemplates = true;
510 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000511 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700512 if (i + 1 < n) {
513 String8 monitorTags = String8(args[i + 1]);
514 if (monitorTags == "off") {
515 mTagMonitor.disableMonitoring();
516 } else {
517 mTagMonitor.parseTagsToMonitor(monitorTags);
518 }
519 } else {
520 mTagMonitor.disableMonitoring();
521 }
522 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800523 }
524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800526
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800527 const char *status =
528 mStatus == STATUS_ERROR ? "ERROR" :
529 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700530 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
531 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800532 mStatus == STATUS_ACTIVE ? "ACTIVE" :
533 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700534
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800535 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700536 if (mStatus == STATUS_ERROR) {
537 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
538 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800539 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800540 const char *mode =
541 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
542 mOperatingMode == static_cast<int>(
543 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
544 "CUSTOM";
545 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800546
547 if (mInputStream != NULL) {
548 write(fd, lines.string(), lines.size());
549 mInputStream->dump(fd, args);
550 } else {
551 lines.appendFormat(" No input stream.\n");
552 write(fd, lines.string(), lines.size());
553 }
554 for (size_t i = 0; i < mOutputStreams.size(); i++) {
555 mOutputStreams[i]->dump(fd,args);
556 }
557
Zhijun He431503c2016-03-07 17:30:16 -0800558 if (mBufferManager != NULL) {
559 lines = String8(" Camera3 Buffer Manager:\n");
560 write(fd, lines.string(), lines.size());
561 mBufferManager->dump(fd, args);
562 }
Zhijun He125684a2015-12-26 15:07:30 -0800563
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700564 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700565 if (mInFlightLock.try_lock()) {
566 if (mInFlightMap.size() == 0) {
567 lines.append(" None\n");
568 } else {
569 for (size_t i = 0; i < mInFlightMap.size(); i++) {
570 InFlightRequest r = mInFlightMap.valueAt(i);
571 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
572 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
573 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
574 r.numBuffersLeft);
575 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700576 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700577 mInFlightLock.unlock();
578 } else {
579 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700580 }
581 write(fd, lines.string(), lines.size());
582
Shuzhen Wang686f6442017-06-20 16:16:04 -0700583 if (mRequestThread != NULL) {
584 mRequestThread->dumpCaptureRequestLatency(fd,
585 " ProcessCaptureRequest latency histogram:");
586 }
587
Igor Murashkin1e479c02013-09-06 16:55:14 -0700588 {
589 lines = String8(" Last request sent:\n");
590 write(fd, lines.string(), lines.size());
591
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700592 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700593 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
594 }
595
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800596 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700597 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800598 "TEMPLATE_PREVIEW",
599 "TEMPLATE_STILL_CAPTURE",
600 "TEMPLATE_VIDEO_RECORD",
601 "TEMPLATE_VIDEO_SNAPSHOT",
602 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800603 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800604 };
605
Emilian Peevf4816702020-04-03 15:44:51 -0700606 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800607 camera_metadata_t *templateRequest = nullptr;
608 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700609 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800611 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 lines.append(" Not supported\n");
613 write(fd, lines.string(), lines.size());
614 } else {
615 write(fd, lines.string(), lines.size());
616 dump_indented_camera_metadata(templateRequest,
617 fd, /*verbosity*/2, /*indentation*/8);
618 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800620 }
621 }
622
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700623 mTagMonitor.dumpMonitoredMetadata(fd);
624
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800625 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800626 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800627 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800629 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800630
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700631 if (gotLock) mLock.unlock();
632 if (gotInterfaceLock) mInterfaceLock.unlock();
633
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800634 return OK;
635}
636
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700637status_t Camera3Device::startWatchingTags(const String8 &tags) {
638 mTagMonitor.parseTagsToMonitor(tags);
639 return OK;
640}
641
642status_t Camera3Device::stopWatchingTags() {
643 mTagMonitor.disableMonitoring();
644 return OK;
645}
646
647status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
648 mTagMonitor.getLatestMonitoredTagEvents(out);
649 return OK;
650}
651
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800652const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800653 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
655 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700656 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800657 mStatus == STATUS_ERROR ?
658 "when in error state" : "before init");
659 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700660 if (physicalId.isEmpty()) {
661 return mDeviceInfo;
662 } else {
663 std::string id(physicalId.c_str());
664 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
665 return mPhysicalDeviceInfoMap.at(id);
666 } else {
667 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
668 return mDeviceInfo;
669 }
670 }
671}
672
673const CameraMetadata& Camera3Device::info() const {
674 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800675 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676}
677
Jianing Wei90e59c92014-03-12 18:29:36 -0700678status_t Camera3Device::checkStatusOkToCaptureLocked() {
679 switch (mStatus) {
680 case STATUS_ERROR:
681 CLOGE("Device has encountered a serious error");
682 return INVALID_OPERATION;
683 case STATUS_UNINITIALIZED:
684 CLOGE("Device not initialized");
685 return INVALID_OPERATION;
686 case STATUS_UNCONFIGURED:
687 case STATUS_CONFIGURED:
688 case STATUS_ACTIVE:
689 // OK
690 break;
691 default:
692 SET_ERR_L("Unexpected status: %d", mStatus);
693 return INVALID_OPERATION;
694 }
695 return OK;
696}
697
698status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700701 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700702 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700703 if (requestList == NULL) {
704 CLOGE("requestList cannot be NULL.");
705 return BAD_VALUE;
706 }
707
Jianing Weicb0652e2014-03-12 18:29:36 -0700708 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000709 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700710 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
711 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
712 ++metadataIt, ++surfaceMapIt) {
713 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700714 if (newRequest == 0) {
715 CLOGE("Can't create capture request");
716 return BAD_VALUE;
717 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700718
Shuzhen Wang9d066012016-09-30 11:30:20 -0700719 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700720 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700721
Jianing Weicb0652e2014-03-12 18:29:36 -0700722 // Setup burst Id and request Id
723 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800724 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
725 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700726 CLOGE("RequestID does not exist in metadata");
727 return BAD_VALUE;
728 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800729 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700730
Jianing Wei90e59c92014-03-12 18:29:36 -0700731 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700732
733 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700734 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700735 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
736 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
737 return BAD_VALUE;
738 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700739
740 // Setup batch size if this is a high speed video recording request.
741 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
742 auto firstRequest = requestList->begin();
743 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
744 if (outputStream->isVideoStream()) {
745 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800746 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700747 break;
748 }
749 }
750 }
751
Jianing Wei90e59c92014-03-12 18:29:36 -0700752 return OK;
753}
754
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800755status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800756 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800757
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700759 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000760 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800762 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700763}
764
Emilian Peevaebbe412018-01-15 13:53:24 +0000765void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700766 std::list<const SurfaceMap>& surfaceMaps,
767 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000768 PhysicalCameraSettingsList requestList;
769 requestList.push_back({std::string(getId().string()), request});
770 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700771
772 SurfaceMap surfaceMap;
773 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
774 // With no surface list passed in, stream and surface will have 1-to-1
775 // mapping. So the surface index is 0 for each stream in the surfaceMap.
776 for (size_t i = 0; i < streams.count; i++) {
777 surfaceMap[streams.data.i32[i]].push_back(0);
778 }
779 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800780}
781
Jianing Wei90e59c92014-03-12 18:29:36 -0700782status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000783 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 const std::list<const SurfaceMap> &surfaceMaps,
785 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700786 /*out*/
787 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700788 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700789 nsecs_t requestTimeNs = systemTime();
790
Jianing Wei90e59c92014-03-12 18:29:36 -0700791 Mutex::Autolock il(mInterfaceLock);
792 Mutex::Autolock l(mLock);
793
794 status_t res = checkStatusOkToCaptureLocked();
795 if (res != OK) {
796 // error logged by previous call
797 return res;
798 }
799
800 RequestList requestList;
801
Shuzhen Wang0129d522016-10-30 22:43:41 -0700802 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700803 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700804 if (res != OK) {
805 // error logged by previous call
806 return res;
807 }
808
809 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700810 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700811 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 }
814
815 if (res == OK) {
816 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
817 if (res != OK) {
818 SET_ERR_L("Can't transition to active in %f seconds!",
819 kActiveTimeout/1e9);
820 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800821 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700822 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700823 } else {
824 CLOGE("Cannot queue request. Impossible.");
825 return BAD_VALUE;
826 }
827
828 return res;
829}
830
Emilian Peevaebbe412018-01-15 13:53:24 +0000831status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700833 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 ATRACE_CALL();
835
Emilian Peevaebbe412018-01-15 13:53:24 +0000836 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700837}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800838
Jianing Weicb0652e2014-03-12 18:29:36 -0700839status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
840 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800841 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800842
Emilian Peevaebbe412018-01-15 13:53:24 +0000843 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700844 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000845 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800849}
850
Emilian Peevaebbe412018-01-15 13:53:24 +0000851status_t Camera3Device::setStreamingRequestList(
852 const List<const PhysicalCameraSettingsList> &requestsList,
853 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700854 ATRACE_CALL();
855
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700857}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800858
859sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 status_t res;
862
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700863 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800864 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
865 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000866 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700867 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700868 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800869 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700870 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800871 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700872 } else if (mStatus == STATUS_UNCONFIGURED) {
873 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700874 CLOGE("No streams configured");
875 return NULL;
876 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800877 }
878
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800880 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800881}
882
Jianing Weicb0652e2014-03-12 18:29:36 -0700883status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800884 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800886 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800887
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800888 switch (mStatus) {
889 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700890 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800891 return INVALID_OPERATION;
892 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700893 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700895 case STATUS_UNCONFIGURED:
896 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800897 case STATUS_ACTIVE:
898 // OK
899 break;
900 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700901 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800902 return INVALID_OPERATION;
903 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800904 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700905
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700906 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800907}
908
909status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
910 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700911 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800912
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700913 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800914}
915
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700916status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800917 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700918 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700919 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700920 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700921 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800922 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
923 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700924
925 status_t res;
926 bool wasActive = false;
927
928 switch (mStatus) {
929 case STATUS_ERROR:
930 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
931 return INVALID_OPERATION;
932 case STATUS_UNINITIALIZED:
933 ALOGE("%s: Device not initialized", __FUNCTION__);
934 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700935 case STATUS_UNCONFIGURED:
936 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700937 // OK
938 break;
939 case STATUS_ACTIVE:
940 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700941 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700943 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700944 return res;
945 }
946 wasActive = true;
947 break;
948 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700949 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700950 return INVALID_OPERATION;
951 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700952 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700953
954 if (mInputStream != 0) {
955 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
956 return INVALID_OPERATION;
957 }
958
959 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
960 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700961 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700962
963 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800964 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700965
966 *id = mNextStreamId++;
967
968 // Continue captures if active at start
969 if (wasActive) {
970 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100971 // Reuse current operating mode and session parameters for new stream config
972 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700973 if (res != OK) {
974 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
975 __FUNCTION__, mNextStreamId, strerror(-res), res);
976 return res;
977 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700978 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700979 }
980
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800981 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700982 return OK;
983}
984
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700985status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700986 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700987 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800988 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800989 const std::unordered_set<int32_t> &sensorPixelModesUsed,
990 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800991 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800992 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700993 ATRACE_CALL();
994
995 if (consumer == nullptr) {
996 ALOGE("%s: consumer must not be null", __FUNCTION__);
997 return BAD_VALUE;
998 }
999
1000 std::vector<sp<Surface>> consumers;
1001 consumers.push_back(consumer);
1002
1003 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001004 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001005 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001006 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001007}
1008
1009static bool isRawFormat(int format) {
1010 switch (format) {
1011 case HAL_PIXEL_FORMAT_RAW16:
1012 case HAL_PIXEL_FORMAT_RAW12:
1013 case HAL_PIXEL_FORMAT_RAW10:
1014 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1015 return true;
1016 default:
1017 return false;
1018 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001019}
1020
1021status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1022 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001023 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001024 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001025 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001026 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1027 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001028 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001029
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001030 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001031 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001032 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001033 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001034 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001035 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1036 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001037 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001038 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001039 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001040
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001041 status_t res;
1042 bool wasActive = false;
1043
1044 switch (mStatus) {
1045 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001046 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001047 return INVALID_OPERATION;
1048 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001049 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001051 case STATUS_UNCONFIGURED:
1052 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001053 // OK
1054 break;
1055 case STATUS_ACTIVE:
1056 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001057 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001058 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060 return res;
1061 }
1062 wasActive = true;
1063 break;
1064 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001065 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001066 return INVALID_OPERATION;
1067 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001068 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001069
1070 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001071
Shuzhen Wang0129d522016-10-30 22:43:41 -07001072 if (consumers.size() == 0 && !hasDeferredConsumer) {
1073 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1074 return BAD_VALUE;
1075 }
Zhijun He5d677d12016-05-29 16:52:39 -07001076
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001078 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1079 return BAD_VALUE;
1080 }
1081
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001082 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1083 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1084 // be found in only one sensor pixel mode.
1085 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1086 return BAD_VALUE;
1087 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001088 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001089 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001090 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001091 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001092 if (blobBufferSize <= 0) {
1093 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1094 return BAD_VALUE;
1095 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001096 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1097 blobBufferSize = width * height;
1098 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001099 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001100 if (blobBufferSize <= 0) {
1101 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1102 return BAD_VALUE;
1103 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001104 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001105 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001106 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001107 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001108 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001109 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001110 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001111 bool maxResolution =
1112 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1113 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001114 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1115 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001116 if (rawOpaqueBufferSize <= 0) {
1117 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1118 return BAD_VALUE;
1119 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001120 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001121 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001122 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001123 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001124 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001125 } else if (isShared) {
1126 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1127 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001128 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001129 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001130 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001131 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001132 newStream = new Camera3OutputStream(mNextStreamId,
1133 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001134 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001135 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001136 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001138 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001139 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001140 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001141 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001142 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 }
Emilian Peev40ead602017-09-26 15:46:36 +01001144
1145 size_t consumerCount = consumers.size();
1146 for (size_t i = 0; i < consumerCount; i++) {
1147 int id = newStream->getSurfaceId(consumers[i]);
1148 if (id < 0) {
1149 SET_ERR_L("Invalid surface id");
1150 return BAD_VALUE;
1151 }
1152 if (surfaceIds != nullptr) {
1153 surfaceIds->push_back(id);
1154 }
1155 }
1156
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001157 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158
Emilian Peev08dd2452017-04-06 16:55:14 +01001159 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001160
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001161 newStream->setImageDumpMask(mImageDumpMask);
1162
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163 res = mOutputStreams.add(mNextStreamId, newStream);
1164 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001165 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001166 return res;
1167 }
1168
Shuzhen Wang316781a2020-08-18 18:11:01 -07001169 mSessionStatsBuilder.addStream(mNextStreamId);
1170
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001172 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173
1174 // Continue captures if active at start
1175 if (wasActive) {
1176 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001177 // Reuse current operating mode and session parameters for new stream config
1178 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001179 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1181 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001182 return res;
1183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001185 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001186 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001188}
1189
Emilian Peev710c1422017-08-30 11:19:38 +01001190status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001191 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001192 if (nullptr == streamInfo) {
1193 return BAD_VALUE;
1194 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001196 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001197
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 switch (mStatus) {
1199 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001200 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 return INVALID_OPERATION;
1202 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001203 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001204 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001205 case STATUS_UNCONFIGURED:
1206 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001207 case STATUS_ACTIVE:
1208 // OK
1209 break;
1210 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001211 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 return INVALID_OPERATION;
1213 }
1214
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001215 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1216 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001217 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001218 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 }
1220
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001221 streamInfo->width = stream->getWidth();
1222 streamInfo->height = stream->getHeight();
1223 streamInfo->format = stream->getFormat();
1224 streamInfo->dataSpace = stream->getDataSpace();
1225 streamInfo->formatOverridden = stream->isFormatOverridden();
1226 streamInfo->originalFormat = stream->getOriginalFormat();
1227 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1228 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001229 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001231}
1232
1233status_t Camera3Device::setStreamTransform(int id,
1234 int transform) {
1235 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001236 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 switch (mStatus) {
1240 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001244 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 case STATUS_UNCONFIGURED:
1247 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 case STATUS_ACTIVE:
1249 // OK
1250 break;
1251 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001252 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 return INVALID_OPERATION;
1254 }
1255
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001256 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1257 if (stream == nullptr) {
1258 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return BAD_VALUE;
1260 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001261 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001262}
1263
1264status_t Camera3Device::deleteStream(int id) {
1265 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 Mutex::Autolock l(mLock);
1268 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001269
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001270 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001271
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 // CameraDevice semantics require device to already be idle before
1273 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001275 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001276 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 }
1278
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001279 if (mStatus == STATUS_ERROR) {
1280 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1281 __FUNCTION__, mId.string());
1282 return -EBUSY;
1283 }
1284
Igor Murashkin2fba5842013-04-22 14:03:54 -07001285 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001286 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 if (mInputStream != NULL && id == mInputStream->getId()) {
1288 deletedStream = mInputStream;
1289 mInputStream.clear();
1290 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001291 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001292 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 return BAD_VALUE;
1294 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001295 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001296 }
1297
1298 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001299 if (stream != nullptr) {
1300 deletedStream = stream;
1301 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001302 }
1303
1304 // Free up the stream endpoint so that it can be used by some other stream
1305 res = deletedStream->disconnect();
1306 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001307 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001308 // fall through since we want to still list the stream as deleted.
1309 }
1310 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001311 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001312
1313 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001314}
1315
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001316status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001317 ATRACE_CALL();
1318 ALOGV("%s: E", __FUNCTION__);
1319
1320 Mutex::Autolock il(mInterfaceLock);
1321 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001322
Emilian Peev811d2952018-05-25 11:08:40 +01001323 // In case the client doesn't include any session parameter, try a
1324 // speculative configuration using the values from the last cached
1325 // default request.
1326 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001327 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001328 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1329 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1330 mLastTemplateId);
1331 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1332 operatingMode);
1333 }
1334
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001335 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1336}
1337
1338status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1339 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001340 //Filter out any incoming session parameters
1341 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001342 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1343 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001344 CameraMetadata filteredParams(availableSessionKeys.count);
1345 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1346 filteredParams.getAndLock());
1347 set_camera_metadata_vendor_id(meta, mVendorTagId);
1348 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001349 if (availableSessionKeys.count > 0) {
1350 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1351 camera_metadata_ro_entry entry = params.find(
1352 availableSessionKeys.data.i32[i]);
1353 if (entry.count > 0) {
1354 filteredParams.update(entry);
1355 }
1356 }
1357 }
1358
1359 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001360}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001361
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001362status_t Camera3Device::getInputBufferProducer(
1363 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001364 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001365 Mutex::Autolock il(mInterfaceLock);
1366 Mutex::Autolock l(mLock);
1367
1368 if (producer == NULL) {
1369 return BAD_VALUE;
1370 } else if (mInputStream == NULL) {
1371 return INVALID_OPERATION;
1372 }
1373
1374 return mInputStream->getInputBufferProducer(producer);
1375}
1376
Emilian Peevf4816702020-04-03 15:44:51 -07001377status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001378 CameraMetadata *request) {
1379 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001380 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001381
Emilian Peevf4816702020-04-03 15:44:51 -07001382 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001383 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001384 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001385 return BAD_VALUE;
1386 }
1387
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001388 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001390 {
1391 Mutex::Autolock l(mLock);
1392 switch (mStatus) {
1393 case STATUS_ERROR:
1394 CLOGE("Device has encountered a serious error");
1395 return INVALID_OPERATION;
1396 case STATUS_UNINITIALIZED:
1397 CLOGE("Device is not initialized!");
1398 return INVALID_OPERATION;
1399 case STATUS_UNCONFIGURED:
1400 case STATUS_CONFIGURED:
1401 case STATUS_ACTIVE:
1402 // OK
1403 break;
1404 default:
1405 SET_ERR_L("Unexpected status: %d", mStatus);
1406 return INVALID_OPERATION;
1407 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001408
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001409 if (!mRequestTemplateCache[templateId].isEmpty()) {
1410 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001411 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001412 return OK;
1413 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001414 }
1415
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416 camera_metadata_t *rawRequest;
1417 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001418 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001419
1420 {
1421 Mutex::Autolock l(mLock);
1422 if (res == BAD_VALUE) {
1423 ALOGI("%s: template %d is not supported on this camera device",
1424 __FUNCTION__, templateId);
1425 return res;
1426 } else if (res != OK) {
1427 CLOGE("Unable to construct request template %d: %s (%d)",
1428 templateId, strerror(-res), res);
1429 return res;
1430 }
1431
1432 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1433 mRequestTemplateCache[templateId].acquire(rawRequest);
1434
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001435 // Override the template request with zoomRatioMapper
1436 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1437 &mRequestTemplateCache[templateId]);
1438 if (res != OK) {
1439 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1440 templateId, strerror(-res), res);
1441 return res;
1442 }
1443
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001444 // Fill in JPEG_QUALITY if not available
1445 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1446 static const uint8_t kDefaultJpegQuality = 95;
1447 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1448 &kDefaultJpegQuality, 1);
1449 }
1450
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001451 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001452 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001453 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454 return OK;
1455}
1456
1457status_t Camera3Device::waitUntilDrained() {
1458 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001459 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001460 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001462
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001463 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001464}
1465
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001466status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 switch (mStatus) {
1468 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 ALOGV("%s: Already idle", __FUNCTION__);
1471 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001472 case STATUS_CONFIGURED:
1473 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 case STATUS_ERROR:
1475 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001476 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 break;
1478 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return INVALID_OPERATION;
1481 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001482 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1483 maxExpectedDuration);
1484 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001485 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001486 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001487 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1488 res);
1489 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001490 return res;
1491}
1492
Ruben Brunk183f0562015-08-12 12:55:02 -07001493void Camera3Device::internalUpdateStatusLocked(Status status) {
1494 mStatus = status;
1495 mRecentStatusUpdates.add(mStatus);
1496 mStatusChanged.broadcast();
1497}
1498
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001500status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001501 if (mRequestThread.get() != nullptr) {
1502 mRequestThread->setPaused(true);
1503 } else {
1504 return NO_INIT;
1505 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001507 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1508 maxExpectedDuration);
1509 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001510 if (res != OK) {
1511 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001512 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 }
1514
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 return res;
1516}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001518// Resume after internalPauseAndWaitLocked
1519status_t Camera3Device::internalResumeLocked() {
1520 status_t res;
1521
1522 mRequestThread->setPaused(false);
1523
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001524 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1525 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1527 if (res != OK) {
1528 SET_ERR_L("Can't transition to active in %f seconds!",
1529 kActiveTimeout/1e9);
1530 }
1531 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533}
1534
Ruben Brunk183f0562015-08-12 12:55:02 -07001535status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001537
1538 size_t startIndex = 0;
1539 if (mStatusWaiters == 0) {
1540 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1541 // this status list
1542 mRecentStatusUpdates.clear();
1543 } else {
1544 // If other threads are waiting on updates to this status list, set the position of the
1545 // first element that this list will check rather than clearing the list.
1546 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 }
1548
Ruben Brunk183f0562015-08-12 12:55:02 -07001549 mStatusWaiters++;
1550
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001551 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001552 if (!active && mUseHalBufManager) {
1553 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001554 if (mStatus == STATUS_ACTIVE) {
1555 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001556 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001557 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001558 mRequestBufferSM.onWaitUntilIdle();
1559 }
1560
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 bool stateSeen = false;
1562 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001563 if (active == (mStatus == STATUS_ACTIVE)) {
1564 // Desired state is current
1565 break;
1566 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567
1568 res = mStatusChanged.waitRelative(mLock, timeout);
1569 if (res != OK) break;
1570
Ruben Brunk183f0562015-08-12 12:55:02 -07001571 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1572 // transitions.
1573 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1574 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1575 __FUNCTION__);
1576
1577 // Encountered desired state since we began waiting
1578 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1580 stateSeen = true;
1581 break;
1582 }
1583 }
1584 } while (!stateSeen);
1585
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001586 if (signalPipelineDrain) {
1587 mRequestThread->resetPipelineDrain();
1588 }
1589
Ruben Brunk183f0562015-08-12 12:55:02 -07001590 mStatusWaiters--;
1591
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 return res;
1593}
1594
1595
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001596status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001598 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001600 if (listener != NULL && mListener != NULL) {
1601 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1602 }
1603 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001604 mRequestThread->setNotificationListener(listener);
1605 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001606
1607 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608}
1609
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001610bool Camera3Device::willNotify3A() {
1611 return false;
1612}
1613
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001614status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001615 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001616 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001617
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001618 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001619 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1620 if (st == std::cv_status::timeout) {
1621 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001622 }
1623 }
1624 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001625}
1626
Jianing Weicb0652e2014-03-12 18:29:36 -07001627status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001629 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001631 if (mResultQueue.empty()) {
1632 return NOT_ENOUGH_DATA;
1633 }
1634
Jianing Weicb0652e2014-03-12 18:29:36 -07001635 if (frame == NULL) {
1636 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1637 return BAD_VALUE;
1638 }
1639
1640 CaptureResult &result = *(mResultQueue.begin());
1641 frame->mResultExtras = result.mResultExtras;
1642 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001643 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001644 mResultQueue.erase(mResultQueue.begin());
1645
1646 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647}
1648
1649status_t Camera3Device::triggerAutofocus(uint32_t id) {
1650 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001653 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1654 // Mix-in this trigger into the next request and only the next request.
1655 RequestTrigger trigger[] = {
1656 {
1657 ANDROID_CONTROL_AF_TRIGGER,
1658 ANDROID_CONTROL_AF_TRIGGER_START
1659 },
1660 {
1661 ANDROID_CONTROL_AF_TRIGGER_ID,
1662 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001663 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001664 };
1665
1666 return mRequestThread->queueTrigger(trigger,
1667 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668}
1669
1670status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1671 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001674 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1675 // Mix-in this trigger into the next request and only the next request.
1676 RequestTrigger trigger[] = {
1677 {
1678 ANDROID_CONTROL_AF_TRIGGER,
1679 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1680 },
1681 {
1682 ANDROID_CONTROL_AF_TRIGGER_ID,
1683 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001684 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001685 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 return mRequestThread->queueTrigger(trigger,
1688 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689}
1690
1691status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1692 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001693 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001695 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1696 // Mix-in this trigger into the next request and only the next request.
1697 RequestTrigger trigger[] = {
1698 {
1699 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1700 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1701 },
1702 {
1703 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1704 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001705 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001706 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001708 return mRequestThread->queueTrigger(trigger,
1709 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001710}
1711
Jianing Weicb0652e2014-03-12 18:29:36 -07001712status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001713 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001714 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001715 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001716
Zhijun He7ef20392014-04-21 16:04:17 -07001717 {
1718 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001719
1720 // b/116514106 "disconnect()" can get called twice for the same device. The
1721 // camera device will not be initialized during the second run.
1722 if (mStatus == STATUS_UNINITIALIZED) {
1723 return OK;
1724 }
1725
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001726 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001727
1728 // Stop session and stream counter
1729 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001730 }
1731
Ravneetdbd5b242022-03-02 07:22:46 +00001732 // Calculate expected duration for flush with additional buffer time in ms for watchdog
1733 uint64_t maxExpectedDuration = (getExpectedInFlightDuration() + kBaseGetBufferWait) / 1e6;
1734 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1735 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1736
1737 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001738}
1739
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001740status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001741 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1742}
1743
1744status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001745 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001746 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001747 Mutex::Autolock il(mInterfaceLock);
1748 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001749
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001750 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1751 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001752 CLOGE("Stream %d does not exist", streamId);
1753 return BAD_VALUE;
1754 }
1755
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001756 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001757 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001758 return BAD_VALUE;
1759 }
1760
1761 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001762 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001763 return BAD_VALUE;
1764 }
1765
Ruben Brunkc78ac262015-08-13 17:58:46 -07001766 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001767}
1768
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001769status_t Camera3Device::tearDown(int streamId) {
1770 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001771 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001772 Mutex::Autolock il(mInterfaceLock);
1773 Mutex::Autolock l(mLock);
1774
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001775 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1776 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001777 CLOGE("Stream %d does not exist", streamId);
1778 return BAD_VALUE;
1779 }
1780
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001781 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1782 CLOGE("Stream %d is a target of a in-progress request", streamId);
1783 return BAD_VALUE;
1784 }
1785
1786 return stream->tearDown();
1787}
1788
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001789status_t Camera3Device::addBufferListenerForStream(int streamId,
1790 wp<Camera3StreamBufferListener> listener) {
1791 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001792 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001793 Mutex::Autolock il(mInterfaceLock);
1794 Mutex::Autolock l(mLock);
1795
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001796 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1797 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001798 CLOGE("Stream %d does not exist", streamId);
1799 return BAD_VALUE;
1800 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001801 stream->addBufferListener(listener);
1802
1803 return OK;
1804}
1805
Austin Borger4a870a32022-02-25 01:48:41 +00001806float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1807 camera_metadata_entry minDurations =
1808 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1809 for (size_t i = 0; i < minDurations.count; i += 4) {
1810 if (minDurations.data.i64[i] == stream->getFormat()
1811 && minDurations.data.i64[i+1] == stream->getWidth()
1812 && minDurations.data.i64[i+2] == stream->getHeight()) {
1813 int64_t minFrameDuration = minDurations.data.i64[i+3];
1814 return 1e9f / minFrameDuration;
1815 }
1816 }
1817 return 0.0f;
1818}
1819
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 * Methods called by subclasses
1822 */
1823
1824void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001825 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001826 std::vector<int> streamIds;
1827 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001828 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001829
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001830 {
1831 // Need mLock to safely update state and synchronize to current
1832 // state of methods in flight.
1833 Mutex::Autolock l(mLock);
1834 // We can get various system-idle notices from the status tracker
1835 // while starting up. Only care about them if we've actually sent
1836 // in some requests recently.
1837 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1838 return;
1839 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001840 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1841 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001842 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843
1844 // Skip notifying listener if we're doing some user-transparent
1845 // state changes
1846 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001847
Austin Borger4a870a32022-02-25 01:48:41 +00001848 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1849 auto stream = mOutputStreams[i];
1850 if (stream.get() == nullptr) continue;
1851
1852 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1853 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1854
1855 // Populate stream statistics in case of Idle
1856 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001857 streamIds.push_back(stream->getId());
1858 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1859 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001860 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001861 if (camera3Stream != nullptr) {
1862 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001863 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001864 }
1865 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001866 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001867 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001868 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001869 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001870 }
1871 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001873
1874 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001876 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001877 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001879 status_t res = OK;
1880 if (listener != nullptr) {
1881 if (idle) {
1882 // Get session stats from the builder, and notify the listener.
1883 int64_t requestCount, resultErrorCount;
1884 bool deviceError;
1885 std::map<int, StreamStats> streamStatsMap;
1886 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1887 &deviceError, &streamStatsMap);
1888 for (size_t i = 0; i < streamIds.size(); i++) {
1889 int streamId = streamIds[i];
1890 auto stats = streamStatsMap.find(streamId);
1891 if (stats != streamStatsMap.end()) {
1892 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1893 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1894 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1895 streamStats[i].mHistogramType =
1896 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1897 streamStats[i].mHistogramBins.assign(
1898 stats->second.mCaptureLatencyBins.begin(),
1899 stats->second.mCaptureLatencyBins.end());
1900 streamStats[i].mHistogramCounts.assign(
1901 stats->second.mCaptureLatencyHistogram.begin(),
1902 stats->second.mCaptureLatencyHistogram.end());
1903 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001904 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001905 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1906 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001907 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001908 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001909 }
1910 if (res != OK) {
1911 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1912 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001913 }
1914}
1915
Shuzhen Wang758c2152017-01-10 18:26:18 -08001916status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001917 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001918 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001919 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1920 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001921
1922 if (surfaceIds == nullptr) {
1923 return BAD_VALUE;
1924 }
1925
Zhijun He5d677d12016-05-29 16:52:39 -07001926 Mutex::Autolock il(mInterfaceLock);
1927 Mutex::Autolock l(mLock);
1928
Shuzhen Wang758c2152017-01-10 18:26:18 -08001929 if (consumers.size() == 0) {
1930 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001931 return BAD_VALUE;
1932 }
1933
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001934 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1935 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001936 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001937 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001938 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001939
1940 // isConsumerConfigurationDeferred will be off after setConsumers
1941 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001942 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001943 if (res != OK) {
1944 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1945 return res;
1946 }
1947
Emilian Peev40ead602017-09-26 15:46:36 +01001948 for (auto &consumer : consumers) {
1949 int id = stream->getSurfaceId(consumer);
1950 if (id < 0) {
1951 CLOGE("Invalid surface id!");
1952 return BAD_VALUE;
1953 }
1954 surfaceIds->push_back(id);
1955 }
1956
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001957 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001958 if (!stream->isConfiguring()) {
1959 CLOGE("Stream %d was already fully configured.", streamId);
1960 return INVALID_OPERATION;
1961 }
Zhijun He5d677d12016-05-29 16:52:39 -07001962
Shuzhen Wang0129d522016-10-30 22:43:41 -07001963 res = stream->finishConfiguration();
1964 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001965 // If finishConfiguration fails due to abandoned surface, do not set
1966 // device to error state.
1967 bool isSurfaceAbandoned =
1968 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1969 if (!isSurfaceAbandoned) {
1970 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1971 stream->getId(), strerror(-res), res);
1972 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001973 return res;
1974 }
Zhijun He5d677d12016-05-29 16:52:39 -07001975 }
1976
1977 return OK;
1978}
1979
Emilian Peev40ead602017-09-26 15:46:36 +01001980status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1981 const std::vector<OutputStreamInfo> &outputInfo,
1982 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1983 Mutex::Autolock il(mInterfaceLock);
1984 Mutex::Autolock l(mLock);
1985
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001986 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1987 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001988 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001989 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001990 }
1991
1992 for (const auto &it : removedSurfaceIds) {
1993 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1994 CLOGE("Shared surface still part of a pending request!");
1995 return -EBUSY;
1996 }
1997 }
1998
Emilian Peev40ead602017-09-26 15:46:36 +01001999 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2000 if (res != OK) {
2001 CLOGE("Stream %d failed to update stream (error %d %s) ",
2002 streamId, res, strerror(-res));
2003 if (res == UNKNOWN_ERROR) {
2004 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2005 __FUNCTION__);
2006 }
2007 return res;
2008 }
2009
2010 return res;
2011}
2012
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002013status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2014 Mutex::Autolock il(mInterfaceLock);
2015 Mutex::Autolock l(mLock);
2016
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002017 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2018 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002019 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2020 return BAD_VALUE;
2021 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002022
2023 if (dropping) {
2024 mSessionStatsBuilder.stopCounter(streamId);
2025 } else {
2026 mSessionStatsBuilder.startCounter(streamId);
2027 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002028 return stream->dropBuffers(dropping);
2029}
2030
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002032 * Camera3Device private methods
2033 */
2034
2035sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002036 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002037 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002038
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002039 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002040 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002041
2042 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002043 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002044 if (inputStreams.count > 0) {
2045 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002046 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002047 CLOGE("Request references unknown input stream %d",
2048 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049 return NULL;
2050 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002051
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002053 SET_ERR_L("%s: input stream %d is not configured!",
2054 __FUNCTION__, mInputStream->getId());
2055 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002056 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002057 // Check if stream prepare is blocking requests.
2058 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002059 CLOGE("Request references an input stream that's being prepared!");
2060 return NULL;
2061 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062
2063 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002064 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065 }
2066
2067 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002068 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002069 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002070 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return NULL;
2072 }
2073
2074 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002075 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2076 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002077 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002078 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 return NULL;
2080 }
Zhijun He5d677d12016-05-29 16:52:39 -07002081 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002082 auto iter = surfaceMap.find(streams.data.i32[i]);
2083 if (iter != surfaceMap.end()) {
2084 const std::vector<size_t>& surfaces = iter->second;
2085 for (const auto& surface : surfaces) {
2086 if (stream->isConsumerConfigurationDeferred(surface)) {
2087 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2088 "due to deferred consumer", stream->getId(), surface);
2089 return NULL;
2090 }
2091 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002092 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002093 }
2094
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002095 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002096 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2097 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002098 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002099 // Check if stream prepare is blocking requests.
2100 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002101 CLOGE("Request references an output stream that's being prepared!");
2102 return NULL;
2103 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104
2105 newRequest->mOutputStreams.push(stream);
2106 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002107 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002108 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002110 auto rotateAndCropEntry =
2111 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2112 if (rotateAndCropEntry.count > 0 &&
2113 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2114 newRequest->mRotateAndCropAuto = true;
2115 } else {
2116 newRequest->mRotateAndCropAuto = false;
2117 }
2118
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002119 auto zoomRatioEntry =
2120 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2121 if (zoomRatioEntry.count > 0 &&
2122 zoomRatioEntry.data.f[0] == 1.0f) {
2123 newRequest->mZoomRatioIs1x = true;
2124 } else {
2125 newRequest->mZoomRatioIs1x = false;
2126 }
2127
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002128 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002129 for (auto& settings : newRequest->mSettingsList) {
2130 auto testPatternModeEntry =
2131 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2132 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2133 testPatternModeEntry.data.i32[0] :
2134 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002135
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002136 auto testPatternDataEntry =
2137 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2138 if (testPatternDataEntry.count >= 4) {
2139 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2140 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2141 } else {
2142 settings.mOriginalTestPatternData[0] = 0;
2143 settings.mOriginalTestPatternData[1] = 0;
2144 settings.mOriginalTestPatternData[2] = 0;
2145 settings.mOriginalTestPatternData[3] = 0;
2146 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002147 }
2148 }
2149
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002151}
2152
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002153void Camera3Device::cancelStreamsConfigurationLocked() {
2154 int res = OK;
2155 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2156 res = mInputStream->cancelConfiguration();
2157 if (res != OK) {
2158 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2159 mInputStream->getId(), strerror(-res), res);
2160 }
2161 }
2162
2163 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002164 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002165 if (outputStream->isConfiguring()) {
2166 res = outputStream->cancelConfiguration();
2167 if (res != OK) {
2168 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2169 outputStream->getId(), strerror(-res), res);
2170 }
2171 }
2172 }
2173
2174 // Return state to that at start of call, so that future configures
2175 // properly clean things up
2176 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2177 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002178
2179 res = mPreparerThread->resume();
2180 if (res != OK) {
2181 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2182 }
2183}
2184
Emilian Peev0d0191e2020-04-21 17:01:18 -07002185bool Camera3Device::checkAbandonedStreamsLocked() {
2186 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2187 return true;
2188 }
2189
2190 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2191 auto stream = mOutputStreams[i];
2192 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2193 return true;
2194 }
2195 }
2196
2197 return false;
2198}
2199
Emilian Peev3bead5f2020-05-28 17:29:08 -07002200bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002201 ATRACE_CALL();
2202 bool ret = false;
2203
Shuzhen Wang316781a2020-08-18 18:11:01 -07002204 nsecs_t startTime = systemTime();
2205
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002206 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002207 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2208
2209 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002210 if (checkAbandonedStreamsLocked()) {
2211 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2212 __FUNCTION__);
2213 return true;
2214 }
2215
Emilian Peev3bead5f2020-05-28 17:29:08 -07002216 status_t rc = NO_ERROR;
2217 bool markClientActive = false;
2218 if (mStatus == STATUS_ACTIVE) {
2219 markClientActive = true;
2220 mPauseStateNotify = true;
2221 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2222
2223 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2224 }
2225
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002226 if (rc == NO_ERROR) {
2227 mNeedConfig = true;
2228 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2229 if (rc == NO_ERROR) {
2230 ret = true;
2231 mPauseStateNotify = false;
2232 //Moving to active state while holding 'mLock' is important.
2233 //There could be pending calls to 'create-/deleteStream' which
2234 //will trigger another stream configuration while the already
2235 //present streams end up with outstanding buffers that will
2236 //not get drained.
2237 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002238 } else if (rc == DEAD_OBJECT) {
2239 // DEAD_OBJECT can be returned if either the consumer surface is
2240 // abandoned, or the HAL has died.
2241 // - If the HAL has died, configureStreamsLocked call will set
2242 // device to error state,
2243 // - If surface is abandoned, we should not set device to error
2244 // state.
2245 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002246 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002247 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002248 }
2249 } else {
2250 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2251 }
2252
Shuzhen Wang316781a2020-08-18 18:11:01 -07002253 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2254 ns2ms(systemTime() - startTime));
2255
Emilian Peev3bead5f2020-05-28 17:29:08 -07002256 if (markClientActive) {
2257 mStatusTracker->markComponentActive(clientStatusId);
2258 }
2259
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002260 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002261}
2262
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002263status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002264 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 ATRACE_CALL();
2266 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002268 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002269 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270 return INVALID_OPERATION;
2271 }
2272
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002273 if (operatingMode < 0) {
2274 CLOGE("Invalid operating mode: %d", operatingMode);
2275 return BAD_VALUE;
2276 }
2277
2278 bool isConstrainedHighSpeed =
2279 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2280 operatingMode;
2281
2282 if (mOperatingMode != operatingMode) {
2283 mNeedConfig = true;
2284 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2285 mOperatingMode = operatingMode;
2286 }
2287
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002288 // In case called from configureStreams, abort queued input buffers not belonging to
2289 // any pending requests.
2290 if (mInputStream != NULL && notifyRequestThread) {
2291 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002292 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002293 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002294 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002295 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002296 if (res != OK) {
2297 // Exhausted acquiring all input buffers.
2298 break;
2299 }
2300
Emilian Peevf4816702020-04-03 15:44:51 -07002301 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002302 res = mInputStream->returnInputBuffer(inputBuffer);
2303 if (res != OK) {
2304 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2305 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2306 }
2307 }
2308 }
2309
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002310 if (!mNeedConfig) {
2311 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2312 return OK;
2313 }
2314
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002315 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002316 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002317 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2318 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002319 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002320 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002321 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002322 }
2323
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002324 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002325 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002327 mPreparerThread->pause();
2328
Emilian Peevf4816702020-04-03 15:44:51 -07002329 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002330 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002332 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333
Emilian Peevf4816702020-04-03 15:44:51 -07002334 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002335 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002336 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002337
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002338
2339 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002340 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002341 inputStream = mInputStream->startConfiguration();
2342 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002343 CLOGE("Can't start input stream configuration");
2344 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345 return INVALID_OPERATION;
2346 }
2347 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002348
2349 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 }
2351
Shuzhen Wang99080502021-03-07 21:08:20 -08002352 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002353 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002355
2356 // Don't configure bidi streams twice, nor add them twice to the list
2357 if (mOutputStreams[i].get() ==
2358 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2359
2360 config.num_streams--;
2361 continue;
2362 }
2363
Emilian Peevf4816702020-04-03 15:44:51 -07002364 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002365 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002367 CLOGE("Can't start output stream configuration");
2368 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 return INVALID_OPERATION;
2370 }
2371 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002372
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002373 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002374 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2375 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002376 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2377 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002378 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2379 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002380 } else if (outputStream->data_space ==
2381 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2382 bufferSizes[k] = outputStream->width * outputStream->height;
2383 } else {
2384 ALOGW("%s: Blob dataSpace %d not supported",
2385 __FUNCTION__, outputStream->data_space);
2386 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002387 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002388
2389 if (mOutputStreams[i]->isMultiResolution()) {
2390 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2391 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2392 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2393 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002394
2395 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2396 composerSurfacePresent = true;
2397 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398 }
2399
2400 config.streams = streams.editArray();
2401
2402 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002403 // max_buffers, usage, and priv fields, as well as data_space and format
2404 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002405
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002406 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002407 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002408 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002409
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002410 if (res == BAD_VALUE) {
2411 // HAL rejected this set of streams as unsupported, clean up config
2412 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002413 CLOGE("Set of requested inputs/outputs not supported by HAL");
2414 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002415 return BAD_VALUE;
2416 } else if (res != OK) {
2417 // Some other kind of error from configure_streams - this is not
2418 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002419 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2420 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002421 return res;
2422 }
2423
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002424 // Finish all stream configuration immediately.
2425 // TODO: Try to relax this later back to lazy completion, which should be
2426 // faster
2427
Igor Murashkin073f8572013-05-02 14:59:28 -07002428 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002429 bool streamReConfigured = false;
2430 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002431 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002432 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002433 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002434 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002435 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2436 return DEAD_OBJECT;
2437 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002438 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002439 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002440 if (streamReConfigured) {
2441 mInterface->onStreamReConfigured(mInputStream->getId());
2442 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002443 }
2444
2445 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002446 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002447 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002448 bool streamReConfigured = false;
2449 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002450 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002451 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002452 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002453 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002454 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2455 return DEAD_OBJECT;
2456 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002458 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002459 if (streamReConfigured) {
2460 mInterface->onStreamReConfigured(outputStream->getId());
2461 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002462 }
2463 }
2464
Emilian Peeve23f1d92021-09-20 14:56:01 -07002465 mRequestThread->setComposerSurface(composerSurfacePresent);
2466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002467 // Request thread needs to know to avoid using repeat-last-settings protocol
2468 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002469 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002470 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2471 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002472 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002473
Zhijun He90f7c372016-08-16 16:19:43 -07002474 char value[PROPERTY_VALUE_MAX];
2475 property_get("camera.fifo.disable", value, "0");
2476 int32_t disableFifo = atoi(value);
2477 if (disableFifo != 1) {
2478 // Boost priority of request thread to SCHED_FIFO.
2479 pid_t requestThreadTid = mRequestThread->getTid();
2480 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002481 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002482 if (res != OK) {
2483 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2484 strerror(-res), res);
2485 } else {
2486 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2487 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002488 }
2489
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002490 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002491 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2492 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2493 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2494 sessionParams.unlock(newSessionParams);
2495 mSessionParams.unlock(currentSessionParams);
2496 if (updateSessionParams) {
2497 mSessionParams = sessionParams;
2498 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002499
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002500 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002501
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002502 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002503 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002505 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002506
Zhijun He0a210512014-07-24 13:45:15 -07002507 // tear down the deleted streams after configure streams.
2508 mDeletedStreams.clear();
2509
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002510 auto rc = mPreparerThread->resume();
2511 if (rc != OK) {
2512 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2513 return rc;
2514 }
2515
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002516 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002517 mRequestBufferSM.onStreamsConfigured();
2518 }
2519
Cliff Wu3b268182021-07-06 15:44:43 +08002520 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002521 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002522 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002523 // configure the injection streams.
2524 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002525 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002526 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2527 res = mInjectionMethods->injectCamera(config, bufferSizes);
2528 if (res != OK) {
2529 ALOGE("Can't finish inject camera process!");
2530 return res;
2531 }
Cliff Wu3b268182021-07-06 15:44:43 +08002532 } else {
2533 // First run configureStreamsLocked() and then call injectCamera() case:
2534 // If the stream configuration has been completed and camera deive is active, but the
2535 // injection camera has not been injected yet, we need to store the stream configuration of
2536 // the internal camera (because the stream configuration of the injection camera is based
2537 // on the internal camera). When injecting occurs later, this configuration can be used by
2538 // the injection camera.
2539 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2540 " injection camera has not been injected yet.", __FUNCTION__);
2541 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002542 }
2543
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002545}
2546
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002547status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548 ATRACE_CALL();
2549 status_t res;
2550
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 if (mFakeStreamId != NO_STREAM) {
2552 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002553 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002554 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002555 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 return INVALID_OPERATION;
2557 }
2558
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002559 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002560
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002561 sp<Camera3OutputStreamInterface> fakeStream =
2562 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002563
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002564 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002565 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002566 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002567 return res;
2568 }
2569
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002570 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002571 mNextStreamId++;
2572
2573 return OK;
2574}
2575
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002576status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002577 ATRACE_CALL();
2578 status_t res;
2579
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002580 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002581 if (mOutputStreams.size() == 1) return OK;
2582
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002583 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002585 // Ok, have a fake stream and there's at least one other output stream,
2586 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002587
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002588 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002590 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002591 return INVALID_OPERATION;
2592 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002593 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002594
2595 // Free up the stream endpoint so that it can be used by some other stream
2596 res = deletedStream->disconnect();
2597 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002598 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002599 // fall through since we want to still list the stream as deleted.
2600 }
2601 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002602 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002603
2604 return res;
2605}
2606
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002607void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002608 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002609 Mutex::Autolock l(mLock);
2610 va_list args;
2611 va_start(args, fmt);
2612
2613 setErrorStateLockedV(fmt, args);
2614
2615 va_end(args);
2616}
2617
2618void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002619 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002620 Mutex::Autolock l(mLock);
2621 setErrorStateLockedV(fmt, args);
2622}
2623
2624void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2625 va_list args;
2626 va_start(args, fmt);
2627
2628 setErrorStateLockedV(fmt, args);
2629
2630 va_end(args);
2631}
2632
2633void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002634 // Print out all error messages to log
2635 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002636 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002637
2638 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002639 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002640
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002641 mErrorCause = errorCause;
2642
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002643 if (mRequestThread != nullptr) {
2644 mRequestThread->setPaused(true);
2645 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002646 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002647
2648 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002649 sp<NotificationListener> listener = mListener.promote();
2650 if (listener != NULL) {
2651 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002652 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002653 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002654 }
2655
2656 // Save stack trace. View by dumping it later.
2657 CameraTraces::saveTrace();
2658 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002659}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
2661/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002662 * In-flight request management
2663 */
2664
Jianing Weicb0652e2014-03-12 18:29:36 -07002665status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002666 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002667 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002668 const std::set<std::set<String8>>& physicalCameraIds,
2669 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2670 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002671 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002672 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002673 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002674
2675 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002676 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002677 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002678 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002679 if (res < 0) return res;
2680
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002681 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002682 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2683 // avoid a deadlock during reprocess requests.
2684 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002685 if (mStatusTracker != nullptr) {
2686 mStatusTracker->markComponentActive(mInFlightStatusId);
2687 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002688 }
2689
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002690 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002691 return OK;
2692}
2693
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002694void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002695 // Indicate idle inFlightMap to the status tracker
2696 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002697 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002698 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2699 // avoid a deadlock during reprocess requests.
2700 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002701 if (mStatusTracker != nullptr) {
2702 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2703 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002704 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002705 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002706}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002707
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002708void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002709 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002710 // something has likely gone wrong. This might still be legit only if application send in
2711 // a long burst of long exposure requests.
2712 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2713 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2714 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2715 mInFlightMap.size(), mExpectedInflightDuration);
2716 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2717 kInFlightWarnLimitHighSpeed) {
2718 CLOGW("In-flight list too large for high speed configuration: %zu,"
2719 "total inflight duration %" PRIu64,
2720 mInFlightMap.size(), mExpectedInflightDuration);
2721 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002722 }
2723}
2724
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002725void Camera3Device::onInflightMapFlushedLocked() {
2726 mExpectedInflightDuration = 0;
2727}
2728
2729void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002730 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002731 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2732 mInFlightMap.removeItemsAt(idx, 1);
2733
2734 onInflightEntryRemovedLocked(duration);
2735}
2736
2737
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002738void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002739 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002740 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002741 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002742 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002743 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002744 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002745
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002746 FlushInflightReqStates states {
2747 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002748 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002749
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002750 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002751}
2752
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002753CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002754 ALOGV("%s", __FUNCTION__);
2755
Igor Murashkin1e479c02013-09-06 16:55:14 -07002756 CameraMetadata retVal;
2757
2758 if (mRequestThread != NULL) {
2759 retVal = mRequestThread->getLatestRequest();
2760 }
2761
Igor Murashkin1e479c02013-09-06 16:55:14 -07002762 return retVal;
2763}
2764
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002765void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002766 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002767 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002768 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2769 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002770
2771 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002772 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002773}
2774
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002775void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002776 std::vector<native_handle_t*> *handles, bool closeFd) {
2777 if (handles == nullptr) {
2778 return;
2779 }
2780 if (closeFd) {
2781 for (auto& handle : *handles) {
2782 native_handle_close(handle);
2783 }
2784 }
2785 for (auto& handle : *handles) {
2786 native_handle_delete(handle);
2787 }
2788 handles->clear();
2789 return;
2790}
2791
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002792/**
2793 * HalInterface inner class methods
2794 */
2795
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002796void Camera3Device::HalInterface::getInflightBufferKeys(
2797 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002798 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002799 return;
2800}
2801
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002802void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2803 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002804 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002805 return;
2806}
2807
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002808bool Camera3Device::HalInterface::verifyBufferIds(
2809 int32_t streamId, std::vector<uint64_t>& bufIds) {
2810 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002811}
2812
2813status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002814 int32_t frameNumber, int32_t streamId,
2815 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002816 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002817}
2818
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002819status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002820 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002821 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002822}
2823
2824// Find and pop a buffer_handle_t based on bufferId
2825status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002826 uint64_t bufferId,
2827 /*out*/ buffer_handle_t** buffer,
2828 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002829 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002830}
2831
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002832std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2833 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002834 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002835}
2836
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002837uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2838 const native_handle_t* handle) {
2839 return mBufferRecords.removeOneBufferCache(streamId, handle);
2840}
2841
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002842void Camera3Device::HalInterface::onBufferFreed(
2843 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002844 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2845 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2846 if (bufferId != BUFFER_ID_NO_BUFFER) {
2847 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002848 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002849}
2850
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002851void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002852 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2853 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2854 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002855 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2856 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002857}
2858
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002859/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002860 * RequestThread inner class methods
2861 */
2862
2863Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002864 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002865 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002866 bool useHalBufManager,
2867 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002868 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002869 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002870 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002871 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002872 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002873 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002874 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002875 mReconfigured(false),
2876 mDoPause(false),
2877 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002878 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002879 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002880 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002881 mCurrentAfTriggerId(0),
2882 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002883 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002884 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002885 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002886 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002887 mRepeatingLastFrameNumber(
2888 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002889 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002890 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002891 mRequestLatency(kRequestLatencyBinSize),
2892 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002893 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002894 mUseHalBufManager(useHalBufManager),
2895 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002896 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002897}
2898
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002899Camera3Device::RequestThread::~RequestThread() {}
2900
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002901void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002902 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002903 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002904 Mutex::Autolock l(mRequestLock);
2905 mListener = listener;
2906}
2907
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002908void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002909 const CameraMetadata& sessionParams,
2910 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002911 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002912 Mutex::Autolock l(mRequestLock);
2913 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002914 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002915 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002916 // Prepare video stream for high speed recording.
2917 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002918 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002919}
2920
Jianing Wei90e59c92014-03-12 18:29:36 -07002921status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002922 List<sp<CaptureRequest> > &requests,
2923 /*out*/
2924 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002925 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002926 Mutex::Autolock l(mRequestLock);
2927 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2928 ++it) {
2929 mRequestQueue.push_back(*it);
2930 }
2931
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002932 if (lastFrameNumber != NULL) {
2933 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2934 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2935 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2936 *lastFrameNumber);
2937 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002938
Jianing Wei90e59c92014-03-12 18:29:36 -07002939 unpauseForNewRequests();
2940
2941 return OK;
2942}
2943
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002944
2945status_t Camera3Device::RequestThread::queueTrigger(
2946 RequestTrigger trigger[],
2947 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002948 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002949 Mutex::Autolock l(mTriggerMutex);
2950 status_t ret;
2951
2952 for (size_t i = 0; i < count; ++i) {
2953 ret = queueTriggerLocked(trigger[i]);
2954
2955 if (ret != OK) {
2956 return ret;
2957 }
2958 }
2959
2960 return OK;
2961}
2962
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002963const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2964 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002965 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002966 if (d != nullptr) return d->mId;
2967 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002968}
2969
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002970status_t Camera3Device::RequestThread::queueTriggerLocked(
2971 RequestTrigger trigger) {
2972
2973 uint32_t tag = trigger.metadataTag;
2974 ssize_t index = mTriggerMap.indexOfKey(tag);
2975
2976 switch (trigger.getTagType()) {
2977 case TYPE_BYTE:
2978 // fall-through
2979 case TYPE_INT32:
2980 break;
2981 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002982 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2983 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002984 return INVALID_OPERATION;
2985 }
2986
2987 /**
2988 * Collect only the latest trigger, since we only have 1 field
2989 * in the request settings per trigger tag, and can't send more than 1
2990 * trigger per request.
2991 */
2992 if (index != NAME_NOT_FOUND) {
2993 mTriggerMap.editValueAt(index) = trigger;
2994 } else {
2995 mTriggerMap.add(tag, trigger);
2996 }
2997
2998 return OK;
2999}
3000
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003001status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003002 const RequestList &requests,
3003 /*out*/
3004 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003005 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003006 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003007 if (lastFrameNumber != NULL) {
3008 *lastFrameNumber = mRepeatingLastFrameNumber;
3009 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003010 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003011 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003012 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3013 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003014
3015 unpauseForNewRequests();
3016
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003017 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003018 return OK;
3019}
3020
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003021bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003022 if (mRepeatingRequests.empty()) {
3023 return false;
3024 }
3025 int32_t requestId = requestIn->mResultExtras.requestId;
3026 const RequestList &repeatRequests = mRepeatingRequests;
3027 // All repeating requests are guaranteed to have same id so only check first quest
3028 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3029 return (firstRequest->mResultExtras.requestId == requestId);
3030}
3031
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003032status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003033 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003034 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003035 return clearRepeatingRequestsLocked(lastFrameNumber);
3036
3037}
3038
3039status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003040 std::vector<int32_t> streamIds;
3041 for (const auto& request : mRepeatingRequests) {
3042 for (const auto& stream : request->mOutputStreams) {
3043 streamIds.push_back(stream->getId());
3044 }
3045 }
3046
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003047 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003048 if (lastFrameNumber != NULL) {
3049 *lastFrameNumber = mRepeatingLastFrameNumber;
3050 }
Emilian Peev2295df72021-11-12 18:14:10 -08003051
3052 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3053
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003054 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003055 return OK;
3056}
3057
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003058status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003059 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003061 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003062 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003063
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003064 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003065
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003066 // Send errors for all requests pending in the request queue, including
3067 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003068 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003069 if (listener != NULL) {
3070 for (RequestList::iterator it = mRequestQueue.begin();
3071 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003072 // Abort the input buffers for reprocess requests.
3073 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003074 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003075 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003076 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003077 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003078 if (res != OK) {
3079 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3080 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3081 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003082 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003083 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3084 if (res != OK) {
3085 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3086 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3087 }
3088 }
3089 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003090 // Set the frame number this request would have had, if it
3091 // had been submitted; this frame number will not be reused.
3092 // The requestId and burstId fields were set when the request was
3093 // submitted originally (in convertMetadataListToRequestListLocked)
3094 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003095 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003096 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003097 }
3098 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003099 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003100
3101 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003102 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003103 if (lastFrameNumber != NULL) {
3104 *lastFrameNumber = mRepeatingLastFrameNumber;
3105 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003106 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003107 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003108 return OK;
3109}
3110
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003111status_t Camera3Device::RequestThread::flush() {
3112 ATRACE_CALL();
3113 Mutex::Autolock l(mFlushLock);
3114
Emilian Peev08dd2452017-04-06 16:55:14 +01003115 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003116}
3117
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003118void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003119 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003120 Mutex::Autolock l(mPauseLock);
3121 mDoPause = paused;
3122 mDoPauseSignal.signal();
3123}
3124
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003125status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3126 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003127 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003128 Mutex::Autolock l(mLatestRequestMutex);
3129 status_t res;
3130 while (mLatestRequestId != requestId) {
3131 nsecs_t startTime = systemTime();
3132
3133 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3134 if (res != OK) return res;
3135
3136 timeout -= (systemTime() - startTime);
3137 }
3138
3139 return OK;
3140}
3141
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003142void Camera3Device::RequestThread::requestExit() {
3143 // Call parent to set up shutdown
3144 Thread::requestExit();
3145 // The exit from any possible waits
3146 mDoPauseSignal.signal();
3147 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003148
3149 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3150 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003151}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003152
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003153void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003154 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003155 bool surfaceAbandoned = false;
3156 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003157 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003158 {
3159 Mutex::Autolock l(mRequestLock);
3160 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3161 // repeating requests.
3162 for (const auto& request : mRepeatingRequests) {
3163 for (const auto& s : request->mOutputStreams) {
3164 if (s->isAbandoned()) {
3165 surfaceAbandoned = true;
3166 clearRepeatingRequestsLocked(&lastFrameNumber);
3167 break;
3168 }
3169 }
3170 if (surfaceAbandoned) {
3171 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003172 }
3173 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003174 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003175 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003176
3177 if (listener != NULL && surfaceAbandoned) {
3178 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003179 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003180}
3181
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003182bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003183 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003184 status_t res;
3185 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003186 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003187 uint32_t numRequestProcessed = 0;
3188 for (size_t i = 0; i < batchSize; i++) {
3189 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003190 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003191 }
3192
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003193 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3194
3195 bool triggerRemoveFailed = false;
3196 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3197 for (size_t i = 0; i < numRequestProcessed; i++) {
3198 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3199 nextRequest.submitted = true;
3200
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003201 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003202
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003203 if (!triggerRemoveFailed) {
3204 // Remove any previously queued triggers (after unlock)
3205 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3206 if (removeTriggerRes != OK) {
3207 triggerRemoveFailed = true;
3208 triggerFailedRequest = nextRequest;
3209 }
3210 }
3211 }
3212
3213 if (triggerRemoveFailed) {
3214 SET_ERR("RequestThread: Unable to remove triggers "
3215 "(capture request %d, HAL device: %s (%d)",
3216 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3217 cleanUpFailedRequests(/*sendRequestError*/ false);
3218 return false;
3219 }
3220
3221 if (res != OK) {
3222 // Should only get a failure here for malformed requests or device-level
3223 // errors, so consider all errors fatal. Bad metadata failures should
3224 // come through notify.
3225 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3226 mNextRequests[numRequestProcessed].halRequest.frame_number,
3227 strerror(-res), res);
3228 cleanUpFailedRequests(/*sendRequestError*/ false);
3229 return false;
3230 }
3231 return true;
3232}
3233
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003234nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3235 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3236 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3237 find_camera_metadata_ro_entry(request,
3238 ANDROID_CONTROL_AE_MODE,
3239 &e);
3240 if (e.count == 0) return maxExpectedDuration;
3241
3242 switch (e.data.u8[0]) {
3243 case ANDROID_CONTROL_AE_MODE_OFF:
3244 find_camera_metadata_ro_entry(request,
3245 ANDROID_SENSOR_EXPOSURE_TIME,
3246 &e);
3247 if (e.count > 0) {
3248 maxExpectedDuration = e.data.i64[0];
3249 }
3250 find_camera_metadata_ro_entry(request,
3251 ANDROID_SENSOR_FRAME_DURATION,
3252 &e);
3253 if (e.count > 0) {
3254 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3255 }
3256 break;
3257 default:
3258 find_camera_metadata_ro_entry(request,
3259 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3260 &e);
3261 if (e.count > 1) {
3262 maxExpectedDuration = 1e9 / e.data.u8[0];
3263 }
3264 break;
3265 }
3266
3267 return maxExpectedDuration;
3268}
3269
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003270bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3271 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3272 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3273 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3274 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3275 return true;
3276 }
3277
3278 return false;
3279}
3280
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003281void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3282 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003283 camera_capture_request_t& halRequest = nextRequest.halRequest;
3284 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003285 Mutex::Autolock al(mLatestRequestMutex);
3286
Shuzhen Wang83bff122020-11-20 15:51:39 -08003287 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003288 mLatestRequest.acquire(cloned);
3289
3290 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003291 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3292 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3293 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003294 CameraMetadata(cloned));
3295 }
3296
3297 sp<Camera3Device> parent = mParent.promote();
3298 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003299 int32_t inputStreamId = -1;
3300 if (halRequest.input_buffer != nullptr) {
3301 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3302 }
3303
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003304 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003305 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003306 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3307 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003308 }
3309 }
3310
Shuzhen Wang83bff122020-11-20 15:51:39 -08003311 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003312 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003313 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003314 }
3315
Shuzhen Wang83bff122020-11-20 15:51:39 -08003316 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003317}
3318
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003319bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3320 ATRACE_CALL();
3321 bool updatesDetected = false;
3322
Emilian Peev4ec17882019-01-24 17:16:58 -08003323 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003324 for (auto tag : mSessionParamKeys) {
3325 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003326 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003327
3328 if (entry.count > 0) {
3329 bool isDifferent = false;
3330 if (lastEntry.count > 0) {
3331 // Have a last value, compare to see if changed
3332 if (lastEntry.type == entry.type &&
3333 lastEntry.count == entry.count) {
3334 // Same type and count, compare values
3335 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3336 size_t entryBytes = bytesPerValue * lastEntry.count;
3337 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3338 if (cmp != 0) {
3339 isDifferent = true;
3340 }
3341 } else {
3342 // Count or type has changed
3343 isDifferent = true;
3344 }
3345 } else {
3346 // No last entry, so always consider to be different
3347 isDifferent = true;
3348 }
3349
3350 if (isDifferent) {
3351 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003352 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3353 updatesDetected = true;
3354 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003355 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003356 }
3357 } else if (lastEntry.count > 0) {
3358 // Value has been removed
3359 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003360 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003361 updatesDetected = true;
3362 }
3363 }
3364
Emilian Peev4ec17882019-01-24 17:16:58 -08003365 bool reconfigureRequired;
3366 if (updatesDetected) {
3367 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3368 updatedParams);
3369 mLatestSessionParams = updatedParams;
3370 } else {
3371 reconfigureRequired = false;
3372 }
3373
3374 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003375}
3376
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003377bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003378 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003379 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003380 // Any function called from threadLoop() must not hold mInterfaceLock since
3381 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3382 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003383
3384 // Handle paused state.
3385 if (waitIfPaused()) {
3386 return true;
3387 }
3388
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003389 // Wait for the next batch of requests.
3390 waitForNextRequestBatch();
3391 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003392 return true;
3393 }
3394
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003395 // Get the latest request ID, if any
3396 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003397 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003398 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003399 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003400 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003401 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003402 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3403 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003404 }
3405
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003406 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3407 // or a single request from streaming or burst. In either case the first element
3408 // should contain the latest camera settings that we need to check for any session
3409 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003410 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003411 res = OK;
3412
3413 //Input stream buffers are already acquired at this point so an input stream
3414 //will not be able to move to idle state unless we force it.
3415 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3416 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3417 if (res != OK) {
3418 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3419 cleanUpFailedRequests(/*sendRequestError*/ false);
3420 return false;
3421 }
3422 }
3423
3424 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003425 sp<Camera3Device> parent = mParent.promote();
3426 if (parent != nullptr) {
3427 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003428 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003429 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003430
3431 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3432 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3433 if (res != OK) {
3434 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3435 cleanUpFailedRequests(/*sendRequestError*/ false);
3436 return false;
3437 }
3438 }
3439 }
3440 }
3441
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003442 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003443 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003444 if (res == TIMED_OUT) {
3445 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003446 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003447 // Check if any stream is abandoned.
3448 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003449 return true;
3450 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003451 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003452 return false;
3453 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003454
Zhijun Hecc27e112013-10-03 16:12:43 -07003455 // Inform waitUntilRequestProcessed thread of a new request ID
3456 {
3457 Mutex::Autolock al(mLatestRequestMutex);
3458
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003459 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003460 mLatestRequestSignal.signal();
3461 }
3462
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003463 // Submit a batch of requests to HAL.
3464 // Use flush lock only when submitting multilple requests in a batch.
3465 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3466 // which may take a long time to finish so synchronizing flush() and
3467 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3468 // For now, only synchronize for high speed recording and we should figure something out for
3469 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003470 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003471
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003472 if (useFlushLock) {
3473 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003474 }
3475
Zhijun Hef0645c12016-08-02 00:58:11 -07003476 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003477 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003478
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003479 sp<Camera3Device> parent = mParent.promote();
3480 if (parent != nullptr) {
3481 parent->mRequestBufferSM.onSubmittingRequest();
3482 }
3483
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003484 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003485 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003486 submitRequestSuccess = sendRequestsBatch();
3487
Shuzhen Wang686f6442017-06-20 16:16:04 -07003488 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3489 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003490
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003491 if (useFlushLock) {
3492 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003493 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003494
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003495 // Unset as current request
3496 {
3497 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003498 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003499 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003500 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003501
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003502 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003503}
3504
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003505status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3506 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3507 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3508 ANDROID_SCALER_CROP_REGION_SET};
3509 if (request == nullptr) {
3510 ALOGE("%s request metadata nullptr", __FUNCTION__);
3511 return BAD_VALUE;
3512 }
3513 status_t res = OK;
3514 for (const auto &key : kFwkOnlyRegionKeys) {
3515 if (request->exists(key)) {
3516 res = request->erase(key);
3517 if (res != OK) {
3518 return res;
3519 }
3520 }
3521 }
3522 return OK;
3523}
3524
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003525status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003526 ATRACE_CALL();
3527
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003528 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003529 for (size_t i = 0; i < mNextRequests.size(); i++) {
3530 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003531 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003532 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3533 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003534
3535 // Prepare a request to HAL
3536 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3537
3538 // Insert any queued triggers (before metadata is locked)
3539 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003540 if (res < 0) {
3541 SET_ERR("RequestThread: Unable to insert triggers "
3542 "(capture request %d, HAL device: %s (%d)",
3543 halRequest->frame_number, strerror(-res), res);
3544 return INVALID_OPERATION;
3545 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003546
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003547 int triggerCount = res;
3548 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3549 mPrevTriggers = triggerCount;
3550
Emilian Peeve23f1d92021-09-20 14:56:01 -07003551 // Do not override rotate&crop for stream configurations that include
3552 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3553 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3554 bool rotateAndCropChanged = mComposerOutput ? false :
3555 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003556 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003557
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003558 // If the request is the same as last, or we had triggers now or last time or
3559 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003560 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003561 (mPrevRequest != captureRequest || triggersMixedIn ||
3562 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003563 // Request settings are all the same within one batch, so only treat the first
3564 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003565 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003566 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003567 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003568 /**
3569 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003570 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003571 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003572 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003573 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003574 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003575 "(capture request %d, HAL device: %s (%d)",
3576 halRequest->frame_number, strerror(-res), res);
3577 return INVALID_OPERATION;
3578 }
3579
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003580 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003581 sp<Camera3Device> parent = mParent.promote();
3582 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003583 List<PhysicalCameraSettings>::iterator it;
3584 for (it = captureRequest->mSettingsList.begin();
3585 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003586 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3587 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003588 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3589 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3590 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3591 res);
3592 return INVALID_OPERATION;
3593 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003594 continue;
3595 }
3596
3597 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3598 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3599 updateCaptureRequest(&(it->metadata));
3600 if (res != OK) {
3601 SET_ERR("RequestThread: Unable to correct capture requests "
3602 "for scaler crop region and metering regions for request "
3603 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3604 res);
3605 return INVALID_OPERATION;
3606 }
3607 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003608 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3609 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3610 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3611 res);
3612 return INVALID_OPERATION;
3613 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003614 }
3615 }
3616
3617 // Correct metadata regions for distortion correction if enabled
3618 for (it = captureRequest->mSettingsList.begin();
3619 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003620 if (parent->mDistortionMappers.find(it->cameraId) ==
3621 parent->mDistortionMappers.end()) {
3622 continue;
3623 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003624
3625 if (!captureRequest->mDistortionCorrectionUpdated) {
3626 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3627 &(it->metadata));
3628 if (res != OK) {
3629 SET_ERR("RequestThread: Unable to correct capture requests "
3630 "for lens distortion for request %d: %s (%d)",
3631 halRequest->frame_number, strerror(-res), res);
3632 return INVALID_OPERATION;
3633 }
3634 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003635 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003636 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003637
3638 for (it = captureRequest->mSettingsList.begin();
3639 it != captureRequest->mSettingsList.end(); it++) {
3640 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3641 parent->mZoomRatioMappers.end()) {
3642 continue;
3643 }
3644
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003645 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003646 cameraIdsWithZoom.insert(it->cameraId);
3647 }
3648
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003649 if (!captureRequest->mZoomRatioUpdated) {
3650 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3651 &(it->metadata));
3652 if (res != OK) {
3653 SET_ERR("RequestThread: Unable to correct capture requests "
3654 "for zoom ratio for request %d: %s (%d)",
3655 halRequest->frame_number, strerror(-res), res);
3656 return INVALID_OPERATION;
3657 }
3658 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003659 }
3660 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003661 if (captureRequest->mRotateAndCropAuto &&
3662 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003663 for (it = captureRequest->mSettingsList.begin();
3664 it != captureRequest->mSettingsList.end(); it++) {
3665 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3666 if (mapper != parent->mRotateAndCropMappers.end()) {
3667 res = mapper->second.updateCaptureRequest(&(it->metadata));
3668 if (res != OK) {
3669 SET_ERR("RequestThread: Unable to correct capture requests "
3670 "for rotate-and-crop for request %d: %s (%d)",
3671 halRequest->frame_number, strerror(-res), res);
3672 return INVALID_OPERATION;
3673 }
3674 }
3675 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003676 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003677 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003678 }
3679 }
3680
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003681 /**
3682 * The request should be presorted so accesses in HAL
3683 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3684 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003685 captureRequest->mSettingsList.begin()->metadata.sort();
3686 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003687 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003688 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003689 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3690
3691 IF_ALOGV() {
3692 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3693 find_camera_metadata_ro_entry(
3694 halRequest->settings,
3695 ANDROID_CONTROL_AF_TRIGGER,
3696 &e
3697 );
3698 if (e.count > 0) {
3699 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3700 __FUNCTION__,
3701 halRequest->frame_number,
3702 e.data.u8[0]);
3703 }
3704 }
3705 } else {
3706 // leave request.settings NULL to indicate 'reuse latest given'
3707 ALOGVV("%s: Request settings are REUSED",
3708 __FUNCTION__);
3709 }
3710
Emilian Peevaebbe412018-01-15 13:53:24 +00003711 if (captureRequest->mSettingsList.size() > 1) {
3712 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3713 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003714 if (newRequest) {
3715 halRequest->physcam_settings =
3716 new const camera_metadata* [halRequest->num_physcam_settings];
3717 } else {
3718 halRequest->physcam_settings = nullptr;
3719 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003720 auto it = ++captureRequest->mSettingsList.begin();
3721 size_t i = 0;
3722 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3723 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003724 if (newRequest) {
3725 it->metadata.sort();
3726 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3727 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003728 }
3729 }
3730
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003731 uint32_t totalNumBuffers = 0;
3732
3733 // Fill in buffers
3734 if (captureRequest->mInputStream != NULL) {
3735 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003736
3737 halRequest->input_width = captureRequest->mInputBufferSize.width;
3738 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003739 totalNumBuffers += 1;
3740 } else {
3741 halRequest->input_buffer = NULL;
3742 }
3743
Emilian Peevf4816702020-04-03 15:44:51 -07003744 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003745 captureRequest->mOutputStreams.size());
3746 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003747 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003748
3749 sp<Camera3Device> parent = mParent.promote();
3750 if (parent == NULL) {
3751 // Should not happen, and nowhere to send errors to, so just log it
3752 CLOGE("RequestThread: Parent is gone");
3753 return INVALID_OPERATION;
3754 }
3755 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3756
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003757 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003758 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003759 sp<Camera3OutputStreamInterface> outputStream =
3760 captureRequest->mOutputStreams.editItemAt(j);
3761 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003762
3763 // Prepare video buffers for high speed recording on the first video request.
3764 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3765 // Only try to prepare video stream on the first video request.
3766 mPrepareVideoStream = false;
3767
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003768 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3769 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003770 while (res == NOT_ENOUGH_DATA) {
3771 res = outputStream->prepareNextBuffer();
3772 }
3773 if (res != OK) {
3774 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3775 __FUNCTION__, strerror(-res), res);
3776 outputStream->cancelPrepare();
3777 }
3778 }
3779
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003780 std::vector<size_t> uniqueSurfaceIds;
3781 res = outputStream->getUniqueSurfaceIds(
3782 captureRequest->mOutputSurfaces[streamId],
3783 &uniqueSurfaceIds);
3784 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3785 if (res != OK && res != INVALID_OPERATION) {
3786 ALOGE("%s: failed to query stream %d unique surface IDs",
3787 __FUNCTION__, streamId);
3788 return res;
3789 }
3790 if (res == OK) {
3791 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3792 }
3793
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003794 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003795 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003796 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003797 return TIMED_OUT;
3798 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003799 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003800 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003801 buffer.stream = outputStream->asHalStream();
3802 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003803 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003804 buffer.acquire_fence = -1;
3805 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003806 // Mark the output stream as unpreparable to block clients from calling
3807 // 'prepare' after this request reaches CameraHal and before the respective
3808 // buffers are requested.
3809 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003810 } else {
3811 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3812 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003813 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003814 if (res != OK) {
3815 // Can't get output buffer from gralloc queue - this could be due to
3816 // abandoned queue or other consumer misbehavior, so not a fatal
3817 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003818 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003819 " %s (%d)", strerror(-res), res);
3820
3821 return TIMED_OUT;
3822 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003823 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003824
3825 {
3826 sp<Camera3Device> parent = mParent.promote();
3827 if (parent != nullptr) {
3828 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3829 for (const auto& settings : captureRequest->mSettingsList) {
3830 if ((streamCameraId.isEmpty() &&
3831 parent->getId() == settings.cameraId.c_str()) ||
3832 streamCameraId == settings.cameraId.c_str()) {
3833 outputStream->fireBufferRequestForFrameNumber(
3834 captureRequest->mResultExtras.frameNumber,
3835 settings.metadata);
3836 }
3837 }
3838 }
3839 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003840
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003841 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003842 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3843 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3844 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3845 } else if (!physicalCameraId.isEmpty()) {
3846 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003847 }
3848 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003849 }
3850 totalNumBuffers += halRequest->num_output_buffers;
3851
3852 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003853 // If this request list is for constrained high speed recording (not
3854 // preview), and the current request is not the last one in the batch,
3855 // do not send callback to the app.
3856 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003857 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003858 hasCallback = false;
3859 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003860 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003861 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003862 const camera_metadata_t* settings = halRequest->settings;
3863 bool shouldUnlockSettings = false;
3864 if (settings == nullptr) {
3865 shouldUnlockSettings = true;
3866 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3867 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003868 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3869 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003870 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003871 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3872 isStillCapture = true;
3873 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3874 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003875
Emilian Peevaf8416e2021-02-04 17:52:43 -08003876 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003877 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003878 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3879 isZslCapture = true;
3880 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003881 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003882 res = parent->registerInFlight(halRequest->frame_number,
3883 totalNumBuffers, captureRequest->mResultExtras,
3884 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003885 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003886 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003887 requestedPhysicalCameras, isStillCapture, isZslCapture,
3888 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003889 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003890 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003891 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3892 ", burstId = %" PRId32 ".",
3893 __FUNCTION__,
3894 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3895 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003896
3897 if (shouldUnlockSettings) {
3898 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3899 }
3900
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003901 if (res != OK) {
3902 SET_ERR("RequestThread: Unable to register new in-flight request:"
3903 " %s (%d)", strerror(-res), res);
3904 return INVALID_OPERATION;
3905 }
3906 }
3907
3908 return OK;
3909}
3910
Igor Murashkin1e479c02013-09-06 16:55:14 -07003911CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003912 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003913 Mutex::Autolock al(mLatestRequestMutex);
3914
3915 ALOGV("RequestThread::%s", __FUNCTION__);
3916
3917 return mLatestRequest;
3918}
3919
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003920bool Camera3Device::RequestThread::isStreamPending(
3921 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003922 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003923 Mutex::Autolock l(mRequestLock);
3924
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003925 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003926 if (!nextRequest.submitted) {
3927 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3928 if (stream == s) return true;
3929 }
3930 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003931 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003932 }
3933
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003934 for (const auto& request : mRequestQueue) {
3935 for (const auto& s : request->mOutputStreams) {
3936 if (stream == s) return true;
3937 }
3938 if (stream == request->mInputStream) return true;
3939 }
3940
3941 for (const auto& request : mRepeatingRequests) {
3942 for (const auto& s : request->mOutputStreams) {
3943 if (stream == s) return true;
3944 }
3945 if (stream == request->mInputStream) return true;
3946 }
3947
3948 return false;
3949}
Jianing Weicb0652e2014-03-12 18:29:36 -07003950
Emilian Peev40ead602017-09-26 15:46:36 +01003951bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3952 ATRACE_CALL();
3953 Mutex::Autolock l(mRequestLock);
3954
3955 for (const auto& nextRequest : mNextRequests) {
3956 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3957 if (s.first == streamId) {
3958 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3959 if (it != s.second.end()) {
3960 return true;
3961 }
3962 }
3963 }
3964 }
3965
3966 for (const auto& request : mRequestQueue) {
3967 for (const auto& s : request->mOutputSurfaces) {
3968 if (s.first == streamId) {
3969 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3970 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003971 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003972 }
3973 }
3974 }
3975 }
3976
3977 for (const auto& request : mRepeatingRequests) {
3978 for (const auto& s : request->mOutputSurfaces) {
3979 if (s.first == streamId) {
3980 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3981 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003982 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003983 }
3984 }
3985 }
3986 }
3987
3988 return false;
3989}
3990
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003991void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3992 if (!mUseHalBufManager) {
3993 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3994 return;
3995 }
3996
3997 Mutex::Autolock pl(mPauseLock);
3998 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003999 mInterface->signalPipelineDrain(streamIds);
4000 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004001 }
4002 // If request thread is still busy, wait until paused then notify HAL
4003 mNotifyPipelineDrain = true;
4004 mStreamIdsToBeDrained = streamIds;
4005}
4006
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004007void Camera3Device::RequestThread::resetPipelineDrain() {
4008 Mutex::Autolock pl(mPauseLock);
4009 mNotifyPipelineDrain = false;
4010 mStreamIdsToBeDrained.clear();
4011}
4012
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004013void Camera3Device::RequestThread::clearPreviousRequest() {
4014 Mutex::Autolock l(mRequestLock);
4015 mPrevRequest.clear();
4016}
4017
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004018status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4019 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4020 ATRACE_CALL();
4021 Mutex::Autolock l(mTriggerMutex);
4022 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4023 return BAD_VALUE;
4024 }
4025 mRotateAndCropOverride = rotateAndCropValue;
4026 return OK;
4027}
4028
Emilian Peeve23f1d92021-09-20 14:56:01 -07004029status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4030 ATRACE_CALL();
4031 Mutex::Autolock l(mTriggerMutex);
4032 mComposerOutput = composerSurfacePresent;
4033 return OK;
4034}
4035
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004036status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004037 ATRACE_CALL();
4038 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004039 if (muteMode != mCameraMute) {
4040 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004041 mCameraMuteChanged = true;
4042 }
4043 return OK;
4044}
4045
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004046nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004047 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004048 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004049 return mExpectedInflightDuration > kMinInflightDuration ?
4050 mExpectedInflightDuration : kMinInflightDuration;
4051}
4052
Emilian Peevaebbe412018-01-15 13:53:24 +00004053void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004054 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004055 if ((request == nullptr) || (halRequest == nullptr)) {
4056 ALOGE("%s: Invalid request!", __FUNCTION__);
4057 return;
4058 }
4059
4060 if (halRequest->num_physcam_settings > 0) {
4061 if (halRequest->physcam_id != nullptr) {
4062 delete [] halRequest->physcam_id;
4063 halRequest->physcam_id = nullptr;
4064 }
4065 if (halRequest->physcam_settings != nullptr) {
4066 auto it = ++(request->mSettingsList.begin());
4067 size_t i = 0;
4068 for (; it != request->mSettingsList.end(); it++, i++) {
4069 it->metadata.unlock(halRequest->physcam_settings[i]);
4070 }
4071 delete [] halRequest->physcam_settings;
4072 halRequest->physcam_settings = nullptr;
4073 }
4074 }
4075}
4076
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004077void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4078 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004079 return;
4080 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004081
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004082 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 // Skip the ones that have been submitted successfully.
4084 if (nextRequest.submitted) {
4085 continue;
4086 }
4087
4088 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004089 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4090 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004091
4092 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004093 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004094 }
4095
Emilian Peevaebbe412018-01-15 13:53:24 +00004096 cleanupPhysicalSettings(captureRequest, halRequest);
4097
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004098 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004099 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4101 }
4102
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004103 // No output buffer can be returned when using HAL buffer manager
4104 if (!mUseHalBufManager) {
4105 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4106 //Buffers that failed processing could still have
4107 //valid acquire fence.
4108 int acquireFence = (*outputBuffers)[i].acquire_fence;
4109 if (0 <= acquireFence) {
4110 close(acquireFence);
4111 outputBuffers->editItemAt(i).acquire_fence = -1;
4112 }
Emilian Peevf4816702020-04-03 15:44:51 -07004113 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004114 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4115 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004116 /*timestampIncreasing*/true, std::vector<size_t> (),
4117 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004118 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004119 }
4120
4121 if (sendRequestError) {
4122 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004123 sp<NotificationListener> listener = mListener.promote();
4124 if (listener != NULL) {
4125 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004126 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004127 captureRequest->mResultExtras);
4128 }
4129 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004130
4131 // Remove yet-to-be submitted inflight request from inflightMap
4132 {
4133 sp<Camera3Device> parent = mParent.promote();
4134 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004135 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004136 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4137 if (idx >= 0) {
4138 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4139 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4140 parent->removeInFlightMapEntryLocked(idx);
4141 }
4142 }
4143 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004144 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004145
4146 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004147 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004148}
4149
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004150void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004151 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152 // Optimized a bit for the simple steady-state case (single repeating
4153 // request), to avoid putting that request in the queue temporarily.
4154 Mutex::Autolock l(mRequestLock);
4155
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004156 assert(mNextRequests.empty());
4157
4158 NextRequest nextRequest;
4159 nextRequest.captureRequest = waitForNextRequestLocked();
4160 if (nextRequest.captureRequest == nullptr) {
4161 return;
4162 }
4163
Emilian Peevf4816702020-04-03 15:44:51 -07004164 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004165 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004166 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004167
4168 // Wait for additional requests
4169 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4170
4171 for (size_t i = 1; i < batchSize; i++) {
4172 NextRequest additionalRequest;
4173 additionalRequest.captureRequest = waitForNextRequestLocked();
4174 if (additionalRequest.captureRequest == nullptr) {
4175 break;
4176 }
4177
Emilian Peevf4816702020-04-03 15:44:51 -07004178 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004179 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004180 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004181 }
4182
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004183 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004184 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004185 mNextRequests.size(), batchSize);
4186 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004187 }
4188
4189 return;
4190}
4191
4192sp<Camera3Device::CaptureRequest>
4193 Camera3Device::RequestThread::waitForNextRequestLocked() {
4194 status_t res;
4195 sp<CaptureRequest> nextRequest;
4196
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004197 while (mRequestQueue.empty()) {
4198 if (!mRepeatingRequests.empty()) {
4199 // Always atomically enqueue all requests in a repeating request
4200 // list. Guarantees a complete in-sequence set of captures to
4201 // application.
4202 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004203 if (mFirstRepeating) {
4204 mFirstRepeating = false;
4205 } else {
4206 for (auto& request : requests) {
4207 // For repeating requests, override timestamp request using
4208 // the time a request is inserted into the request queue,
4209 // because the original repeating request will have an old
4210 // fixed timestamp.
4211 request->mRequestTimeNs = systemTime();
4212 }
4213 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 RequestList::const_iterator firstRequest =
4215 requests.begin();
4216 nextRequest = *firstRequest;
4217 mRequestQueue.insert(mRequestQueue.end(),
4218 ++firstRequest,
4219 requests.end());
4220 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004221
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004222 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004223
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004224 break;
4225 }
4226
4227 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4228
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004229 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4230 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004231 Mutex::Autolock pl(mPauseLock);
4232 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004233 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004235 if (mNotifyPipelineDrain) {
4236 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4237 mNotifyPipelineDrain = false;
4238 mStreamIdsToBeDrained.clear();
4239 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004240 // Let the tracker know
4241 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4242 if (statusTracker != 0) {
4243 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4244 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004245 sp<Camera3Device> parent = mParent.promote();
4246 if (parent != nullptr) {
4247 parent->mRequestBufferSM.onRequestThreadPaused();
4248 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004249 }
4250 // Stop waiting for now and let thread management happen
4251 return NULL;
4252 }
4253 }
4254
4255 if (nextRequest == NULL) {
4256 // Don't have a repeating request already in hand, so queue
4257 // must have an entry now.
4258 RequestList::iterator firstRequest =
4259 mRequestQueue.begin();
4260 nextRequest = *firstRequest;
4261 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004262 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4263 sp<NotificationListener> listener = mListener.promote();
4264 if (listener != NULL) {
4265 listener->notifyRequestQueueEmpty();
4266 }
4267 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004268 }
4269
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004270 // In case we've been unpaused by setPaused clearing mDoPause, need to
4271 // update internal pause state (capture/setRepeatingRequest unpause
4272 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004273 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004274 if (mPaused) {
4275 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4276 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4277 if (statusTracker != 0) {
4278 statusTracker->markComponentActive(mStatusId);
4279 }
4280 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004281 mPaused = false;
4282
4283 // Check if we've reconfigured since last time, and reset the preview
4284 // request if so. Can't use 'NULL request == repeat' across configure calls.
4285 if (mReconfigured) {
4286 mPrevRequest.clear();
4287 mReconfigured = false;
4288 }
4289
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004290 if (nextRequest != NULL) {
4291 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004292 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4293 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004294
4295 // Since RequestThread::clear() removes buffers from the input stream,
4296 // get the right buffer here before unlocking mRequestLock
4297 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004298 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4299 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004300 if (res != OK) {
4301 // Can't get input buffer from gralloc queue - this could be due to
4302 // disconnected queue or other producer misbehavior, so not a fatal
4303 // error
4304 ALOGE("%s: Can't get input buffer, skipping request:"
4305 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004306
4307 sp<NotificationListener> listener = mListener.promote();
4308 if (listener != NULL) {
4309 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004310 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004311 nextRequest->mResultExtras);
4312 }
4313 return NULL;
4314 }
4315 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004316 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004317
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004318 return nextRequest;
4319}
4320
4321bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004322 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 status_t res;
4324 Mutex::Autolock l(mPauseLock);
4325 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004326 if (mPaused == false) {
4327 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004328 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004329 if (mNotifyPipelineDrain) {
4330 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4331 mNotifyPipelineDrain = false;
4332 mStreamIdsToBeDrained.clear();
4333 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004334 // Let the tracker know
4335 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4336 if (statusTracker != 0) {
4337 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4338 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004339 sp<Camera3Device> parent = mParent.promote();
4340 if (parent != nullptr) {
4341 parent->mRequestBufferSM.onRequestThreadPaused();
4342 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004343 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004346 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 return true;
4348 }
4349 }
4350 // We don't set mPaused to false here, because waitForNextRequest needs
4351 // to further manage the paused state in case of starvation.
4352 return false;
4353}
4354
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004355void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004356 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004357 // With work to do, mark thread as unpaused.
4358 // If paused by request (setPaused), don't resume, to avoid
4359 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004360 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004361 Mutex::Autolock p(mPauseLock);
4362 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004363 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4364 if (mPaused) {
4365 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4366 if (statusTracker != 0) {
4367 statusTracker->markComponentActive(mStatusId);
4368 }
4369 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004370 mPaused = false;
4371 }
4372}
4373
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004374void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4375 sp<Camera3Device> parent = mParent.promote();
4376 if (parent != NULL) {
4377 va_list args;
4378 va_start(args, fmt);
4379
4380 parent->setErrorStateV(fmt, args);
4381
4382 va_end(args);
4383 }
4384}
4385
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004386status_t Camera3Device::RequestThread::insertTriggers(
4387 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004388 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004389 Mutex::Autolock al(mTriggerMutex);
4390
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004391 sp<Camera3Device> parent = mParent.promote();
4392 if (parent == NULL) {
4393 CLOGE("RequestThread: Parent is gone");
4394 return DEAD_OBJECT;
4395 }
4396
Emilian Peevaebbe412018-01-15 13:53:24 +00004397 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004398 size_t count = mTriggerMap.size();
4399
4400 for (size_t i = 0; i < count; ++i) {
4401 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004402 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004403
4404 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4405 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4406 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004407 if (isAeTrigger) {
4408 request->mResultExtras.precaptureTriggerId = triggerId;
4409 mCurrentPreCaptureTriggerId = triggerId;
4410 } else {
4411 request->mResultExtras.afTriggerId = triggerId;
4412 mCurrentAfTriggerId = triggerId;
4413 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004414 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004415 }
4416
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004417 camera_metadata_entry entry = metadata.find(tag);
4418
4419 if (entry.count > 0) {
4420 /**
4421 * Already has an entry for this trigger in the request.
4422 * Rewrite it with our requested trigger value.
4423 */
4424 RequestTrigger oldTrigger = trigger;
4425
4426 oldTrigger.entryValue = entry.data.u8[0];
4427
4428 mTriggerReplacedMap.add(tag, oldTrigger);
4429 } else {
4430 /**
4431 * More typical, no trigger entry, so we just add it
4432 */
4433 mTriggerRemovedMap.add(tag, trigger);
4434 }
4435
4436 status_t res;
4437
4438 switch (trigger.getTagType()) {
4439 case TYPE_BYTE: {
4440 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4441 res = metadata.update(tag,
4442 &entryValue,
4443 /*count*/1);
4444 break;
4445 }
4446 case TYPE_INT32:
4447 res = metadata.update(tag,
4448 &trigger.entryValue,
4449 /*count*/1);
4450 break;
4451 default:
4452 ALOGE("%s: Type not supported: 0x%x",
4453 __FUNCTION__,
4454 trigger.getTagType());
4455 return INVALID_OPERATION;
4456 }
4457
4458 if (res != OK) {
4459 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4460 ", value %d", __FUNCTION__, trigger.getTagName(),
4461 trigger.entryValue);
4462 return res;
4463 }
4464
4465 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4466 trigger.getTagName(),
4467 trigger.entryValue);
4468 }
4469
4470 mTriggerMap.clear();
4471
4472 return count;
4473}
4474
4475status_t Camera3Device::RequestThread::removeTriggers(
4476 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004477 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004478 Mutex::Autolock al(mTriggerMutex);
4479
Emilian Peevaebbe412018-01-15 13:53:24 +00004480 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004481
4482 /**
4483 * Replace all old entries with their old values.
4484 */
4485 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4486 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4487
4488 status_t res;
4489
4490 uint32_t tag = trigger.metadataTag;
4491 switch (trigger.getTagType()) {
4492 case TYPE_BYTE: {
4493 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4494 res = metadata.update(tag,
4495 &entryValue,
4496 /*count*/1);
4497 break;
4498 }
4499 case TYPE_INT32:
4500 res = metadata.update(tag,
4501 &trigger.entryValue,
4502 /*count*/1);
4503 break;
4504 default:
4505 ALOGE("%s: Type not supported: 0x%x",
4506 __FUNCTION__,
4507 trigger.getTagType());
4508 return INVALID_OPERATION;
4509 }
4510
4511 if (res != OK) {
4512 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4513 ", trigger value %d", __FUNCTION__,
4514 trigger.getTagName(), trigger.entryValue);
4515 return res;
4516 }
4517 }
4518 mTriggerReplacedMap.clear();
4519
4520 /**
4521 * Remove all new entries.
4522 */
4523 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4524 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4525 status_t res = metadata.erase(trigger.metadataTag);
4526
4527 if (res != OK) {
4528 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4529 ", trigger value %d", __FUNCTION__,
4530 trigger.getTagName(), trigger.entryValue);
4531 return res;
4532 }
4533 }
4534 mTriggerRemovedMap.clear();
4535
4536 return OK;
4537}
4538
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004539status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004540 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004541 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004542 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004543 status_t res;
4544
Emilian Peevaebbe412018-01-15 13:53:24 +00004545 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004546
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004547 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004548 // exists
4549 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4550 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4551 if (afTrigger.count > 0 &&
4552 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4553 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004554 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004555 if (res != OK) return res;
4556 }
4557
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004558 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004559 // if none already exists
4560 camera_metadata_entry pcTrigger =
4561 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4562 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4563 if (pcTrigger.count > 0 &&
4564 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4565 pcId.count == 0) {
4566 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004567 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004568 if (res != OK) return res;
4569 }
4570
4571 return OK;
4572}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004573
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004574bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4575 const sp<CaptureRequest> &request) {
4576 ATRACE_CALL();
4577
4578 if (request->mRotateAndCropAuto) {
4579 Mutex::Autolock l(mTriggerMutex);
4580 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4581
4582 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4583 if (rotateAndCropEntry.count > 0) {
4584 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4585 return false;
4586 } else {
4587 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4588 return true;
4589 }
4590 } else {
4591 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4592 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4593 &rotateAndCrop_u8, 1);
4594 return true;
4595 }
4596 }
4597 return false;
4598}
4599
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004600bool Camera3Device::RequestThread::overrideTestPattern(
4601 const sp<CaptureRequest> &request) {
4602 ATRACE_CALL();
4603
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004604 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004605
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004606 Mutex::Autolock l(mTriggerMutex);
4607
4608 bool changed = false;
4609
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004610 // For a multi-camera, the physical cameras support the same set of
4611 // test pattern modes as the logical camera.
4612 for (auto& settings : request->mSettingsList) {
4613 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004614
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004615 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4616 int32_t testPatternData[4] = {
4617 settings.mOriginalTestPatternData[0],
4618 settings.mOriginalTestPatternData[1],
4619 settings.mOriginalTestPatternData[2],
4620 settings.mOriginalTestPatternData[3]
4621 };
4622 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4623 testPatternMode = mCameraMute;
4624 testPatternData[0] = 0;
4625 testPatternData[1] = 0;
4626 testPatternData[2] = 0;
4627 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004628 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004629
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004630 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4631 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4632 if (testPatternEntry.count > 0) {
4633 if (testPatternEntry.data.i32[0] != testPatternMode) {
4634 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004635 changed = true;
4636 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004637 } else if (supportTestPatternModeKey) {
4638 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4639 &testPatternMode, 1);
4640 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004641 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004642
4643 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4644 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4645 if (testPatternColor.count >= 4) {
4646 for (size_t i = 0; i < 4; i++) {
4647 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4648 testPatternColor.data.i32[i] = testPatternData[i];
4649 changed = true;
4650 }
4651 }
4652 } else if (supportTestPatternDataKey) {
4653 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4654 testPatternData, 4);
4655 changed = true;
4656 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004657 }
4658
4659 return changed;
4660}
4661
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004662status_t Camera3Device::RequestThread::setHalInterface(
4663 sp<HalInterface> newHalInterface) {
4664 if (newHalInterface.get() == nullptr) {
4665 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4666 return DEAD_OBJECT;
4667 }
4668
4669 mInterface = newHalInterface;
4670
4671 return OK;
4672}
4673
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004674/**
4675 * PreparerThread inner class methods
4676 */
4677
4678Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004679 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004680 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004681}
4682
4683Camera3Device::PreparerThread::~PreparerThread() {
4684 Thread::requestExitAndWait();
4685 if (mCurrentStream != nullptr) {
4686 mCurrentStream->cancelPrepare();
4687 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4688 mCurrentStream.clear();
4689 }
4690 clear();
4691}
4692
Ruben Brunkc78ac262015-08-13 17:58:46 -07004693status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004694 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004695 status_t res;
4696
4697 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004698 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004699
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004700 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004701 if (res == OK) {
4702 // No preparation needed, fire listener right off
4703 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004704 if (listener != NULL) {
4705 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004706 }
4707 return OK;
4708 } else if (res != NOT_ENOUGH_DATA) {
4709 return res;
4710 }
4711
4712 // Need to prepare, start up thread if necessary
4713 if (!mActive) {
4714 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4715 // isn't running
4716 Thread::requestExitAndWait();
4717 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4718 if (res != OK) {
4719 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004720 if (listener != NULL) {
4721 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004722 }
4723 return res;
4724 }
4725 mCancelNow = false;
4726 mActive = true;
4727 ALOGV("%s: Preparer stream started", __FUNCTION__);
4728 }
4729
4730 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004731 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004732 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4733
4734 return OK;
4735}
4736
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004737void Camera3Device::PreparerThread::pause() {
4738 ATRACE_CALL();
4739
4740 Mutex::Autolock l(mLock);
4741
4742 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4743 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4744 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4745 int currentMaxCount = mCurrentMaxCount;
4746 mPendingStreams.clear();
4747 mCancelNow = true;
4748 while (mActive) {
4749 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4750 if (res == TIMED_OUT) {
4751 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4752 return;
4753 } else if (res != OK) {
4754 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4755 return;
4756 }
4757 }
4758
4759 //Check whether the prepare thread was able to complete the current
4760 //stream. In case work is still pending emplace it along with the rest
4761 //of the streams in the pending list.
4762 if (currentStream != nullptr) {
4763 if (!mCurrentPrepareComplete) {
4764 pendingStreams.emplace(currentMaxCount, currentStream);
4765 }
4766 }
4767
4768 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4769 for (const auto& it : mPendingStreams) {
4770 it.second->cancelPrepare();
4771 }
4772}
4773
4774status_t Camera3Device::PreparerThread::resume() {
4775 ATRACE_CALL();
4776 status_t res;
4777
4778 Mutex::Autolock l(mLock);
4779 sp<NotificationListener> listener = mListener.promote();
4780
4781 if (mActive) {
4782 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4783 return NO_INIT;
4784 }
4785
4786 auto it = mPendingStreams.begin();
4787 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004788 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004789 if (res == OK) {
4790 if (listener != NULL) {
4791 listener->notifyPrepared(it->second->getId());
4792 }
4793 it = mPendingStreams.erase(it);
4794 } else if (res != NOT_ENOUGH_DATA) {
4795 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4796 res, strerror(-res));
4797 it = mPendingStreams.erase(it);
4798 } else {
4799 it++;
4800 }
4801 }
4802
4803 if (mPendingStreams.empty()) {
4804 return OK;
4805 }
4806
4807 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4808 if (res != OK) {
4809 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4810 __FUNCTION__, res, strerror(-res));
4811 return res;
4812 }
4813 mCancelNow = false;
4814 mActive = true;
4815 ALOGV("%s: Preparer stream started", __FUNCTION__);
4816
4817 return OK;
4818}
4819
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004820status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004821 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004822 Mutex::Autolock l(mLock);
4823
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004824 for (const auto& it : mPendingStreams) {
4825 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004826 }
4827 mPendingStreams.clear();
4828 mCancelNow = true;
4829
4830 return OK;
4831}
4832
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004833void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004834 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004835 Mutex::Autolock l(mLock);
4836 mListener = listener;
4837}
4838
4839bool Camera3Device::PreparerThread::threadLoop() {
4840 status_t res;
4841 {
4842 Mutex::Autolock l(mLock);
4843 if (mCurrentStream == nullptr) {
4844 // End thread if done with work
4845 if (mPendingStreams.empty()) {
4846 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4847 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4848 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4849 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004850 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004851 return false;
4852 }
4853
4854 // Get next stream to prepare
4855 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004856 mCurrentStream = it->second;
4857 mCurrentMaxCount = it->first;
4858 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004859 mPendingStreams.erase(it);
4860 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4861 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4862 } else if (mCancelNow) {
4863 mCurrentStream->cancelPrepare();
4864 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4865 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4866 mCurrentStream.clear();
4867 mCancelNow = false;
4868 return true;
4869 }
4870 }
4871
4872 res = mCurrentStream->prepareNextBuffer();
4873 if (res == NOT_ENOUGH_DATA) return true;
4874 if (res != OK) {
4875 // Something bad happened; try to recover by cancelling prepare and
4876 // signalling listener anyway
4877 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4878 mCurrentStream->getId(), res, strerror(-res));
4879 mCurrentStream->cancelPrepare();
4880 }
4881
4882 // This stream has finished, notify listener
4883 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004884 sp<NotificationListener> listener = mListener.promote();
4885 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004886 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4887 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004888 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004889 }
4890
4891 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4892 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004893 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004894
4895 return true;
4896}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004897
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004898status_t Camera3Device::RequestBufferStateMachine::initialize(
4899 sp<camera3::StatusTracker> statusTracker) {
4900 if (statusTracker == nullptr) {
4901 ALOGE("%s: statusTracker is null", __FUNCTION__);
4902 return BAD_VALUE;
4903 }
4904
4905 std::lock_guard<std::mutex> lock(mLock);
4906 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004907 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004908 return OK;
4909}
4910
4911bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4912 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004913 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004914 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004915 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004916 return true;
4917 }
4918 return false;
4919}
4920
4921void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4922 std::lock_guard<std::mutex> lock(mLock);
4923 if (!mRequestBufferOngoing) {
4924 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4925 return;
4926 }
4927 mRequestBufferOngoing = false;
4928 if (mStatus == RB_STATUS_PENDING_STOP) {
4929 checkSwitchToStopLocked();
4930 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004931 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004932}
4933
4934void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4935 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004936 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004937 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004938 return;
4939}
4940
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004941void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004942 std::lock_guard<std::mutex> lock(mLock);
4943 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004944 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4945 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004946 mInflightMapEmpty = false;
4947 if (mStatus == RB_STATUS_STOPPED) {
4948 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004949 }
4950 return;
4951}
4952
4953void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4954 std::lock_guard<std::mutex> lock(mLock);
4955 mRequestThreadPaused = true;
4956 if (mStatus == RB_STATUS_PENDING_STOP) {
4957 checkSwitchToStopLocked();
4958 }
4959 return;
4960}
4961
4962void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4963 std::lock_guard<std::mutex> lock(mLock);
4964 mInflightMapEmpty = true;
4965 if (mStatus == RB_STATUS_PENDING_STOP) {
4966 checkSwitchToStopLocked();
4967 }
4968 return;
4969}
4970
4971void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4972 std::lock_guard<std::mutex> lock(mLock);
4973 if (!checkSwitchToStopLocked()) {
4974 mStatus = RB_STATUS_PENDING_STOP;
4975 }
4976 return;
4977}
4978
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004979bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4980 std::lock_guard<std::mutex> lock(mLock);
4981 if (mRequestBufferOngoing) {
4982 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4983 __FUNCTION__);
4984 return false;
4985 }
4986 mSwitchedToOffline = true;
4987 mInflightMapEmpty = true;
4988 mRequestThreadPaused = true;
4989 mStatus = RB_STATUS_STOPPED;
4990 return true;
4991}
4992
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004993void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4994 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4995 if (statusTracker != nullptr) {
4996 if (active) {
4997 statusTracker->markComponentActive(mRequestBufferStatusId);
4998 } else {
4999 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5000 }
5001 }
5002}
5003
5004bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5005 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5006 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005007 return true;
5008 }
5009 return false;
5010}
5011
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005012bool Camera3Device::startRequestBuffer() {
5013 return mRequestBufferSM.startRequestBuffer();
5014}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005015
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005016void Camera3Device::endRequestBuffer() {
5017 mRequestBufferSM.endRequestBuffer();
5018}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005019
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005020nsecs_t Camera3Device::getWaitDuration() {
5021 return kBaseGetBufferWait + getExpectedInFlightDuration();
5022}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005023
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005024void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5025 mInterface->getInflightBufferKeys(out);
5026}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005027
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005028void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5029 mInterface->getInflightRequestBufferKeys(out);
5030}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005032std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5033 std::vector<sp<Camera3StreamInterface>> ret;
5034 bool hasInputStream = mInputStream != nullptr;
5035 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5036 if (hasInputStream) {
5037 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005038 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005039 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5040 ret.push_back(mOutputStreams[i]);
5041 }
5042 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5043 ret.push_back(mDeletedStreams[i]);
5044 }
5045 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005046}
5047
Emilian Peevcc0b7952020-01-07 13:54:47 -08005048void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5049 ATRACE_CALL();
5050
5051 if (offlineStreamIds == nullptr) {
5052 return;
5053 }
5054
5055 Mutex::Autolock il(mInterfaceLock);
5056
5057 auto streamIds = mOutputStreams.getStreamIds();
5058 bool hasInputStream = mInputStream != nullptr;
5059 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5060 offlineStreamIds->push_back(mInputStream->getId());
5061 }
5062
5063 for (const auto & streamId : streamIds) {
5064 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5065 // Streams that use the camera buffer manager are currently not supported in
5066 // offline mode
5067 if (stream->getOfflineProcessingSupport() &&
5068 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5069 offlineStreamIds->push_back(streamId);
5070 }
5071 }
5072}
5073
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005074status_t Camera3Device::setRotateAndCropAutoBehavior(
5075 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5076 ATRACE_CALL();
5077 Mutex::Autolock il(mInterfaceLock);
5078 Mutex::Autolock l(mLock);
5079 if (mRequestThread == nullptr) {
5080 return INVALID_OPERATION;
5081 }
5082 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5083}
5084
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005085bool Camera3Device::supportsCameraMute() {
5086 Mutex::Autolock il(mInterfaceLock);
5087 Mutex::Autolock l(mLock);
5088
5089 return mSupportCameraMute;
5090}
5091
5092status_t Camera3Device::setCameraMute(bool enabled) {
5093 ATRACE_CALL();
5094 Mutex::Autolock il(mInterfaceLock);
5095 Mutex::Autolock l(mLock);
5096
5097 if (mRequestThread == nullptr || !mSupportCameraMute) {
5098 return INVALID_OPERATION;
5099 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005100 int32_t muteMode =
5101 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5102 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5103 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5104 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005105}
5106
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005107status_t Camera3Device::injectCamera(const String8& injectedCamId,
5108 sp<CameraProviderManager> manager) {
5109 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5110 ATRACE_CALL();
5111 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005112 // When the camera device is active, injectCamera() and stopInjection() will call
5113 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5114 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5115 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5116 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5117 // waitUntilStateThenRelock().
5118 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005119
5120 status_t res = NO_ERROR;
5121 if (mInjectionMethods->isInjecting()) {
5122 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5123 return OK;
5124 } else {
5125 res = mInjectionMethods->stopInjection();
5126 if (res != OK) {
5127 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5128 __FUNCTION__, res);
5129 return res;
5130 }
5131 }
5132 }
5133
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005134 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005135 if (res != OK) {
5136 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5137 __FUNCTION__, res);
5138 return res;
5139 }
5140
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005141 // When the second display of android is cast to the remote device, and the opened camera is
5142 // also cast to the second display, in this case, because the camera has configured the streams
5143 // at this time, we can directly call injectCamera() to replace the internal camera with
5144 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005145 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5146 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5147
5148 camera3::camera_stream_configuration injectionConfig;
5149 std::vector<uint32_t> injectionBufferSizes;
5150 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5151 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5152 || injectionBufferSizes.size() <= 0) {
5153 ALOGE("Failed to inject camera due to abandoned configuration! "
5154 "mOperatingMode: %d injectionConfig.num_streams: %d "
5155 "injectionBufferSizes.size(): %zu", mOperatingMode,
5156 injectionConfig.num_streams, injectionBufferSizes.size());
5157 return DEAD_OBJECT;
5158 }
5159
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005160 res = mInjectionMethods->injectCamera(
5161 injectionConfig, injectionBufferSizes);
5162 if (res != OK) {
5163 ALOGE("Can't finish inject camera process!");
5164 return res;
5165 }
5166 }
5167
5168 return OK;
5169}
5170
5171status_t Camera3Device::stopInjection() {
5172 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5173 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005174 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005175 return mInjectionMethods->stopInjection();
5176}
5177
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005178}; // namespace android