blob: c8f631071a16bf7aeaa5b3ad088939b150b5baa4 [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
Jayant Chowdhary0bd38522021-11-05 17:49:27 -070068#include "../common/hidl/HidlProviderInfo.h"
69
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080070#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080071#include <tuple>
72
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080073using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074using namespace android::hardware::camera;
75using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080076using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080077
78namespace android {
79
Emilian Peev5104fe92021-10-21 14:27:09 -070080Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070082 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080083 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070084 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070085 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070086 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070087 mUsePartialResult(false),
88 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080089 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070090 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070091 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070092 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070093 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070094 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070095 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000096 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010097 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070098 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070099 mNeedFixupMonochromeTags(false),
100 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101{
102 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
106Camera3Device::~Camera3Device()
107{
108 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700110 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800111}
112
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800113const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800114 return mId;
115}
116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117status_t Camera3Device::initializeCommonLocked() {
118
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700119 /** Start up status tracker thread */
120 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800121 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700122 if (res != OK) {
123 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
124 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700126 mStatusTracker.clear();
127 return res;
128 }
129
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700130 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700131 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700132
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700133 if (mUseHalBufManager) {
134 res = mRequestBufferSM.initialize(mStatusTracker);
135 if (res != OK) {
136 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
137 strerror(-res), res);
138 mInterface->close();
139 mStatusTracker.clear();
140 return res;
141 }
142 }
143
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800144 /** Create buffer manager */
145 mBufferManager = new Camera3BufferManager();
146
147 Vector<int32_t> sessionParamKeys;
148 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
149 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
150 if (sessionKeysEntry.count > 0) {
151 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
152 }
153
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700154 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
155 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
156 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
157 if (availableTestPatternModes.data.i32[i] ==
158 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
159 mSupportCameraMute = true;
160 mSupportTestPatternSolidColor = true;
161 break;
162 } else if (availableTestPatternModes.data.i32[i] ==
163 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
164 mSupportCameraMute = true;
165 mSupportTestPatternSolidColor = false;
166 }
167 }
168
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700169 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800170 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700171 this, mStatusTracker, mInterface, sessionParamKeys,
172 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800173 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800174 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700175 SET_ERR_L("Unable to start request queue thread: %s (%d)",
176 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800177 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800178 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800179 return res;
180 }
181
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700182 mPreparerThread = new PreparerThread();
183
Ruben Brunk183f0562015-08-12 12:55:02 -0700184 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800185 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400186 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700187 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700188 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800189 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800190
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800191 // Measure the clock domain offset between camera and video/hw_composer
192 camera_metadata_entry timestampSource =
193 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
194 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
195 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
196 mTimestampOffset = getMonoToBoottimeOffset();
197 }
198
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700199 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100200 camera_metadata_entry partialResultsCount =
201 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
202 if (partialResultsCount.count > 0) {
203 mNumPartialResults = partialResultsCount.data.i32[0];
204 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700205 }
206
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800207 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
208 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700209 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700210 if (res != OK) {
211 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
212 return res;
213 }
214 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800216 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700219 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
220 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
221 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
222 }
223
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800224 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
225 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
226 }
227
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800228 // Hidl/AidlCamera3DeviceInjectionMethods
229 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800230
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 return OK;
232}
233
234status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700235 return disconnectImpl();
236}
237
238status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800239 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700240 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800241
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700242 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700243 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800245 Mutex::Autolock il(mInterfaceLock);
246 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
247 {
248 Mutex::Autolock l(mLock);
249 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700250
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800251 if (mStatus == STATUS_ACTIVE ||
252 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
253 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700254 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800255 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 } else {
258 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
259 if (res != OK) {
260 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
261 maxExpectedDuration);
262 // Continue to close device even in case of error
263 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800266
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800267 if (mStatus == STATUS_ERROR) {
268 CLOGE("Shutting down in an error state");
269 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700270
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800271 if (mStatusTracker != NULL) {
272 mStatusTracker->requestExit();
273 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700274
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800275 if (mRequestThread != NULL) {
276 mRequestThread->requestExit();
277 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700278
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800279 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
280 for (size_t i = 0; i < mOutputStreams.size(); i++) {
281 streams.push_back(mOutputStreams[i]);
282 }
283 if (mInputStream != nullptr) {
284 streams.push_back(mInputStream);
285 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
289 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
291 // HAL may be in a bad state, so waiting for request thread
292 // (which may be stuck in the HAL processCaptureRequest call)
293 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800294 // give up mInterfaceLock here and then lock it again. Could this lead
295 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 mRequestThread->join();
297 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800299 Mutex::Autolock il(mInterfaceLock);
300 if (mStatusTracker != NULL) {
301 mStatusTracker->join();
302 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800304 if (mInjectionMethods->isInjecting()) {
305 mInjectionMethods->stopInjection();
306 }
307
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 HalInterface* interface;
309 {
310 Mutex::Autolock l(mLock);
311 mRequestThread.clear();
312 Mutex::Autolock stLock(mTrackerLock);
313 mStatusTracker.clear();
314 interface = mInterface.get();
315 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700316
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 // Call close without internal mutex held, as the HAL close may need to
318 // wait on assorted callbacks,etc, to complete before it can return.
319 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700320
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800321 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800322
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 {
324 Mutex::Autolock l(mLock);
325 mInterface->clear();
326 mOutputStreams.clear();
327 mInputStream.clear();
328 mDeletedStreams.clear();
329 mBufferManager.clear();
330 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
331 }
332
333 for (auto& weakStream : streams) {
334 sp<Camera3StreamInterface> stream = weakStream.promote();
335 if (stream != nullptr) {
336 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
337 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
338 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700339 }
340 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343}
344
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345// For dumping/debugging only -
346// try to acquire a lock a few times, eventually give up to proceed with
347// debug/dump operations
348bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
349 bool gotLock = false;
350 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
351 if (lock.tryLock() == NO_ERROR) {
352 gotLock = true;
353 break;
354 } else {
355 usleep(kDumpSleepDuration);
356 }
357 }
358 return gotLock;
359}
360
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800361nsecs_t Camera3Device::getMonoToBoottimeOffset() {
362 // try three times to get the clock offset, choose the one
363 // with the minimum gap in measurements.
364 const int tries = 3;
365 nsecs_t bestGap, measured;
366 for (int i = 0; i < tries; ++i) {
367 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
368 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
369 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t gap = tmono2 - tmono;
371 if (i == 0 || gap < bestGap) {
372 bestGap = gap;
373 measured = tbase - ((tmono + tmono2) >> 1);
374 }
375 }
376 return measured;
377}
378
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800379ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
380 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700381 // Get max jpeg size (area-wise) for default sensor pixel mode
382 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800383 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700384 /*isUltraHighResolutionSensor*/false);
385 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
386 // not ultra high res sensor
387 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800388 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700389 /*isUltraHighResolution*/true);
390 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
392 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700393 return BAD_VALUE;
394 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700395 bool useMaxSensorPixelModeThreshold = false;
396 if (uhrMaxJpegResolution.width != 0 &&
397 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
398 // Use the ultra high res max jpeg size and max jpeg buffer size
399 useMaxSensorPixelModeThreshold = true;
400 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700401
Zhijun Hef7da0962014-04-24 13:27:56 -0700402 // Get max jpeg buffer size
403 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800404 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
407 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700408 return BAD_VALUE;
409 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700410 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700411
412 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
413 if (useMaxSensorPixelModeThreshold) {
414 maxJpegBufferSize =
415 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
416 maxDefaultJpegResolution, maxJpegBufferSize);
417 chosenMaxJpegResolution = uhrMaxJpegResolution;
418 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800419 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700420
421 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700422 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700423 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800424 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
425 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700426 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800427 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
428 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700429 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700430 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 return jpegBufferSize;
432}
433
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800434ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700435 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800436 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700437 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800438 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
439 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700440 return BAD_VALUE;
441 }
442 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
443 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
444 return maxBytesForPointCloud;
445}
446
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800447ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
448 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800449 const int PER_CONFIGURATION_SIZE = 3;
450 const int WIDTH_OFFSET = 0;
451 const int HEIGHT_OFFSET = 1;
452 const int SIZE_OFFSET = 2;
453 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800454 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800455 camera3::SessionConfigurationUtils::getAppropriateModeTag(
456 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
457 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800458 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800459 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800460 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
461 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800462 return BAD_VALUE;
463 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700464
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800465 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
466 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
467 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
468 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
469 }
470 }
471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800472 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
473 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 return BAD_VALUE;
475}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700476
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800477status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
478 ATRACE_CALL();
479 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700480
481 // Try to lock, but continue in case of failure (to avoid blocking in
482 // deadlocks)
483 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
484 bool gotLock = tryLockSpinRightRound(mLock);
485
486 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
488 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700489 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
491 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700492
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800493 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700494
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800495 String16 templatesOption("-t");
496 int n = args.size();
497 for (int i = 0; i < n; i++) {
498 if (args[i] == templatesOption) {
499 dumpTemplates = true;
500 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000501 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700502 if (i + 1 < n) {
503 String8 monitorTags = String8(args[i + 1]);
504 if (monitorTags == "off") {
505 mTagMonitor.disableMonitoring();
506 } else {
507 mTagMonitor.parseTagsToMonitor(monitorTags);
508 }
509 } else {
510 mTagMonitor.disableMonitoring();
511 }
512 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800513 }
514
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800515 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800517 const char *status =
518 mStatus == STATUS_ERROR ? "ERROR" :
519 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700520 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
521 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800522 mStatus == STATUS_ACTIVE ? "ACTIVE" :
523 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800525 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700526 if (mStatus == STATUS_ERROR) {
527 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800529 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800530 const char *mode =
531 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
532 mOperatingMode == static_cast<int>(
533 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
534 "CUSTOM";
535 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800536
537 if (mInputStream != NULL) {
538 write(fd, lines.string(), lines.size());
539 mInputStream->dump(fd, args);
540 } else {
541 lines.appendFormat(" No input stream.\n");
542 write(fd, lines.string(), lines.size());
543 }
544 for (size_t i = 0; i < mOutputStreams.size(); i++) {
545 mOutputStreams[i]->dump(fd,args);
546 }
547
Zhijun He431503c2016-03-07 17:30:16 -0800548 if (mBufferManager != NULL) {
549 lines = String8(" Camera3 Buffer Manager:\n");
550 write(fd, lines.string(), lines.size());
551 mBufferManager->dump(fd, args);
552 }
Zhijun He125684a2015-12-26 15:07:30 -0800553
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700554 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700555 if (mInFlightLock.try_lock()) {
556 if (mInFlightMap.size() == 0) {
557 lines.append(" None\n");
558 } else {
559 for (size_t i = 0; i < mInFlightMap.size(); i++) {
560 InFlightRequest r = mInFlightMap.valueAt(i);
561 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
562 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
563 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
564 r.numBuffersLeft);
565 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700566 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700567 mInFlightLock.unlock();
568 } else {
569 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700570 }
571 write(fd, lines.string(), lines.size());
572
Shuzhen Wang686f6442017-06-20 16:16:04 -0700573 if (mRequestThread != NULL) {
574 mRequestThread->dumpCaptureRequestLatency(fd,
575 " ProcessCaptureRequest latency histogram:");
576 }
577
Igor Murashkin1e479c02013-09-06 16:55:14 -0700578 {
579 lines = String8(" Last request sent:\n");
580 write(fd, lines.string(), lines.size());
581
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700582 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700583 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
584 }
585
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800586 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700587 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800588 "TEMPLATE_PREVIEW",
589 "TEMPLATE_STILL_CAPTURE",
590 "TEMPLATE_VIDEO_RECORD",
591 "TEMPLATE_VIDEO_SNAPSHOT",
592 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800593 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800594 };
595
Emilian Peevf4816702020-04-03 15:44:51 -0700596 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 camera_metadata_t *templateRequest = nullptr;
598 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700599 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800601 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 lines.append(" Not supported\n");
603 write(fd, lines.string(), lines.size());
604 } else {
605 write(fd, lines.string(), lines.size());
606 dump_indented_camera_metadata(templateRequest,
607 fd, /*verbosity*/2, /*indentation*/8);
608 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 }
611 }
612
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700613 mTagMonitor.dumpMonitoredMetadata(fd);
614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800616 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800617 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800620
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700621 if (gotLock) mLock.unlock();
622 if (gotInterfaceLock) mInterfaceLock.unlock();
623
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800624 return OK;
625}
626
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700627status_t Camera3Device::startWatchingTags(const String8 &tags) {
628 mTagMonitor.parseTagsToMonitor(tags);
629 return OK;
630}
631
632status_t Camera3Device::stopWatchingTags() {
633 mTagMonitor.disableMonitoring();
634 return OK;
635}
636
637status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
638 mTagMonitor.getLatestMonitoredTagEvents(out);
639 return OK;
640}
641
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800642const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800643 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
645 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700646 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800647 mStatus == STATUS_ERROR ?
648 "when in error state" : "before init");
649 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700650 if (physicalId.isEmpty()) {
651 return mDeviceInfo;
652 } else {
653 std::string id(physicalId.c_str());
654 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
655 return mPhysicalDeviceInfoMap.at(id);
656 } else {
657 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
658 return mDeviceInfo;
659 }
660 }
661}
662
663const CameraMetadata& Camera3Device::info() const {
664 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800665 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800666}
667
Jianing Wei90e59c92014-03-12 18:29:36 -0700668status_t Camera3Device::checkStatusOkToCaptureLocked() {
669 switch (mStatus) {
670 case STATUS_ERROR:
671 CLOGE("Device has encountered a serious error");
672 return INVALID_OPERATION;
673 case STATUS_UNINITIALIZED:
674 CLOGE("Device not initialized");
675 return INVALID_OPERATION;
676 case STATUS_UNCONFIGURED:
677 case STATUS_CONFIGURED:
678 case STATUS_ACTIVE:
679 // OK
680 break;
681 default:
682 SET_ERR_L("Unexpected status: %d", mStatus);
683 return INVALID_OPERATION;
684 }
685 return OK;
686}
687
688status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000689 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700690 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700691 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700692 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700693 if (requestList == NULL) {
694 CLOGE("requestList cannot be NULL.");
695 return BAD_VALUE;
696 }
697
Jianing Weicb0652e2014-03-12 18:29:36 -0700698 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000699 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700700 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
701 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
702 ++metadataIt, ++surfaceMapIt) {
703 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700704 if (newRequest == 0) {
705 CLOGE("Can't create capture request");
706 return BAD_VALUE;
707 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700708
Shuzhen Wang9d066012016-09-30 11:30:20 -0700709 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700710 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700711
Jianing Weicb0652e2014-03-12 18:29:36 -0700712 // Setup burst Id and request Id
713 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800714 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
715 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700716 CLOGE("RequestID does not exist in metadata");
717 return BAD_VALUE;
718 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800719 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700720
Jianing Wei90e59c92014-03-12 18:29:36 -0700721 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700722
723 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700724 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700725 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
726 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
727 return BAD_VALUE;
728 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700729
730 // Setup batch size if this is a high speed video recording request.
731 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
732 auto firstRequest = requestList->begin();
733 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
734 if (outputStream->isVideoStream()) {
735 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800736 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700737 break;
738 }
739 }
740 }
741
Jianing Wei90e59c92014-03-12 18:29:36 -0700742 return OK;
743}
744
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800745status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800746 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800747
Emilian Peevaebbe412018-01-15 13:53:24 +0000748 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700749 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000750 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800752 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753}
754
Emilian Peevaebbe412018-01-15 13:53:24 +0000755void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700756 std::list<const SurfaceMap>& surfaceMaps,
757 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000758 PhysicalCameraSettingsList requestList;
759 requestList.push_back({std::string(getId().string()), request});
760 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761
762 SurfaceMap surfaceMap;
763 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
764 // With no surface list passed in, stream and surface will have 1-to-1
765 // mapping. So the surface index is 0 for each stream in the surfaceMap.
766 for (size_t i = 0; i < streams.count; i++) {
767 surfaceMap[streams.data.i32[i]].push_back(0);
768 }
769 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800770}
771
Jianing Wei90e59c92014-03-12 18:29:36 -0700772status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000773 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700774 const std::list<const SurfaceMap> &surfaceMaps,
775 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700776 /*out*/
777 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700778 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700779 nsecs_t requestTimeNs = systemTime();
780
Jianing Wei90e59c92014-03-12 18:29:36 -0700781 Mutex::Autolock il(mInterfaceLock);
782 Mutex::Autolock l(mLock);
783
784 status_t res = checkStatusOkToCaptureLocked();
785 if (res != OK) {
786 // error logged by previous call
787 return res;
788 }
789
790 RequestList requestList;
791
Shuzhen Wang0129d522016-10-30 22:43:41 -0700792 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700793 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700794 if (res != OK) {
795 // error logged by previous call
796 return res;
797 }
798
799 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700800 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700801 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700802 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 }
804
805 if (res == OK) {
806 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
807 if (res != OK) {
808 SET_ERR_L("Can't transition to active in %f seconds!",
809 kActiveTimeout/1e9);
810 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700812 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700813 } else {
814 CLOGE("Cannot queue request. Impossible.");
815 return BAD_VALUE;
816 }
817
818 return res;
819}
820
Emilian Peevaebbe412018-01-15 13:53:24 +0000821status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700822 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700823 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 ATRACE_CALL();
825
Emilian Peevaebbe412018-01-15 13:53:24 +0000826 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828
Jianing Weicb0652e2014-03-12 18:29:36 -0700829status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
830 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800831 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832
Emilian Peevaebbe412018-01-15 13:53:24 +0000833 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700834 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836
Emilian Peevaebbe412018-01-15 13:53:24 +0000837 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700838 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800839}
840
Emilian Peevaebbe412018-01-15 13:53:24 +0000841status_t Camera3Device::setStreamingRequestList(
842 const List<const PhysicalCameraSettingsList> &requestsList,
843 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 ATRACE_CALL();
845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700847}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800848
849sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800851 status_t res;
852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700853 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800854 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
855 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700857 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700858 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800859 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700862 } else if (mStatus == STATUS_UNCONFIGURED) {
863 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700864 CLOGE("No streams configured");
865 return NULL;
866 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800867 }
868
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800870 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800871}
872
Jianing Weicb0652e2014-03-12 18:29:36 -0700873status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800874 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700875 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800876 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800877
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 switch (mStatus) {
879 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700880 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 return INVALID_OPERATION;
882 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700883 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700885 case STATUS_UNCONFIGURED:
886 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800887 case STATUS_ACTIVE:
888 // OK
889 break;
890 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700891 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 return INVALID_OPERATION;
893 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800894 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700895
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800897}
898
899status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
900 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700901 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800902
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700903 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904}
905
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700906status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800907 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700908 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700909 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700910 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700911 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800912 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
913 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700914
915 status_t res;
916 bool wasActive = false;
917
918 switch (mStatus) {
919 case STATUS_ERROR:
920 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
921 return INVALID_OPERATION;
922 case STATUS_UNINITIALIZED:
923 ALOGE("%s: Device not initialized", __FUNCTION__);
924 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700925 case STATUS_UNCONFIGURED:
926 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700927 // OK
928 break;
929 case STATUS_ACTIVE:
930 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700931 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700932 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700933 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 return res;
935 }
936 wasActive = true;
937 break;
938 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700940 return INVALID_OPERATION;
941 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700942 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700943
944 if (mInputStream != 0) {
945 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
946 return INVALID_OPERATION;
947 }
948
949 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
950 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700951 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700952
953 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800954 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700955
956 *id = mNextStreamId++;
957
958 // Continue captures if active at start
959 if (wasActive) {
960 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100961 // Reuse current operating mode and session parameters for new stream config
962 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700963 if (res != OK) {
964 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
965 __FUNCTION__, mNextStreamId, strerror(-res), res);
966 return res;
967 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700968 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700969 }
970
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800971 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700972 return OK;
973}
974
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700975status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700976 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700977 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800978 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800979 const std::unordered_set<int32_t> &sensorPixelModesUsed,
980 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800981 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700982 ATRACE_CALL();
983
984 if (consumer == nullptr) {
985 ALOGE("%s: consumer must not be null", __FUNCTION__);
986 return BAD_VALUE;
987 }
988
989 std::vector<sp<Surface>> consumers;
990 consumers.push_back(consumer);
991
992 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800993 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800994 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
995 streamUseCase);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800996}
997
998static bool isRawFormat(int format) {
999 switch (format) {
1000 case HAL_PIXEL_FORMAT_RAW16:
1001 case HAL_PIXEL_FORMAT_RAW12:
1002 case HAL_PIXEL_FORMAT_RAW10:
1003 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1004 return true;
1005 default:
1006 return false;
1007 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001008}
1009
1010status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1011 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001012 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001013 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001014 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001015 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001016 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001017
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001018 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001019 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001020 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001021 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001022 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1023 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1024 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001025
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001026 status_t res;
1027 bool wasActive = false;
1028
1029 switch (mStatus) {
1030 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001031 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001032 return INVALID_OPERATION;
1033 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001034 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001035 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001036 case STATUS_UNCONFIGURED:
1037 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001038 // OK
1039 break;
1040 case STATUS_ACTIVE:
1041 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001042 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001043 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001044 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001045 return res;
1046 }
1047 wasActive = true;
1048 break;
1049 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001050 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051 return INVALID_OPERATION;
1052 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001053 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001054
1055 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001056
Shuzhen Wang0129d522016-10-30 22:43:41 -07001057 if (consumers.size() == 0 && !hasDeferredConsumer) {
1058 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1059 return BAD_VALUE;
1060 }
Zhijun He5d677d12016-05-29 16:52:39 -07001061
Shuzhen Wang0129d522016-10-30 22:43:41 -07001062 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001063 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1064 return BAD_VALUE;
1065 }
1066
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001067 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1068 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1069 // be found in only one sensor pixel mode.
1070 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1071 return BAD_VALUE;
1072 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001074 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001075 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001076 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001077 if (blobBufferSize <= 0) {
1078 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1079 return BAD_VALUE;
1080 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001081 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1082 blobBufferSize = width * height;
1083 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001084 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001085 if (blobBufferSize <= 0) {
1086 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1087 return BAD_VALUE;
1088 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001089 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001090 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001091 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001092 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001093 isMultiResolution, dynamicRangeProfile, streamUseCase);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001094 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001095 bool maxResolution =
1096 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1097 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001098 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1099 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001100 if (rawOpaqueBufferSize <= 0) {
1101 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1102 return BAD_VALUE;
1103 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001104 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001105 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001106 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001107 isMultiResolution, dynamicRangeProfile, streamUseCase);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001108 } else if (isShared) {
1109 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1110 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001111 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001112 mUseHalBufManager, dynamicRangeProfile, streamUseCase);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001113 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001114 newStream = new Camera3OutputStream(mNextStreamId,
1115 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001116 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001117 isMultiResolution, dynamicRangeProfile, streamUseCase);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001118 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001119 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001120 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001121 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001122 isMultiResolution, dynamicRangeProfile, streamUseCase);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001123 }
Emilian Peev40ead602017-09-26 15:46:36 +01001124
1125 size_t consumerCount = consumers.size();
1126 for (size_t i = 0; i < consumerCount; i++) {
1127 int id = newStream->getSurfaceId(consumers[i]);
1128 if (id < 0) {
1129 SET_ERR_L("Invalid surface id");
1130 return BAD_VALUE;
1131 }
1132 if (surfaceIds != nullptr) {
1133 surfaceIds->push_back(id);
1134 }
1135 }
1136
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001137 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001138
Emilian Peev08dd2452017-04-06 16:55:14 +01001139 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001140
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001141 newStream->setImageDumpMask(mImageDumpMask);
1142
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001143 res = mOutputStreams.add(mNextStreamId, newStream);
1144 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001145 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001146 return res;
1147 }
1148
Shuzhen Wang316781a2020-08-18 18:11:01 -07001149 mSessionStatsBuilder.addStream(mNextStreamId);
1150
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001151 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001152 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001153
1154 // Continue captures if active at start
1155 if (wasActive) {
1156 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001157 // Reuse current operating mode and session parameters for new stream config
1158 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001159 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001160 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1161 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001162 return res;
1163 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001164 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001165 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001166 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001167 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001168}
1169
Emilian Peev710c1422017-08-30 11:19:38 +01001170status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001171 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001172 if (nullptr == streamInfo) {
1173 return BAD_VALUE;
1174 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001175 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 switch (mStatus) {
1179 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001180 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181 return INVALID_OPERATION;
1182 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001183 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001184 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001185 case STATUS_UNCONFIGURED:
1186 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 case STATUS_ACTIVE:
1188 // OK
1189 break;
1190 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001191 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 return INVALID_OPERATION;
1193 }
1194
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001195 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1196 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001197 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001198 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 }
1200
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001201 streamInfo->width = stream->getWidth();
1202 streamInfo->height = stream->getHeight();
1203 streamInfo->format = stream->getFormat();
1204 streamInfo->dataSpace = stream->getDataSpace();
1205 streamInfo->formatOverridden = stream->isFormatOverridden();
1206 streamInfo->originalFormat = stream->getOriginalFormat();
1207 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1208 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001209 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001211}
1212
1213status_t Camera3Device::setStreamTransform(int id,
1214 int transform) {
1215 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001216 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001218
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 switch (mStatus) {
1220 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001221 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return INVALID_OPERATION;
1223 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001224 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 case STATUS_UNCONFIGURED:
1227 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 case STATUS_ACTIVE:
1229 // OK
1230 break;
1231 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
1234 }
1235
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001236 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1237 if (stream == nullptr) {
1238 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 return BAD_VALUE;
1240 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001241 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001242}
1243
1244status_t Camera3Device::deleteStream(int id) {
1245 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001246 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 Mutex::Autolock l(mLock);
1248 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001250 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001251
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 // CameraDevice semantics require device to already be idle before
1253 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001254 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001255 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001256 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 }
1258
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001259 if (mStatus == STATUS_ERROR) {
1260 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1261 __FUNCTION__, mId.string());
1262 return -EBUSY;
1263 }
1264
Igor Murashkin2fba5842013-04-22 14:03:54 -07001265 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001266 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001267 if (mInputStream != NULL && id == mInputStream->getId()) {
1268 deletedStream = mInputStream;
1269 mInputStream.clear();
1270 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001271 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001272 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001273 return BAD_VALUE;
1274 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001275 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001276 }
1277
1278 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001279 if (stream != nullptr) {
1280 deletedStream = stream;
1281 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 }
1283
1284 // Free up the stream endpoint so that it can be used by some other stream
1285 res = deletedStream->disconnect();
1286 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001287 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001288 // fall through since we want to still list the stream as deleted.
1289 }
1290 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001291 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292
1293 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001294}
1295
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001296status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001297 ATRACE_CALL();
1298 ALOGV("%s: E", __FUNCTION__);
1299
1300 Mutex::Autolock il(mInterfaceLock);
1301 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001302
Emilian Peev811d2952018-05-25 11:08:40 +01001303 // In case the client doesn't include any session parameter, try a
1304 // speculative configuration using the values from the last cached
1305 // default request.
1306 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001307 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001308 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1309 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1310 mLastTemplateId);
1311 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1312 operatingMode);
1313 }
1314
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001315 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1316}
1317
1318status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1319 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001320 //Filter out any incoming session parameters
1321 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001322 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1323 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001324 CameraMetadata filteredParams(availableSessionKeys.count);
1325 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1326 filteredParams.getAndLock());
1327 set_camera_metadata_vendor_id(meta, mVendorTagId);
1328 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001329 if (availableSessionKeys.count > 0) {
1330 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1331 camera_metadata_ro_entry entry = params.find(
1332 availableSessionKeys.data.i32[i]);
1333 if (entry.count > 0) {
1334 filteredParams.update(entry);
1335 }
1336 }
1337 }
1338
1339 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001340}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001342status_t Camera3Device::getInputBufferProducer(
1343 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001344 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001345 Mutex::Autolock il(mInterfaceLock);
1346 Mutex::Autolock l(mLock);
1347
1348 if (producer == NULL) {
1349 return BAD_VALUE;
1350 } else if (mInputStream == NULL) {
1351 return INVALID_OPERATION;
1352 }
1353
1354 return mInputStream->getInputBufferProducer(producer);
1355}
1356
Emilian Peevf4816702020-04-03 15:44:51 -07001357status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001358 CameraMetadata *request) {
1359 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001360 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001361
Emilian Peevf4816702020-04-03 15:44:51 -07001362 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001363 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001364 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001365 return BAD_VALUE;
1366 }
1367
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001368 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001370 {
1371 Mutex::Autolock l(mLock);
1372 switch (mStatus) {
1373 case STATUS_ERROR:
1374 CLOGE("Device has encountered a serious error");
1375 return INVALID_OPERATION;
1376 case STATUS_UNINITIALIZED:
1377 CLOGE("Device is not initialized!");
1378 return INVALID_OPERATION;
1379 case STATUS_UNCONFIGURED:
1380 case STATUS_CONFIGURED:
1381 case STATUS_ACTIVE:
1382 // OK
1383 break;
1384 default:
1385 SET_ERR_L("Unexpected status: %d", mStatus);
1386 return INVALID_OPERATION;
1387 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001388
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001389 if (!mRequestTemplateCache[templateId].isEmpty()) {
1390 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001391 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001392 return OK;
1393 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001394 }
1395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001396 camera_metadata_t *rawRequest;
1397 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001398 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399
1400 {
1401 Mutex::Autolock l(mLock);
1402 if (res == BAD_VALUE) {
1403 ALOGI("%s: template %d is not supported on this camera device",
1404 __FUNCTION__, templateId);
1405 return res;
1406 } else if (res != OK) {
1407 CLOGE("Unable to construct request template %d: %s (%d)",
1408 templateId, strerror(-res), res);
1409 return res;
1410 }
1411
1412 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1413 mRequestTemplateCache[templateId].acquire(rawRequest);
1414
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001415 // Override the template request with zoomRatioMapper
1416 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1417 &mRequestTemplateCache[templateId]);
1418 if (res != OK) {
1419 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1420 templateId, strerror(-res), res);
1421 return res;
1422 }
1423
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001424 // Fill in JPEG_QUALITY if not available
1425 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1426 static const uint8_t kDefaultJpegQuality = 95;
1427 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1428 &kDefaultJpegQuality, 1);
1429 }
1430
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001431 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001432 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001433 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001434 return OK;
1435}
1436
1437status_t Camera3Device::waitUntilDrained() {
1438 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001439 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001440 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001442
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001443 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001444}
1445
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001446status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001447 switch (mStatus) {
1448 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001449 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450 ALOGV("%s: Already idle", __FUNCTION__);
1451 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001452 case STATUS_CONFIGURED:
1453 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 case STATUS_ERROR:
1455 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001456 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457 break;
1458 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001459 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460 return INVALID_OPERATION;
1461 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001462 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1463 maxExpectedDuration);
1464 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001465 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001466 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001467 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1468 res);
1469 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001470 return res;
1471}
1472
Ruben Brunk183f0562015-08-12 12:55:02 -07001473void Camera3Device::internalUpdateStatusLocked(Status status) {
1474 mStatus = status;
1475 mRecentStatusUpdates.add(mStatus);
1476 mStatusChanged.broadcast();
1477}
1478
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001479// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001480status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001481 if (mRequestThread.get() != nullptr) {
1482 mRequestThread->setPaused(true);
1483 } else {
1484 return NO_INIT;
1485 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001486
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001487 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1488 maxExpectedDuration);
1489 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001490 if (res != OK) {
1491 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001492 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 }
1494
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 return res;
1496}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001498// Resume after internalPauseAndWaitLocked
1499status_t Camera3Device::internalResumeLocked() {
1500 status_t res;
1501
1502 mRequestThread->setPaused(false);
1503
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001504 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1505 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1507 if (res != OK) {
1508 SET_ERR_L("Can't transition to active in %f seconds!",
1509 kActiveTimeout/1e9);
1510 }
1511 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513}
1514
Ruben Brunk183f0562015-08-12 12:55:02 -07001515status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001517
1518 size_t startIndex = 0;
1519 if (mStatusWaiters == 0) {
1520 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1521 // this status list
1522 mRecentStatusUpdates.clear();
1523 } else {
1524 // If other threads are waiting on updates to this status list, set the position of the
1525 // first element that this list will check rather than clearing the list.
1526 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001527 }
1528
Ruben Brunk183f0562015-08-12 12:55:02 -07001529 mStatusWaiters++;
1530
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001531 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001532 if (!active && mUseHalBufManager) {
1533 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001534 if (mStatus == STATUS_ACTIVE) {
1535 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001536 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001537 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001538 mRequestBufferSM.onWaitUntilIdle();
1539 }
1540
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 bool stateSeen = false;
1542 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001543 if (active == (mStatus == STATUS_ACTIVE)) {
1544 // Desired state is current
1545 break;
1546 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547
1548 res = mStatusChanged.waitRelative(mLock, timeout);
1549 if (res != OK) break;
1550
Ruben Brunk183f0562015-08-12 12:55:02 -07001551 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1552 // transitions.
1553 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1554 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1555 __FUNCTION__);
1556
1557 // Encountered desired state since we began waiting
1558 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1560 stateSeen = true;
1561 break;
1562 }
1563 }
1564 } while (!stateSeen);
1565
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001566 if (signalPipelineDrain) {
1567 mRequestThread->resetPipelineDrain();
1568 }
1569
Ruben Brunk183f0562015-08-12 12:55:02 -07001570 mStatusWaiters--;
1571
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 return res;
1573}
1574
1575
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001576status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001578 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001579
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001580 if (listener != NULL && mListener != NULL) {
1581 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1582 }
1583 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001584 mRequestThread->setNotificationListener(listener);
1585 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001586
1587 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588}
1589
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001590bool Camera3Device::willNotify3A() {
1591 return false;
1592}
1593
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001594status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001595 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001596 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001597
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001598 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001599 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1600 if (st == std::cv_status::timeout) {
1601 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001602 }
1603 }
1604 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001605}
1606
Jianing Weicb0652e2014-03-12 18:29:36 -07001607status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001609 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001611 if (mResultQueue.empty()) {
1612 return NOT_ENOUGH_DATA;
1613 }
1614
Jianing Weicb0652e2014-03-12 18:29:36 -07001615 if (frame == NULL) {
1616 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1617 return BAD_VALUE;
1618 }
1619
1620 CaptureResult &result = *(mResultQueue.begin());
1621 frame->mResultExtras = result.mResultExtras;
1622 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001623 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001624 mResultQueue.erase(mResultQueue.begin());
1625
1626 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001627}
1628
1629status_t Camera3Device::triggerAutofocus(uint32_t id) {
1630 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001632
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001633 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1634 // Mix-in this trigger into the next request and only the next request.
1635 RequestTrigger trigger[] = {
1636 {
1637 ANDROID_CONTROL_AF_TRIGGER,
1638 ANDROID_CONTROL_AF_TRIGGER_START
1639 },
1640 {
1641 ANDROID_CONTROL_AF_TRIGGER_ID,
1642 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001643 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001644 };
1645
1646 return mRequestThread->queueTrigger(trigger,
1647 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001648}
1649
1650status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1651 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001652 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001653
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001654 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1655 // Mix-in this trigger into the next request and only the next request.
1656 RequestTrigger trigger[] = {
1657 {
1658 ANDROID_CONTROL_AF_TRIGGER,
1659 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1660 },
1661 {
1662 ANDROID_CONTROL_AF_TRIGGER_ID,
1663 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001664 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001665 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001666
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001667 return mRequestThread->queueTrigger(trigger,
1668 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001669}
1670
1671status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1672 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001675 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1676 // Mix-in this trigger into the next request and only the next request.
1677 RequestTrigger trigger[] = {
1678 {
1679 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1680 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1681 },
1682 {
1683 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1684 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001685 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001687
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001688 return mRequestThread->queueTrigger(trigger,
1689 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001690}
1691
Jianing Weicb0652e2014-03-12 18:29:36 -07001692status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001693 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001694 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001695 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001696
Zhijun He7ef20392014-04-21 16:04:17 -07001697 {
1698 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001699
1700 // b/116514106 "disconnect()" can get called twice for the same device. The
1701 // camera device will not be initialized during the second run.
1702 if (mStatus == STATUS_UNINITIALIZED) {
1703 return OK;
1704 }
1705
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001706 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001707
1708 // Stop session and stream counter
1709 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001710 }
1711
Emilian Peev08dd2452017-04-06 16:55:14 +01001712 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001713}
1714
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001715status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001716 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1717}
1718
1719status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001720 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001721 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001722 Mutex::Autolock il(mInterfaceLock);
1723 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001724
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001725 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1726 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001727 CLOGE("Stream %d does not exist", streamId);
1728 return BAD_VALUE;
1729 }
1730
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001731 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001732 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001733 return BAD_VALUE;
1734 }
1735
1736 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001737 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001738 return BAD_VALUE;
1739 }
1740
Ruben Brunkc78ac262015-08-13 17:58:46 -07001741 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001742}
1743
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001744status_t Camera3Device::tearDown(int streamId) {
1745 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001746 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001747 Mutex::Autolock il(mInterfaceLock);
1748 Mutex::Autolock l(mLock);
1749
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001750 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1751 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001752 CLOGE("Stream %d does not exist", streamId);
1753 return BAD_VALUE;
1754 }
1755
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001756 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1757 CLOGE("Stream %d is a target of a in-progress request", streamId);
1758 return BAD_VALUE;
1759 }
1760
1761 return stream->tearDown();
1762}
1763
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001764status_t Camera3Device::addBufferListenerForStream(int streamId,
1765 wp<Camera3StreamBufferListener> listener) {
1766 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001767 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001768 Mutex::Autolock il(mInterfaceLock);
1769 Mutex::Autolock l(mLock);
1770
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001771 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1772 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001773 CLOGE("Stream %d does not exist", streamId);
1774 return BAD_VALUE;
1775 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001776 stream->addBufferListener(listener);
1777
1778 return OK;
1779}
1780
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001782 * Methods called by subclasses
1783 */
1784
1785void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001786 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001787 std::vector<int> streamIds;
1788 std::vector<hardware::CameraStreamStats> streamStats;
1789
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001790 {
1791 // Need mLock to safely update state and synchronize to current
1792 // state of methods in flight.
1793 Mutex::Autolock l(mLock);
1794 // We can get various system-idle notices from the status tracker
1795 // while starting up. Only care about them if we've actually sent
1796 // in some requests recently.
1797 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1798 return;
1799 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001800 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1801 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001802 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803
1804 // Skip notifying listener if we're doing some user-transparent
1805 // state changes
1806 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001807
1808 // Populate stream statistics in case of Idle
1809 if (idle) {
1810 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1811 auto stream = mOutputStreams[i];
1812 if (stream.get() == nullptr) continue;
1813 streamIds.push_back(stream->getId());
1814 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1815 int64_t usage = 0LL;
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001816 int streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001817 if (camera3Stream != nullptr) {
1818 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001819 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001820 }
1821 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1822 stream->getFormat(), stream->getDataSpace(), usage,
1823 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001824 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001825 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001826 }
1827 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001829
1830 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001832 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001833 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001834 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001835 status_t res = OK;
1836 if (listener != nullptr) {
1837 if (idle) {
1838 // Get session stats from the builder, and notify the listener.
1839 int64_t requestCount, resultErrorCount;
1840 bool deviceError;
1841 std::map<int, StreamStats> streamStatsMap;
1842 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1843 &deviceError, &streamStatsMap);
1844 for (size_t i = 0; i < streamIds.size(); i++) {
1845 int streamId = streamIds[i];
1846 auto stats = streamStatsMap.find(streamId);
1847 if (stats != streamStatsMap.end()) {
1848 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1849 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1850 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1851 streamStats[i].mHistogramType =
1852 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1853 streamStats[i].mHistogramBins.assign(
1854 stats->second.mCaptureLatencyBins.begin(),
1855 stats->second.mCaptureLatencyBins.end());
1856 streamStats[i].mHistogramCounts.assign(
1857 stats->second.mCaptureLatencyHistogram.begin(),
1858 stats->second.mCaptureLatencyHistogram.end());
1859 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001860 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001861 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1862 } else {
1863 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001864 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001865 }
1866 if (res != OK) {
1867 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1868 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 }
1870}
1871
Shuzhen Wang758c2152017-01-10 18:26:18 -08001872status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001873 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001874 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001875 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1876 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001877
1878 if (surfaceIds == nullptr) {
1879 return BAD_VALUE;
1880 }
1881
Zhijun He5d677d12016-05-29 16:52:39 -07001882 Mutex::Autolock il(mInterfaceLock);
1883 Mutex::Autolock l(mLock);
1884
Shuzhen Wang758c2152017-01-10 18:26:18 -08001885 if (consumers.size() == 0) {
1886 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001887 return BAD_VALUE;
1888 }
1889
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001890 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1891 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001892 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001893 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001894 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001895
1896 // isConsumerConfigurationDeferred will be off after setConsumers
1897 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001898 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001899 if (res != OK) {
1900 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1901 return res;
1902 }
1903
Emilian Peev40ead602017-09-26 15:46:36 +01001904 for (auto &consumer : consumers) {
1905 int id = stream->getSurfaceId(consumer);
1906 if (id < 0) {
1907 CLOGE("Invalid surface id!");
1908 return BAD_VALUE;
1909 }
1910 surfaceIds->push_back(id);
1911 }
1912
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001913 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001914 if (!stream->isConfiguring()) {
1915 CLOGE("Stream %d was already fully configured.", streamId);
1916 return INVALID_OPERATION;
1917 }
Zhijun He5d677d12016-05-29 16:52:39 -07001918
Shuzhen Wang0129d522016-10-30 22:43:41 -07001919 res = stream->finishConfiguration();
1920 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001921 // If finishConfiguration fails due to abandoned surface, do not set
1922 // device to error state.
1923 bool isSurfaceAbandoned =
1924 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1925 if (!isSurfaceAbandoned) {
1926 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1927 stream->getId(), strerror(-res), res);
1928 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001929 return res;
1930 }
Zhijun He5d677d12016-05-29 16:52:39 -07001931 }
1932
1933 return OK;
1934}
1935
Emilian Peev40ead602017-09-26 15:46:36 +01001936status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1937 const std::vector<OutputStreamInfo> &outputInfo,
1938 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1939 Mutex::Autolock il(mInterfaceLock);
1940 Mutex::Autolock l(mLock);
1941
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001942 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1943 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001944 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001945 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001946 }
1947
1948 for (const auto &it : removedSurfaceIds) {
1949 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1950 CLOGE("Shared surface still part of a pending request!");
1951 return -EBUSY;
1952 }
1953 }
1954
Emilian Peev40ead602017-09-26 15:46:36 +01001955 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1956 if (res != OK) {
1957 CLOGE("Stream %d failed to update stream (error %d %s) ",
1958 streamId, res, strerror(-res));
1959 if (res == UNKNOWN_ERROR) {
1960 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1961 __FUNCTION__);
1962 }
1963 return res;
1964 }
1965
1966 return res;
1967}
1968
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001969status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1970 Mutex::Autolock il(mInterfaceLock);
1971 Mutex::Autolock l(mLock);
1972
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001973 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1974 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001975 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1976 return BAD_VALUE;
1977 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001978
1979 if (dropping) {
1980 mSessionStatsBuilder.stopCounter(streamId);
1981 } else {
1982 mSessionStatsBuilder.startCounter(streamId);
1983 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001984 return stream->dropBuffers(dropping);
1985}
1986
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001987/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988 * Camera3Device private methods
1989 */
1990
1991sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00001992 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001994
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001995 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00001996 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001997
1998 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00001999 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002000 if (inputStreams.count > 0) {
2001 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002002 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002003 CLOGE("Request references unknown input stream %d",
2004 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002005 return NULL;
2006 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002007
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002008 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002009 SET_ERR_L("%s: input stream %d is not configured!",
2010 __FUNCTION__, mInputStream->getId());
2011 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002012 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002013 // Check if stream prepare is blocking requests.
2014 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002015 CLOGE("Request references an input stream that's being prepared!");
2016 return NULL;
2017 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002018
2019 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002020 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002021 }
2022
2023 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002024 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002025 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002026 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027 return NULL;
2028 }
2029
2030 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002031 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2032 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002033 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002034 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002035 return NULL;
2036 }
Zhijun He5d677d12016-05-29 16:52:39 -07002037 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002038 auto iter = surfaceMap.find(streams.data.i32[i]);
2039 if (iter != surfaceMap.end()) {
2040 const std::vector<size_t>& surfaces = iter->second;
2041 for (const auto& surface : surfaces) {
2042 if (stream->isConsumerConfigurationDeferred(surface)) {
2043 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2044 "due to deferred consumer", stream->getId(), surface);
2045 return NULL;
2046 }
2047 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002048 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002049 }
2050
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002052 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2053 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002054 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002055 // Check if stream prepare is blocking requests.
2056 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002057 CLOGE("Request references an output stream that's being prepared!");
2058 return NULL;
2059 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002060
2061 newRequest->mOutputStreams.push(stream);
2062 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002063 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002064 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002066 auto rotateAndCropEntry =
2067 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2068 if (rotateAndCropEntry.count > 0 &&
2069 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2070 newRequest->mRotateAndCropAuto = true;
2071 } else {
2072 newRequest->mRotateAndCropAuto = false;
2073 }
2074
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002075 auto zoomRatioEntry =
2076 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2077 if (zoomRatioEntry.count > 0 &&
2078 zoomRatioEntry.data.f[0] == 1.0f) {
2079 newRequest->mZoomRatioIs1x = true;
2080 } else {
2081 newRequest->mZoomRatioIs1x = false;
2082 }
2083
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002084 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002085 for (auto& settings : newRequest->mSettingsList) {
2086 auto testPatternModeEntry =
2087 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2088 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2089 testPatternModeEntry.data.i32[0] :
2090 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002091
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002092 auto testPatternDataEntry =
2093 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2094 if (testPatternDataEntry.count >= 4) {
2095 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2096 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2097 } else {
2098 settings.mOriginalTestPatternData[0] = 0;
2099 settings.mOriginalTestPatternData[1] = 0;
2100 settings.mOriginalTestPatternData[2] = 0;
2101 settings.mOriginalTestPatternData[3] = 0;
2102 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002103 }
2104 }
2105
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002106 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002107}
2108
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002109void Camera3Device::cancelStreamsConfigurationLocked() {
2110 int res = OK;
2111 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2112 res = mInputStream->cancelConfiguration();
2113 if (res != OK) {
2114 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2115 mInputStream->getId(), strerror(-res), res);
2116 }
2117 }
2118
2119 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002120 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002121 if (outputStream->isConfiguring()) {
2122 res = outputStream->cancelConfiguration();
2123 if (res != OK) {
2124 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2125 outputStream->getId(), strerror(-res), res);
2126 }
2127 }
2128 }
2129
2130 // Return state to that at start of call, so that future configures
2131 // properly clean things up
2132 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2133 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002134
2135 res = mPreparerThread->resume();
2136 if (res != OK) {
2137 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2138 }
2139}
2140
Emilian Peev0d0191e2020-04-21 17:01:18 -07002141bool Camera3Device::checkAbandonedStreamsLocked() {
2142 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2143 return true;
2144 }
2145
2146 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2147 auto stream = mOutputStreams[i];
2148 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2149 return true;
2150 }
2151 }
2152
2153 return false;
2154}
2155
Emilian Peev3bead5f2020-05-28 17:29:08 -07002156bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002157 ATRACE_CALL();
2158 bool ret = false;
2159
Shuzhen Wang316781a2020-08-18 18:11:01 -07002160 nsecs_t startTime = systemTime();
2161
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002162 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002163 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2164
2165 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002166 if (checkAbandonedStreamsLocked()) {
2167 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2168 __FUNCTION__);
2169 return true;
2170 }
2171
Emilian Peev3bead5f2020-05-28 17:29:08 -07002172 status_t rc = NO_ERROR;
2173 bool markClientActive = false;
2174 if (mStatus == STATUS_ACTIVE) {
2175 markClientActive = true;
2176 mPauseStateNotify = true;
2177 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2178
2179 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2180 }
2181
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002182 if (rc == NO_ERROR) {
2183 mNeedConfig = true;
2184 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2185 if (rc == NO_ERROR) {
2186 ret = true;
2187 mPauseStateNotify = false;
2188 //Moving to active state while holding 'mLock' is important.
2189 //There could be pending calls to 'create-/deleteStream' which
2190 //will trigger another stream configuration while the already
2191 //present streams end up with outstanding buffers that will
2192 //not get drained.
2193 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002194 } else if (rc == DEAD_OBJECT) {
2195 // DEAD_OBJECT can be returned if either the consumer surface is
2196 // abandoned, or the HAL has died.
2197 // - If the HAL has died, configureStreamsLocked call will set
2198 // device to error state,
2199 // - If surface is abandoned, we should not set device to error
2200 // state.
2201 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002202 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002203 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002204 }
2205 } else {
2206 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2207 }
2208
Shuzhen Wang316781a2020-08-18 18:11:01 -07002209 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2210 ns2ms(systemTime() - startTime));
2211
Emilian Peev3bead5f2020-05-28 17:29:08 -07002212 if (markClientActive) {
2213 mStatusTracker->markComponentActive(clientStatusId);
2214 }
2215
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002216 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002217}
2218
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002219status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002220 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002221 ATRACE_CALL();
2222 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002223
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002225 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002226 return INVALID_OPERATION;
2227 }
2228
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002229 if (operatingMode < 0) {
2230 CLOGE("Invalid operating mode: %d", operatingMode);
2231 return BAD_VALUE;
2232 }
2233
2234 bool isConstrainedHighSpeed =
2235 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2236 operatingMode;
2237
2238 if (mOperatingMode != operatingMode) {
2239 mNeedConfig = true;
2240 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2241 mOperatingMode = operatingMode;
2242 }
2243
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002244 // In case called from configureStreams, abort queued input buffers not belonging to
2245 // any pending requests.
2246 if (mInputStream != NULL && notifyRequestThread) {
2247 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002248 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002249 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002250 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002251 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002252 if (res != OK) {
2253 // Exhausted acquiring all input buffers.
2254 break;
2255 }
2256
Emilian Peevf4816702020-04-03 15:44:51 -07002257 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002258 res = mInputStream->returnInputBuffer(inputBuffer);
2259 if (res != OK) {
2260 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2261 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2262 }
2263 }
2264 }
2265
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002266 if (!mNeedConfig) {
2267 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2268 return OK;
2269 }
2270
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002271 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002272 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002273 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2274 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002275 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002276 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002277 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002278 }
2279
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002280 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002281 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002282
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002283 mPreparerThread->pause();
2284
Emilian Peevf4816702020-04-03 15:44:51 -07002285 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002286 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002288 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289
Emilian Peevf4816702020-04-03 15:44:51 -07002290 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002292 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002293
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294
2295 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002296 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297 inputStream = mInputStream->startConfiguration();
2298 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002299 CLOGE("Can't start input stream configuration");
2300 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 return INVALID_OPERATION;
2302 }
2303 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002304
2305 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 }
2307
Shuzhen Wang99080502021-03-07 21:08:20 -08002308 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002309 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002311
2312 // Don't configure bidi streams twice, nor add them twice to the list
2313 if (mOutputStreams[i].get() ==
2314 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2315
2316 config.num_streams--;
2317 continue;
2318 }
2319
Emilian Peevf4816702020-04-03 15:44:51 -07002320 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002321 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002322 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002323 CLOGE("Can't start output stream configuration");
2324 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325 return INVALID_OPERATION;
2326 }
2327 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002328
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002329 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002330 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2331 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002332 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2333 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002334 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2335 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002336 } else if (outputStream->data_space ==
2337 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2338 bufferSizes[k] = outputStream->width * outputStream->height;
2339 } else {
2340 ALOGW("%s: Blob dataSpace %d not supported",
2341 __FUNCTION__, outputStream->data_space);
2342 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002343 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002344
2345 if (mOutputStreams[i]->isMultiResolution()) {
2346 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2347 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2348 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2349 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002350
2351 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2352 composerSurfacePresent = true;
2353 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 }
2355
2356 config.streams = streams.editArray();
2357
2358 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002359 // max_buffers, usage, and priv fields, as well as data_space and format
2360 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002361
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002362 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002363 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002364 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002366 if (res == BAD_VALUE) {
2367 // HAL rejected this set of streams as unsupported, clean up config
2368 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002369 CLOGE("Set of requested inputs/outputs not supported by HAL");
2370 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002371 return BAD_VALUE;
2372 } else if (res != OK) {
2373 // Some other kind of error from configure_streams - this is not
2374 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002375 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2376 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002377 return res;
2378 }
2379
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002380 // Finish all stream configuration immediately.
2381 // TODO: Try to relax this later back to lazy completion, which should be
2382 // faster
2383
Igor Murashkin073f8572013-05-02 14:59:28 -07002384 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002385 bool streamReConfigured = false;
2386 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002387 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002388 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002389 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002390 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002391 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2392 return DEAD_OBJECT;
2393 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002394 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002395 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002396 if (streamReConfigured) {
2397 mInterface->onStreamReConfigured(mInputStream->getId());
2398 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002399 }
2400
2401 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002402 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002403 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002404 bool streamReConfigured = false;
2405 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002406 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002407 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002408 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002409 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002410 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2411 return DEAD_OBJECT;
2412 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002413 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002414 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002415 if (streamReConfigured) {
2416 mInterface->onStreamReConfigured(outputStream->getId());
2417 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002418 }
2419 }
2420
Emilian Peeve23f1d92021-09-20 14:56:01 -07002421 mRequestThread->setComposerSurface(composerSurfacePresent);
2422
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423 // Request thread needs to know to avoid using repeat-last-settings protocol
2424 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002425 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002426 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2427 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002428 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002429
Zhijun He90f7c372016-08-16 16:19:43 -07002430 char value[PROPERTY_VALUE_MAX];
2431 property_get("camera.fifo.disable", value, "0");
2432 int32_t disableFifo = atoi(value);
2433 if (disableFifo != 1) {
2434 // Boost priority of request thread to SCHED_FIFO.
2435 pid_t requestThreadTid = mRequestThread->getTid();
2436 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002437 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002438 if (res != OK) {
2439 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2440 strerror(-res), res);
2441 } else {
2442 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2443 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002444 }
2445
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002446 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002447 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2448 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2449 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2450 sessionParams.unlock(newSessionParams);
2451 mSessionParams.unlock(currentSessionParams);
2452 if (updateSessionParams) {
2453 mSessionParams = sessionParams;
2454 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002455
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002456 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002458 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002459 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002460
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002461 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002462
Zhijun He0a210512014-07-24 13:45:15 -07002463 // tear down the deleted streams after configure streams.
2464 mDeletedStreams.clear();
2465
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002466 auto rc = mPreparerThread->resume();
2467 if (rc != OK) {
2468 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2469 return rc;
2470 }
2471
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002472 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002473 mRequestBufferSM.onStreamsConfigured();
2474 }
2475
Cliff Wu3b268182021-07-06 15:44:43 +08002476 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002477 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002478 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002479 // configure the injection streams.
2480 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002481 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002482 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2483 res = mInjectionMethods->injectCamera(config, bufferSizes);
2484 if (res != OK) {
2485 ALOGE("Can't finish inject camera process!");
2486 return res;
2487 }
Cliff Wu3b268182021-07-06 15:44:43 +08002488 } else {
2489 // First run configureStreamsLocked() and then call injectCamera() case:
2490 // If the stream configuration has been completed and camera deive is active, but the
2491 // injection camera has not been injected yet, we need to store the stream configuration of
2492 // the internal camera (because the stream configuration of the injection camera is based
2493 // on the internal camera). When injecting occurs later, this configuration can be used by
2494 // the injection camera.
2495 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2496 " injection camera has not been injected yet.", __FUNCTION__);
2497 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002498 }
2499
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002500 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002501}
2502
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002503status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002504 ATRACE_CALL();
2505 status_t res;
2506
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002507 if (mFakeStreamId != NO_STREAM) {
2508 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002509 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002510 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002511 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002512 return INVALID_OPERATION;
2513 }
2514
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002515 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002516
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002517 sp<Camera3OutputStreamInterface> fakeStream =
2518 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002519
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002520 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002521 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002522 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002523 return res;
2524 }
2525
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002526 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002527 mNextStreamId++;
2528
2529 return OK;
2530}
2531
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002532status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002533 ATRACE_CALL();
2534 status_t res;
2535
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002536 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002537 if (mOutputStreams.size() == 1) return OK;
2538
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002539 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002540
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002541 // Ok, have a fake stream and there's at least one other output stream,
2542 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002543
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002544 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002545 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002546 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002547 return INVALID_OPERATION;
2548 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002549 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002550
2551 // Free up the stream endpoint so that it can be used by some other stream
2552 res = deletedStream->disconnect();
2553 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002554 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002555 // fall through since we want to still list the stream as deleted.
2556 }
2557 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002558 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002559
2560 return res;
2561}
2562
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002563void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002564 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002565 Mutex::Autolock l(mLock);
2566 va_list args;
2567 va_start(args, fmt);
2568
2569 setErrorStateLockedV(fmt, args);
2570
2571 va_end(args);
2572}
2573
2574void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002575 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002576 Mutex::Autolock l(mLock);
2577 setErrorStateLockedV(fmt, args);
2578}
2579
2580void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2581 va_list args;
2582 va_start(args, fmt);
2583
2584 setErrorStateLockedV(fmt, args);
2585
2586 va_end(args);
2587}
2588
2589void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002590 // Print out all error messages to log
2591 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002592 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002593
2594 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002595 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002596
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002597 mErrorCause = errorCause;
2598
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002599 if (mRequestThread != nullptr) {
2600 mRequestThread->setPaused(true);
2601 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002602 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002603
2604 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002605 sp<NotificationListener> listener = mListener.promote();
2606 if (listener != NULL) {
2607 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002608 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002609 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002610 }
2611
2612 // Save stack trace. View by dumping it later.
2613 CameraTraces::saveTrace();
2614 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002615}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616
2617/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002618 * In-flight request management
2619 */
2620
Jianing Weicb0652e2014-03-12 18:29:36 -07002621status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002622 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002623 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002624 const std::set<std::set<String8>>& physicalCameraIds,
2625 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2626 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002627 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002628 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002629 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002630
2631 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002632 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002633 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002634 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002635 if (res < 0) return res;
2636
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002637 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002638 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2639 // avoid a deadlock during reprocess requests.
2640 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002641 if (mStatusTracker != nullptr) {
2642 mStatusTracker->markComponentActive(mInFlightStatusId);
2643 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002644 }
2645
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002646 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002647 return OK;
2648}
2649
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002650void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002651 // Indicate idle inFlightMap to the status tracker
2652 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002653 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002654 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2655 // avoid a deadlock during reprocess requests.
2656 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002657 if (mStatusTracker != nullptr) {
2658 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2659 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002660 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002661 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002662}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002663
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002664void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002665 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002666 // something has likely gone wrong. This might still be legit only if application send in
2667 // a long burst of long exposure requests.
2668 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2669 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2670 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2671 mInFlightMap.size(), mExpectedInflightDuration);
2672 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2673 kInFlightWarnLimitHighSpeed) {
2674 CLOGW("In-flight list too large for high speed configuration: %zu,"
2675 "total inflight duration %" PRIu64,
2676 mInFlightMap.size(), mExpectedInflightDuration);
2677 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002678 }
2679}
2680
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002681void Camera3Device::onInflightMapFlushedLocked() {
2682 mExpectedInflightDuration = 0;
2683}
2684
2685void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002686 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002687 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2688 mInFlightMap.removeItemsAt(idx, 1);
2689
2690 onInflightEntryRemovedLocked(duration);
2691}
2692
2693
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002694void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002695 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002696 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002697 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002698 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002699 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002700 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002701
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002702 FlushInflightReqStates states {
2703 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002704 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002705
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002706 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002707}
2708
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002709CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002710 ALOGV("%s", __FUNCTION__);
2711
Igor Murashkin1e479c02013-09-06 16:55:14 -07002712 CameraMetadata retVal;
2713
2714 if (mRequestThread != NULL) {
2715 retVal = mRequestThread->getLatestRequest();
2716 }
2717
Igor Murashkin1e479c02013-09-06 16:55:14 -07002718 return retVal;
2719}
2720
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002721void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002722 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002723 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002724 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2725 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002726
2727 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002728 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002729}
2730
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002731/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002732 * HalInterface inner class methods
2733 */
2734
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002735void Camera3Device::HalInterface::cleanupNativeHandles(
2736 std::vector<native_handle_t*> *handles, bool closeFd) {
2737 if (handles == nullptr) {
2738 return;
2739 }
2740 if (closeFd) {
2741 for (auto& handle : *handles) {
2742 native_handle_close(handle);
2743 }
2744 }
2745 for (auto& handle : *handles) {
2746 native_handle_delete(handle);
2747 }
2748 handles->clear();
2749 return;
2750}
2751
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002752void Camera3Device::HalInterface::getInflightBufferKeys(
2753 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002754 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002755 return;
2756}
2757
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002758void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2759 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002760 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002761 return;
2762}
2763
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002764bool Camera3Device::HalInterface::verifyBufferIds(
2765 int32_t streamId, std::vector<uint64_t>& bufIds) {
2766 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002767}
2768
2769status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002770 int32_t frameNumber, int32_t streamId,
2771 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002772 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002773}
2774
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002775status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002776 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002777 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002778}
2779
2780// Find and pop a buffer_handle_t based on bufferId
2781status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002782 uint64_t bufferId,
2783 /*out*/ buffer_handle_t** buffer,
2784 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002785 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002786}
2787
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002788std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2789 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002790 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002791}
2792
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002793uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2794 const native_handle_t* handle) {
2795 return mBufferRecords.removeOneBufferCache(streamId, handle);
2796}
2797
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002798void Camera3Device::HalInterface::onBufferFreed(
2799 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002800 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2801 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2802 if (bufferId != BUFFER_ID_NO_BUFFER) {
2803 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002804 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002805}
2806
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002807void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002808 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2809 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2810 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002811 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2812 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002813}
2814
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002815/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002816 * RequestThread inner class methods
2817 */
2818
2819Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002820 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002821 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002822 bool useHalBufManager,
2823 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002824 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002826 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002827 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002828 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002829 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002830 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002831 mReconfigured(false),
2832 mDoPause(false),
2833 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002834 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002835 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002836 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002837 mCurrentAfTriggerId(0),
2838 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002839 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002840 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002841 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002842 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002843 mRepeatingLastFrameNumber(
2844 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002845 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002846 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002847 mRequestLatency(kRequestLatencyBinSize),
2848 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002849 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002850 mUseHalBufManager(useHalBufManager),
2851 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002852 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853}
2854
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002855Camera3Device::RequestThread::~RequestThread() {}
2856
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002857void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002858 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002859 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002860 Mutex::Autolock l(mRequestLock);
2861 mListener = listener;
2862}
2863
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002864void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002865 const CameraMetadata& sessionParams,
2866 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002867 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002868 Mutex::Autolock l(mRequestLock);
2869 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002870 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002871 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002872 // Prepare video stream for high speed recording.
2873 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002874 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002875}
2876
Jianing Wei90e59c92014-03-12 18:29:36 -07002877status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002878 List<sp<CaptureRequest> > &requests,
2879 /*out*/
2880 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002881 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002882 Mutex::Autolock l(mRequestLock);
2883 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2884 ++it) {
2885 mRequestQueue.push_back(*it);
2886 }
2887
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002888 if (lastFrameNumber != NULL) {
2889 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2890 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2891 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2892 *lastFrameNumber);
2893 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002894
Jianing Wei90e59c92014-03-12 18:29:36 -07002895 unpauseForNewRequests();
2896
2897 return OK;
2898}
2899
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002900
2901status_t Camera3Device::RequestThread::queueTrigger(
2902 RequestTrigger trigger[],
2903 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002904 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002905 Mutex::Autolock l(mTriggerMutex);
2906 status_t ret;
2907
2908 for (size_t i = 0; i < count; ++i) {
2909 ret = queueTriggerLocked(trigger[i]);
2910
2911 if (ret != OK) {
2912 return ret;
2913 }
2914 }
2915
2916 return OK;
2917}
2918
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2920 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002921 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922 if (d != nullptr) return d->mId;
2923 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002924}
2925
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002926status_t Camera3Device::RequestThread::queueTriggerLocked(
2927 RequestTrigger trigger) {
2928
2929 uint32_t tag = trigger.metadataTag;
2930 ssize_t index = mTriggerMap.indexOfKey(tag);
2931
2932 switch (trigger.getTagType()) {
2933 case TYPE_BYTE:
2934 // fall-through
2935 case TYPE_INT32:
2936 break;
2937 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002938 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2939 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002940 return INVALID_OPERATION;
2941 }
2942
2943 /**
2944 * Collect only the latest trigger, since we only have 1 field
2945 * in the request settings per trigger tag, and can't send more than 1
2946 * trigger per request.
2947 */
2948 if (index != NAME_NOT_FOUND) {
2949 mTriggerMap.editValueAt(index) = trigger;
2950 } else {
2951 mTriggerMap.add(tag, trigger);
2952 }
2953
2954 return OK;
2955}
2956
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002957status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002958 const RequestList &requests,
2959 /*out*/
2960 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002961 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002962 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002963 if (lastFrameNumber != NULL) {
2964 *lastFrameNumber = mRepeatingLastFrameNumber;
2965 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002966 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002967 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002968 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2969 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002970
2971 unpauseForNewRequests();
2972
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002973 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974 return OK;
2975}
2976
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002977bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002978 if (mRepeatingRequests.empty()) {
2979 return false;
2980 }
2981 int32_t requestId = requestIn->mResultExtras.requestId;
2982 const RequestList &repeatRequests = mRepeatingRequests;
2983 // All repeating requests are guaranteed to have same id so only check first quest
2984 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2985 return (firstRequest->mResultExtras.requestId == requestId);
2986}
2987
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002988status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002989 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002990 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07002991 return clearRepeatingRequestsLocked(lastFrameNumber);
2992
2993}
2994
2995status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08002996 std::vector<int32_t> streamIds;
2997 for (const auto& request : mRepeatingRequests) {
2998 for (const auto& stream : request->mOutputStreams) {
2999 streamIds.push_back(stream->getId());
3000 }
3001 }
3002
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003003 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003004 if (lastFrameNumber != NULL) {
3005 *lastFrameNumber = mRepeatingLastFrameNumber;
3006 }
Emilian Peev2295df72021-11-12 18:14:10 -08003007
3008 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3009
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003011 return OK;
3012}
3013
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003014status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003015 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003016 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003017 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003018 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003019
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003020 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003021
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003022 // Send errors for all requests pending in the request queue, including
3023 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003024 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003025 if (listener != NULL) {
3026 for (RequestList::iterator it = mRequestQueue.begin();
3027 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003028 // Abort the input buffers for reprocess requests.
3029 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003030 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003031 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003032 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003033 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003034 if (res != OK) {
3035 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3036 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3037 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003038 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003039 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3040 if (res != OK) {
3041 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3042 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3043 }
3044 }
3045 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003046 // Set the frame number this request would have had, if it
3047 // had been submitted; this frame number will not be reused.
3048 // The requestId and burstId fields were set when the request was
3049 // submitted originally (in convertMetadataListToRequestListLocked)
3050 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003052 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003053 }
3054 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003055 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003056
3057 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003058 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003059 if (lastFrameNumber != NULL) {
3060 *lastFrameNumber = mRepeatingLastFrameNumber;
3061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003062 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003063 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003064 return OK;
3065}
3066
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003067status_t Camera3Device::RequestThread::flush() {
3068 ATRACE_CALL();
3069 Mutex::Autolock l(mFlushLock);
3070
Emilian Peev08dd2452017-04-06 16:55:14 +01003071 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003072}
3073
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003074void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003075 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003076 Mutex::Autolock l(mPauseLock);
3077 mDoPause = paused;
3078 mDoPauseSignal.signal();
3079}
3080
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003081status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3082 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003083 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003084 Mutex::Autolock l(mLatestRequestMutex);
3085 status_t res;
3086 while (mLatestRequestId != requestId) {
3087 nsecs_t startTime = systemTime();
3088
3089 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3090 if (res != OK) return res;
3091
3092 timeout -= (systemTime() - startTime);
3093 }
3094
3095 return OK;
3096}
3097
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003098void Camera3Device::RequestThread::requestExit() {
3099 // Call parent to set up shutdown
3100 Thread::requestExit();
3101 // The exit from any possible waits
3102 mDoPauseSignal.signal();
3103 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003104
3105 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3106 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003107}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003108
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003109void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003110 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003111 bool surfaceAbandoned = false;
3112 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003113 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003114 {
3115 Mutex::Autolock l(mRequestLock);
3116 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3117 // repeating requests.
3118 for (const auto& request : mRepeatingRequests) {
3119 for (const auto& s : request->mOutputStreams) {
3120 if (s->isAbandoned()) {
3121 surfaceAbandoned = true;
3122 clearRepeatingRequestsLocked(&lastFrameNumber);
3123 break;
3124 }
3125 }
3126 if (surfaceAbandoned) {
3127 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003128 }
3129 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003130 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003131 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003132
3133 if (listener != NULL && surfaceAbandoned) {
3134 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003135 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003136}
3137
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003138bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003139 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003140 status_t res;
3141 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003142 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003143 uint32_t numRequestProcessed = 0;
3144 for (size_t i = 0; i < batchSize; i++) {
3145 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003146 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003147 }
3148
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003149 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3150
3151 bool triggerRemoveFailed = false;
3152 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3153 for (size_t i = 0; i < numRequestProcessed; i++) {
3154 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3155 nextRequest.submitted = true;
3156
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003157 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003158
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003159 if (!triggerRemoveFailed) {
3160 // Remove any previously queued triggers (after unlock)
3161 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3162 if (removeTriggerRes != OK) {
3163 triggerRemoveFailed = true;
3164 triggerFailedRequest = nextRequest;
3165 }
3166 }
3167 }
3168
3169 if (triggerRemoveFailed) {
3170 SET_ERR("RequestThread: Unable to remove triggers "
3171 "(capture request %d, HAL device: %s (%d)",
3172 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3173 cleanUpFailedRequests(/*sendRequestError*/ false);
3174 return false;
3175 }
3176
3177 if (res != OK) {
3178 // Should only get a failure here for malformed requests or device-level
3179 // errors, so consider all errors fatal. Bad metadata failures should
3180 // come through notify.
3181 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3182 mNextRequests[numRequestProcessed].halRequest.frame_number,
3183 strerror(-res), res);
3184 cleanUpFailedRequests(/*sendRequestError*/ false);
3185 return false;
3186 }
3187 return true;
3188}
3189
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003190nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3191 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3192 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3193 find_camera_metadata_ro_entry(request,
3194 ANDROID_CONTROL_AE_MODE,
3195 &e);
3196 if (e.count == 0) return maxExpectedDuration;
3197
3198 switch (e.data.u8[0]) {
3199 case ANDROID_CONTROL_AE_MODE_OFF:
3200 find_camera_metadata_ro_entry(request,
3201 ANDROID_SENSOR_EXPOSURE_TIME,
3202 &e);
3203 if (e.count > 0) {
3204 maxExpectedDuration = e.data.i64[0];
3205 }
3206 find_camera_metadata_ro_entry(request,
3207 ANDROID_SENSOR_FRAME_DURATION,
3208 &e);
3209 if (e.count > 0) {
3210 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3211 }
3212 break;
3213 default:
3214 find_camera_metadata_ro_entry(request,
3215 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3216 &e);
3217 if (e.count > 1) {
3218 maxExpectedDuration = 1e9 / e.data.u8[0];
3219 }
3220 break;
3221 }
3222
3223 return maxExpectedDuration;
3224}
3225
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003226bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3227 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3228 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3229 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3230 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3231 return true;
3232 }
3233
3234 return false;
3235}
3236
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003237void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3238 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003239 camera_capture_request_t& halRequest = nextRequest.halRequest;
3240 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003241 Mutex::Autolock al(mLatestRequestMutex);
3242
Shuzhen Wang83bff122020-11-20 15:51:39 -08003243 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003244 mLatestRequest.acquire(cloned);
3245
3246 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003247 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3248 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3249 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003250 CameraMetadata(cloned));
3251 }
3252
3253 sp<Camera3Device> parent = mParent.promote();
3254 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003255 int32_t inputStreamId = -1;
3256 if (halRequest.input_buffer != nullptr) {
3257 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3258 }
3259
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003260 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003261 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003262 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3263 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003264 }
3265 }
3266
Shuzhen Wang83bff122020-11-20 15:51:39 -08003267 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003268 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003269 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003270 }
3271
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003273}
3274
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003275bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3276 ATRACE_CALL();
3277 bool updatesDetected = false;
3278
Emilian Peev4ec17882019-01-24 17:16:58 -08003279 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003280 for (auto tag : mSessionParamKeys) {
3281 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003282 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003283
3284 if (entry.count > 0) {
3285 bool isDifferent = false;
3286 if (lastEntry.count > 0) {
3287 // Have a last value, compare to see if changed
3288 if (lastEntry.type == entry.type &&
3289 lastEntry.count == entry.count) {
3290 // Same type and count, compare values
3291 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3292 size_t entryBytes = bytesPerValue * lastEntry.count;
3293 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3294 if (cmp != 0) {
3295 isDifferent = true;
3296 }
3297 } else {
3298 // Count or type has changed
3299 isDifferent = true;
3300 }
3301 } else {
3302 // No last entry, so always consider to be different
3303 isDifferent = true;
3304 }
3305
3306 if (isDifferent) {
3307 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003308 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3309 updatesDetected = true;
3310 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003311 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003312 }
3313 } else if (lastEntry.count > 0) {
3314 // Value has been removed
3315 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003316 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003317 updatesDetected = true;
3318 }
3319 }
3320
Emilian Peev4ec17882019-01-24 17:16:58 -08003321 bool reconfigureRequired;
3322 if (updatesDetected) {
3323 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3324 updatedParams);
3325 mLatestSessionParams = updatedParams;
3326 } else {
3327 reconfigureRequired = false;
3328 }
3329
3330 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003331}
3332
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003333bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003334 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003335 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003336 // Any function called from threadLoop() must not hold mInterfaceLock since
3337 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3338 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003339
3340 // Handle paused state.
3341 if (waitIfPaused()) {
3342 return true;
3343 }
3344
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003345 // Wait for the next batch of requests.
3346 waitForNextRequestBatch();
3347 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003348 return true;
3349 }
3350
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003351 // Get the latest request ID, if any
3352 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003353 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003354 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003355 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003356 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003357 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003358 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3359 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003360 }
3361
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003362 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3363 // or a single request from streaming or burst. In either case the first element
3364 // should contain the latest camera settings that we need to check for any session
3365 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003366 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003367 res = OK;
3368
3369 //Input stream buffers are already acquired at this point so an input stream
3370 //will not be able to move to idle state unless we force it.
3371 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3372 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3373 if (res != OK) {
3374 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3375 cleanUpFailedRequests(/*sendRequestError*/ false);
3376 return false;
3377 }
3378 }
3379
3380 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003381 sp<Camera3Device> parent = mParent.promote();
3382 if (parent != nullptr) {
3383 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003384 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003385 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003386
3387 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3388 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3389 if (res != OK) {
3390 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3391 cleanUpFailedRequests(/*sendRequestError*/ false);
3392 return false;
3393 }
3394 }
3395 }
3396 }
3397
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003398 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003399 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003400 if (res == TIMED_OUT) {
3401 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003402 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003403 // Check if any stream is abandoned.
3404 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003405 return true;
3406 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003407 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003408 return false;
3409 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003410
Zhijun Hecc27e112013-10-03 16:12:43 -07003411 // Inform waitUntilRequestProcessed thread of a new request ID
3412 {
3413 Mutex::Autolock al(mLatestRequestMutex);
3414
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003415 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003416 mLatestRequestSignal.signal();
3417 }
3418
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003419 // Submit a batch of requests to HAL.
3420 // Use flush lock only when submitting multilple requests in a batch.
3421 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3422 // which may take a long time to finish so synchronizing flush() and
3423 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3424 // For now, only synchronize for high speed recording and we should figure something out for
3425 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003426 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003427
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003428 if (useFlushLock) {
3429 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003430 }
3431
Zhijun Hef0645c12016-08-02 00:58:11 -07003432 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003433 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003434
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003435 sp<Camera3Device> parent = mParent.promote();
3436 if (parent != nullptr) {
3437 parent->mRequestBufferSM.onSubmittingRequest();
3438 }
3439
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003440 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003441 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003442 submitRequestSuccess = sendRequestsBatch();
3443
Shuzhen Wang686f6442017-06-20 16:16:04 -07003444 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3445 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003446
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003447 if (useFlushLock) {
3448 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003449 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003450
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003451 // Unset as current request
3452 {
3453 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003454 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003455 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003456 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003457
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003458 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003459}
3460
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003461status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3462 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3463 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3464 ANDROID_SCALER_CROP_REGION_SET};
3465 if (request == nullptr) {
3466 ALOGE("%s request metadata nullptr", __FUNCTION__);
3467 return BAD_VALUE;
3468 }
3469 status_t res = OK;
3470 for (const auto &key : kFwkOnlyRegionKeys) {
3471 if (request->exists(key)) {
3472 res = request->erase(key);
3473 if (res != OK) {
3474 return res;
3475 }
3476 }
3477 }
3478 return OK;
3479}
3480
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003481status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003482 ATRACE_CALL();
3483
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003484 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003485 for (size_t i = 0; i < mNextRequests.size(); i++) {
3486 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003487 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003488 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3489 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003490
3491 // Prepare a request to HAL
3492 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3493
3494 // Insert any queued triggers (before metadata is locked)
3495 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003496 if (res < 0) {
3497 SET_ERR("RequestThread: Unable to insert triggers "
3498 "(capture request %d, HAL device: %s (%d)",
3499 halRequest->frame_number, strerror(-res), res);
3500 return INVALID_OPERATION;
3501 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003502
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003503 int triggerCount = res;
3504 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3505 mPrevTriggers = triggerCount;
3506
Emilian Peeve23f1d92021-09-20 14:56:01 -07003507 // Do not override rotate&crop for stream configurations that include
3508 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3509 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3510 bool rotateAndCropChanged = mComposerOutput ? false :
3511 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003512 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003513
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003514 // If the request is the same as last, or we had triggers now or last time or
3515 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003516 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003517 (mPrevRequest != captureRequest || triggersMixedIn ||
3518 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003519 // Request settings are all the same within one batch, so only treat the first
3520 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003521 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003522 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003523 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003524 /**
3525 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003526 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003527 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003528 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003529 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003530 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003531 "(capture request %d, HAL device: %s (%d)",
3532 halRequest->frame_number, strerror(-res), res);
3533 return INVALID_OPERATION;
3534 }
3535
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003536 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003537 sp<Camera3Device> parent = mParent.promote();
3538 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003539 List<PhysicalCameraSettings>::iterator it;
3540 for (it = captureRequest->mSettingsList.begin();
3541 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003542 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3543 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003544 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3545 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3546 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3547 res);
3548 return INVALID_OPERATION;
3549 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003550 continue;
3551 }
3552
3553 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3554 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3555 updateCaptureRequest(&(it->metadata));
3556 if (res != OK) {
3557 SET_ERR("RequestThread: Unable to correct capture requests "
3558 "for scaler crop region and metering regions for request "
3559 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3560 res);
3561 return INVALID_OPERATION;
3562 }
3563 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003564 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3565 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3566 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3567 res);
3568 return INVALID_OPERATION;
3569 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003570 }
3571 }
3572
3573 // Correct metadata regions for distortion correction if enabled
3574 for (it = captureRequest->mSettingsList.begin();
3575 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003576 if (parent->mDistortionMappers.find(it->cameraId) ==
3577 parent->mDistortionMappers.end()) {
3578 continue;
3579 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003580
3581 if (!captureRequest->mDistortionCorrectionUpdated) {
3582 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3583 &(it->metadata));
3584 if (res != OK) {
3585 SET_ERR("RequestThread: Unable to correct capture requests "
3586 "for lens distortion for request %d: %s (%d)",
3587 halRequest->frame_number, strerror(-res), res);
3588 return INVALID_OPERATION;
3589 }
3590 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003591 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003592 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003593
3594 for (it = captureRequest->mSettingsList.begin();
3595 it != captureRequest->mSettingsList.end(); it++) {
3596 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3597 parent->mZoomRatioMappers.end()) {
3598 continue;
3599 }
3600
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003601 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003602 cameraIdsWithZoom.insert(it->cameraId);
3603 }
3604
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003605 if (!captureRequest->mZoomRatioUpdated) {
3606 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3607 &(it->metadata));
3608 if (res != OK) {
3609 SET_ERR("RequestThread: Unable to correct capture requests "
3610 "for zoom ratio for request %d: %s (%d)",
3611 halRequest->frame_number, strerror(-res), res);
3612 return INVALID_OPERATION;
3613 }
3614 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003615 }
3616 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003617 if (captureRequest->mRotateAndCropAuto &&
3618 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003619 for (it = captureRequest->mSettingsList.begin();
3620 it != captureRequest->mSettingsList.end(); it++) {
3621 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3622 if (mapper != parent->mRotateAndCropMappers.end()) {
3623 res = mapper->second.updateCaptureRequest(&(it->metadata));
3624 if (res != OK) {
3625 SET_ERR("RequestThread: Unable to correct capture requests "
3626 "for rotate-and-crop for request %d: %s (%d)",
3627 halRequest->frame_number, strerror(-res), res);
3628 return INVALID_OPERATION;
3629 }
3630 }
3631 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003632 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003633 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003634 }
3635 }
3636
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003637 /**
3638 * The request should be presorted so accesses in HAL
3639 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3640 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003641 captureRequest->mSettingsList.begin()->metadata.sort();
3642 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003643 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003644 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003645 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3646
3647 IF_ALOGV() {
3648 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3649 find_camera_metadata_ro_entry(
3650 halRequest->settings,
3651 ANDROID_CONTROL_AF_TRIGGER,
3652 &e
3653 );
3654 if (e.count > 0) {
3655 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3656 __FUNCTION__,
3657 halRequest->frame_number,
3658 e.data.u8[0]);
3659 }
3660 }
3661 } else {
3662 // leave request.settings NULL to indicate 'reuse latest given'
3663 ALOGVV("%s: Request settings are REUSED",
3664 __FUNCTION__);
3665 }
3666
Emilian Peevaebbe412018-01-15 13:53:24 +00003667 if (captureRequest->mSettingsList.size() > 1) {
3668 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3669 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003670 if (newRequest) {
3671 halRequest->physcam_settings =
3672 new const camera_metadata* [halRequest->num_physcam_settings];
3673 } else {
3674 halRequest->physcam_settings = nullptr;
3675 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003676 auto it = ++captureRequest->mSettingsList.begin();
3677 size_t i = 0;
3678 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3679 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003680 if (newRequest) {
3681 it->metadata.sort();
3682 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3683 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003684 }
3685 }
3686
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003687 uint32_t totalNumBuffers = 0;
3688
3689 // Fill in buffers
3690 if (captureRequest->mInputStream != NULL) {
3691 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003692
3693 halRequest->input_width = captureRequest->mInputBufferSize.width;
3694 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003695 totalNumBuffers += 1;
3696 } else {
3697 halRequest->input_buffer = NULL;
3698 }
3699
Emilian Peevf4816702020-04-03 15:44:51 -07003700 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003701 captureRequest->mOutputStreams.size());
3702 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003703 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003704
3705 sp<Camera3Device> parent = mParent.promote();
3706 if (parent == NULL) {
3707 // Should not happen, and nowhere to send errors to, so just log it
3708 CLOGE("RequestThread: Parent is gone");
3709 return INVALID_OPERATION;
3710 }
3711 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3712
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003713 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003714 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003715 sp<Camera3OutputStreamInterface> outputStream =
3716 captureRequest->mOutputStreams.editItemAt(j);
3717 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003718
3719 // Prepare video buffers for high speed recording on the first video request.
3720 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3721 // Only try to prepare video stream on the first video request.
3722 mPrepareVideoStream = false;
3723
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003724 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3725 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003726 while (res == NOT_ENOUGH_DATA) {
3727 res = outputStream->prepareNextBuffer();
3728 }
3729 if (res != OK) {
3730 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3731 __FUNCTION__, strerror(-res), res);
3732 outputStream->cancelPrepare();
3733 }
3734 }
3735
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003736 std::vector<size_t> uniqueSurfaceIds;
3737 res = outputStream->getUniqueSurfaceIds(
3738 captureRequest->mOutputSurfaces[streamId],
3739 &uniqueSurfaceIds);
3740 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3741 if (res != OK && res != INVALID_OPERATION) {
3742 ALOGE("%s: failed to query stream %d unique surface IDs",
3743 __FUNCTION__, streamId);
3744 return res;
3745 }
3746 if (res == OK) {
3747 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3748 }
3749
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003750 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003751 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003752 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003753 return TIMED_OUT;
3754 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003755 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003756 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003757 buffer.stream = outputStream->asHalStream();
3758 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003759 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003760 buffer.acquire_fence = -1;
3761 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003762 // Mark the output stream as unpreparable to block clients from calling
3763 // 'prepare' after this request reaches CameraHal and before the respective
3764 // buffers are requested.
3765 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003766 } else {
3767 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3768 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003769 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003770 if (res != OK) {
3771 // Can't get output buffer from gralloc queue - this could be due to
3772 // abandoned queue or other consumer misbehavior, so not a fatal
3773 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003774 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003775 " %s (%d)", strerror(-res), res);
3776
3777 return TIMED_OUT;
3778 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003779 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003780
3781 {
3782 sp<Camera3Device> parent = mParent.promote();
3783 if (parent != nullptr) {
3784 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3785 for (const auto& settings : captureRequest->mSettingsList) {
3786 if ((streamCameraId.isEmpty() &&
3787 parent->getId() == settings.cameraId.c_str()) ||
3788 streamCameraId == settings.cameraId.c_str()) {
3789 outputStream->fireBufferRequestForFrameNumber(
3790 captureRequest->mResultExtras.frameNumber,
3791 settings.metadata);
3792 }
3793 }
3794 }
3795 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003796
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003797 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003798 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3799 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3800 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3801 } else if (!physicalCameraId.isEmpty()) {
3802 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003803 }
3804 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003805 }
3806 totalNumBuffers += halRequest->num_output_buffers;
3807
3808 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003809 // If this request list is for constrained high speed recording (not
3810 // preview), and the current request is not the last one in the batch,
3811 // do not send callback to the app.
3812 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003813 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003814 hasCallback = false;
3815 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003816 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003817 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003818 const camera_metadata_t* settings = halRequest->settings;
3819 bool shouldUnlockSettings = false;
3820 if (settings == nullptr) {
3821 shouldUnlockSettings = true;
3822 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3823 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003824 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3825 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003826 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003827 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3828 isStillCapture = true;
3829 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3830 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003831
Emilian Peevaf8416e2021-02-04 17:52:43 -08003832 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003833 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003834 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3835 isZslCapture = true;
3836 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003837 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003838 res = parent->registerInFlight(halRequest->frame_number,
3839 totalNumBuffers, captureRequest->mResultExtras,
3840 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003841 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003842 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003843 requestedPhysicalCameras, isStillCapture, isZslCapture,
3844 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003845 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003846 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003847 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3848 ", burstId = %" PRId32 ".",
3849 __FUNCTION__,
3850 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3851 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003852
3853 if (shouldUnlockSettings) {
3854 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3855 }
3856
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003857 if (res != OK) {
3858 SET_ERR("RequestThread: Unable to register new in-flight request:"
3859 " %s (%d)", strerror(-res), res);
3860 return INVALID_OPERATION;
3861 }
3862 }
3863
3864 return OK;
3865}
3866
Igor Murashkin1e479c02013-09-06 16:55:14 -07003867CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003868 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003869 Mutex::Autolock al(mLatestRequestMutex);
3870
3871 ALOGV("RequestThread::%s", __FUNCTION__);
3872
3873 return mLatestRequest;
3874}
3875
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003876bool Camera3Device::RequestThread::isStreamPending(
3877 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003878 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003879 Mutex::Autolock l(mRequestLock);
3880
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003881 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003882 if (!nextRequest.submitted) {
3883 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3884 if (stream == s) return true;
3885 }
3886 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003887 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003888 }
3889
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003890 for (const auto& request : mRequestQueue) {
3891 for (const auto& s : request->mOutputStreams) {
3892 if (stream == s) return true;
3893 }
3894 if (stream == request->mInputStream) return true;
3895 }
3896
3897 for (const auto& request : mRepeatingRequests) {
3898 for (const auto& s : request->mOutputStreams) {
3899 if (stream == s) return true;
3900 }
3901 if (stream == request->mInputStream) return true;
3902 }
3903
3904 return false;
3905}
Jianing Weicb0652e2014-03-12 18:29:36 -07003906
Emilian Peev40ead602017-09-26 15:46:36 +01003907bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3908 ATRACE_CALL();
3909 Mutex::Autolock l(mRequestLock);
3910
3911 for (const auto& nextRequest : mNextRequests) {
3912 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3913 if (s.first == streamId) {
3914 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3915 if (it != s.second.end()) {
3916 return true;
3917 }
3918 }
3919 }
3920 }
3921
3922 for (const auto& request : mRequestQueue) {
3923 for (const auto& s : request->mOutputSurfaces) {
3924 if (s.first == streamId) {
3925 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3926 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003927 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003928 }
3929 }
3930 }
3931 }
3932
3933 for (const auto& request : mRepeatingRequests) {
3934 for (const auto& s : request->mOutputSurfaces) {
3935 if (s.first == streamId) {
3936 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3937 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003938 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003939 }
3940 }
3941 }
3942 }
3943
3944 return false;
3945}
3946
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003947void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3948 if (!mUseHalBufManager) {
3949 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3950 return;
3951 }
3952
3953 Mutex::Autolock pl(mPauseLock);
3954 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003955 mInterface->signalPipelineDrain(streamIds);
3956 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003957 }
3958 // If request thread is still busy, wait until paused then notify HAL
3959 mNotifyPipelineDrain = true;
3960 mStreamIdsToBeDrained = streamIds;
3961}
3962
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003963void Camera3Device::RequestThread::resetPipelineDrain() {
3964 Mutex::Autolock pl(mPauseLock);
3965 mNotifyPipelineDrain = false;
3966 mStreamIdsToBeDrained.clear();
3967}
3968
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003969void Camera3Device::RequestThread::clearPreviousRequest() {
3970 Mutex::Autolock l(mRequestLock);
3971 mPrevRequest.clear();
3972}
3973
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003974status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3975 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3976 ATRACE_CALL();
3977 Mutex::Autolock l(mTriggerMutex);
3978 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3979 return BAD_VALUE;
3980 }
3981 mRotateAndCropOverride = rotateAndCropValue;
3982 return OK;
3983}
3984
Emilian Peeve23f1d92021-09-20 14:56:01 -07003985status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3986 ATRACE_CALL();
3987 Mutex::Autolock l(mTriggerMutex);
3988 mComposerOutput = composerSurfacePresent;
3989 return OK;
3990}
3991
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003992status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003993 ATRACE_CALL();
3994 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003995 if (muteMode != mCameraMute) {
3996 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003997 mCameraMuteChanged = true;
3998 }
3999 return OK;
4000}
4001
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004002nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004003 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004004 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004005 return mExpectedInflightDuration > kMinInflightDuration ?
4006 mExpectedInflightDuration : kMinInflightDuration;
4007}
4008
Emilian Peevaebbe412018-01-15 13:53:24 +00004009void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004010 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004011 if ((request == nullptr) || (halRequest == nullptr)) {
4012 ALOGE("%s: Invalid request!", __FUNCTION__);
4013 return;
4014 }
4015
4016 if (halRequest->num_physcam_settings > 0) {
4017 if (halRequest->physcam_id != nullptr) {
4018 delete [] halRequest->physcam_id;
4019 halRequest->physcam_id = nullptr;
4020 }
4021 if (halRequest->physcam_settings != nullptr) {
4022 auto it = ++(request->mSettingsList.begin());
4023 size_t i = 0;
4024 for (; it != request->mSettingsList.end(); it++, i++) {
4025 it->metadata.unlock(halRequest->physcam_settings[i]);
4026 }
4027 delete [] halRequest->physcam_settings;
4028 halRequest->physcam_settings = nullptr;
4029 }
4030 }
4031}
4032
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004033void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4034 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004035 return;
4036 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004037
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004038 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004039 // Skip the ones that have been submitted successfully.
4040 if (nextRequest.submitted) {
4041 continue;
4042 }
4043
4044 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004045 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4046 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004047
4048 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004049 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004050 }
4051
Emilian Peevaebbe412018-01-15 13:53:24 +00004052 cleanupPhysicalSettings(captureRequest, halRequest);
4053
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004054 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004055 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004056 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4057 }
4058
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004059 // No output buffer can be returned when using HAL buffer manager
4060 if (!mUseHalBufManager) {
4061 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4062 //Buffers that failed processing could still have
4063 //valid acquire fence.
4064 int acquireFence = (*outputBuffers)[i].acquire_fence;
4065 if (0 <= acquireFence) {
4066 close(acquireFence);
4067 outputBuffers->editItemAt(i).acquire_fence = -1;
4068 }
Emilian Peevf4816702020-04-03 15:44:51 -07004069 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004070 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4071 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004072 /*timestampIncreasing*/true, std::vector<size_t> (),
4073 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004074 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004075 }
4076
4077 if (sendRequestError) {
4078 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004079 sp<NotificationListener> listener = mListener.promote();
4080 if (listener != NULL) {
4081 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004082 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004083 captureRequest->mResultExtras);
4084 }
4085 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004086
4087 // Remove yet-to-be submitted inflight request from inflightMap
4088 {
4089 sp<Camera3Device> parent = mParent.promote();
4090 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004091 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004092 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4093 if (idx >= 0) {
4094 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4095 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4096 parent->removeInFlightMapEntryLocked(idx);
4097 }
4098 }
4099 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004100 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004101
4102 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004103 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004104}
4105
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004106void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004107 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004108 // Optimized a bit for the simple steady-state case (single repeating
4109 // request), to avoid putting that request in the queue temporarily.
4110 Mutex::Autolock l(mRequestLock);
4111
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004112 assert(mNextRequests.empty());
4113
4114 NextRequest nextRequest;
4115 nextRequest.captureRequest = waitForNextRequestLocked();
4116 if (nextRequest.captureRequest == nullptr) {
4117 return;
4118 }
4119
Emilian Peevf4816702020-04-03 15:44:51 -07004120 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004121 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004122 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004123
4124 // Wait for additional requests
4125 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4126
4127 for (size_t i = 1; i < batchSize; i++) {
4128 NextRequest additionalRequest;
4129 additionalRequest.captureRequest = waitForNextRequestLocked();
4130 if (additionalRequest.captureRequest == nullptr) {
4131 break;
4132 }
4133
Emilian Peevf4816702020-04-03 15:44:51 -07004134 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004135 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004136 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004137 }
4138
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004139 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004140 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004141 mNextRequests.size(), batchSize);
4142 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004143 }
4144
4145 return;
4146}
4147
4148sp<Camera3Device::CaptureRequest>
4149 Camera3Device::RequestThread::waitForNextRequestLocked() {
4150 status_t res;
4151 sp<CaptureRequest> nextRequest;
4152
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004153 while (mRequestQueue.empty()) {
4154 if (!mRepeatingRequests.empty()) {
4155 // Always atomically enqueue all requests in a repeating request
4156 // list. Guarantees a complete in-sequence set of captures to
4157 // application.
4158 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004159 if (mFirstRepeating) {
4160 mFirstRepeating = false;
4161 } else {
4162 for (auto& request : requests) {
4163 // For repeating requests, override timestamp request using
4164 // the time a request is inserted into the request queue,
4165 // because the original repeating request will have an old
4166 // fixed timestamp.
4167 request->mRequestTimeNs = systemTime();
4168 }
4169 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004170 RequestList::const_iterator firstRequest =
4171 requests.begin();
4172 nextRequest = *firstRequest;
4173 mRequestQueue.insert(mRequestQueue.end(),
4174 ++firstRequest,
4175 requests.end());
4176 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004177
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004178 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004179
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004180 break;
4181 }
4182
4183 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4184
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004185 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4186 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004187 Mutex::Autolock pl(mPauseLock);
4188 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004189 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004190 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004191 if (mNotifyPipelineDrain) {
4192 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4193 mNotifyPipelineDrain = false;
4194 mStreamIdsToBeDrained.clear();
4195 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004196 // Let the tracker know
4197 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4198 if (statusTracker != 0) {
4199 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4200 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004201 sp<Camera3Device> parent = mParent.promote();
4202 if (parent != nullptr) {
4203 parent->mRequestBufferSM.onRequestThreadPaused();
4204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004205 }
4206 // Stop waiting for now and let thread management happen
4207 return NULL;
4208 }
4209 }
4210
4211 if (nextRequest == NULL) {
4212 // Don't have a repeating request already in hand, so queue
4213 // must have an entry now.
4214 RequestList::iterator firstRequest =
4215 mRequestQueue.begin();
4216 nextRequest = *firstRequest;
4217 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004218 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4219 sp<NotificationListener> listener = mListener.promote();
4220 if (listener != NULL) {
4221 listener->notifyRequestQueueEmpty();
4222 }
4223 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004224 }
4225
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004226 // In case we've been unpaused by setPaused clearing mDoPause, need to
4227 // update internal pause state (capture/setRepeatingRequest unpause
4228 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004229 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004230 if (mPaused) {
4231 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4232 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4233 if (statusTracker != 0) {
4234 statusTracker->markComponentActive(mStatusId);
4235 }
4236 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004237 mPaused = false;
4238
4239 // Check if we've reconfigured since last time, and reset the preview
4240 // request if so. Can't use 'NULL request == repeat' across configure calls.
4241 if (mReconfigured) {
4242 mPrevRequest.clear();
4243 mReconfigured = false;
4244 }
4245
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004246 if (nextRequest != NULL) {
4247 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004248 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4249 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004250
4251 // Since RequestThread::clear() removes buffers from the input stream,
4252 // get the right buffer here before unlocking mRequestLock
4253 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004254 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4255 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004256 if (res != OK) {
4257 // Can't get input buffer from gralloc queue - this could be due to
4258 // disconnected queue or other producer misbehavior, so not a fatal
4259 // error
4260 ALOGE("%s: Can't get input buffer, skipping request:"
4261 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004262
4263 sp<NotificationListener> listener = mListener.promote();
4264 if (listener != NULL) {
4265 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004266 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004267 nextRequest->mResultExtras);
4268 }
4269 return NULL;
4270 }
4271 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004272 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004273
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004274 return nextRequest;
4275}
4276
4277bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004278 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004279 status_t res;
4280 Mutex::Autolock l(mPauseLock);
4281 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004282 if (mPaused == false) {
4283 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004284 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004285 if (mNotifyPipelineDrain) {
4286 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4287 mNotifyPipelineDrain = false;
4288 mStreamIdsToBeDrained.clear();
4289 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004290 // Let the tracker know
4291 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4292 if (statusTracker != 0) {
4293 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4294 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004295 sp<Camera3Device> parent = mParent.promote();
4296 if (parent != nullptr) {
4297 parent->mRequestBufferSM.onRequestThreadPaused();
4298 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004299 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004301 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004302 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004303 return true;
4304 }
4305 }
4306 // We don't set mPaused to false here, because waitForNextRequest needs
4307 // to further manage the paused state in case of starvation.
4308 return false;
4309}
4310
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004311void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004312 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004313 // With work to do, mark thread as unpaused.
4314 // If paused by request (setPaused), don't resume, to avoid
4315 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004316 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004317 Mutex::Autolock p(mPauseLock);
4318 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004319 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4320 if (mPaused) {
4321 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4322 if (statusTracker != 0) {
4323 statusTracker->markComponentActive(mStatusId);
4324 }
4325 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004326 mPaused = false;
4327 }
4328}
4329
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004330void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4331 sp<Camera3Device> parent = mParent.promote();
4332 if (parent != NULL) {
4333 va_list args;
4334 va_start(args, fmt);
4335
4336 parent->setErrorStateV(fmt, args);
4337
4338 va_end(args);
4339 }
4340}
4341
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004342status_t Camera3Device::RequestThread::insertTriggers(
4343 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004344 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004345 Mutex::Autolock al(mTriggerMutex);
4346
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004347 sp<Camera3Device> parent = mParent.promote();
4348 if (parent == NULL) {
4349 CLOGE("RequestThread: Parent is gone");
4350 return DEAD_OBJECT;
4351 }
4352
Emilian Peevaebbe412018-01-15 13:53:24 +00004353 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004354 size_t count = mTriggerMap.size();
4355
4356 for (size_t i = 0; i < count; ++i) {
4357 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004358 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004359
4360 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4361 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4362 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004363 if (isAeTrigger) {
4364 request->mResultExtras.precaptureTriggerId = triggerId;
4365 mCurrentPreCaptureTriggerId = triggerId;
4366 } else {
4367 request->mResultExtras.afTriggerId = triggerId;
4368 mCurrentAfTriggerId = triggerId;
4369 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004370 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004371 }
4372
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004373 camera_metadata_entry entry = metadata.find(tag);
4374
4375 if (entry.count > 0) {
4376 /**
4377 * Already has an entry for this trigger in the request.
4378 * Rewrite it with our requested trigger value.
4379 */
4380 RequestTrigger oldTrigger = trigger;
4381
4382 oldTrigger.entryValue = entry.data.u8[0];
4383
4384 mTriggerReplacedMap.add(tag, oldTrigger);
4385 } else {
4386 /**
4387 * More typical, no trigger entry, so we just add it
4388 */
4389 mTriggerRemovedMap.add(tag, trigger);
4390 }
4391
4392 status_t res;
4393
4394 switch (trigger.getTagType()) {
4395 case TYPE_BYTE: {
4396 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4397 res = metadata.update(tag,
4398 &entryValue,
4399 /*count*/1);
4400 break;
4401 }
4402 case TYPE_INT32:
4403 res = metadata.update(tag,
4404 &trigger.entryValue,
4405 /*count*/1);
4406 break;
4407 default:
4408 ALOGE("%s: Type not supported: 0x%x",
4409 __FUNCTION__,
4410 trigger.getTagType());
4411 return INVALID_OPERATION;
4412 }
4413
4414 if (res != OK) {
4415 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4416 ", value %d", __FUNCTION__, trigger.getTagName(),
4417 trigger.entryValue);
4418 return res;
4419 }
4420
4421 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4422 trigger.getTagName(),
4423 trigger.entryValue);
4424 }
4425
4426 mTriggerMap.clear();
4427
4428 return count;
4429}
4430
4431status_t Camera3Device::RequestThread::removeTriggers(
4432 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004433 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004434 Mutex::Autolock al(mTriggerMutex);
4435
Emilian Peevaebbe412018-01-15 13:53:24 +00004436 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004437
4438 /**
4439 * Replace all old entries with their old values.
4440 */
4441 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4442 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4443
4444 status_t res;
4445
4446 uint32_t tag = trigger.metadataTag;
4447 switch (trigger.getTagType()) {
4448 case TYPE_BYTE: {
4449 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4450 res = metadata.update(tag,
4451 &entryValue,
4452 /*count*/1);
4453 break;
4454 }
4455 case TYPE_INT32:
4456 res = metadata.update(tag,
4457 &trigger.entryValue,
4458 /*count*/1);
4459 break;
4460 default:
4461 ALOGE("%s: Type not supported: 0x%x",
4462 __FUNCTION__,
4463 trigger.getTagType());
4464 return INVALID_OPERATION;
4465 }
4466
4467 if (res != OK) {
4468 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4469 ", trigger value %d", __FUNCTION__,
4470 trigger.getTagName(), trigger.entryValue);
4471 return res;
4472 }
4473 }
4474 mTriggerReplacedMap.clear();
4475
4476 /**
4477 * Remove all new entries.
4478 */
4479 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4480 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4481 status_t res = metadata.erase(trigger.metadataTag);
4482
4483 if (res != OK) {
4484 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4485 ", trigger value %d", __FUNCTION__,
4486 trigger.getTagName(), trigger.entryValue);
4487 return res;
4488 }
4489 }
4490 mTriggerRemovedMap.clear();
4491
4492 return OK;
4493}
4494
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004495status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004496 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004497 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004498 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004499 status_t res;
4500
Emilian Peevaebbe412018-01-15 13:53:24 +00004501 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004502
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004503 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004504 // exists
4505 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4506 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4507 if (afTrigger.count > 0 &&
4508 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4509 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004510 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004511 if (res != OK) return res;
4512 }
4513
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004514 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004515 // if none already exists
4516 camera_metadata_entry pcTrigger =
4517 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4518 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4519 if (pcTrigger.count > 0 &&
4520 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4521 pcId.count == 0) {
4522 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004523 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004524 if (res != OK) return res;
4525 }
4526
4527 return OK;
4528}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004529
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004530bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4531 const sp<CaptureRequest> &request) {
4532 ATRACE_CALL();
4533
4534 if (request->mRotateAndCropAuto) {
4535 Mutex::Autolock l(mTriggerMutex);
4536 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4537
4538 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4539 if (rotateAndCropEntry.count > 0) {
4540 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4541 return false;
4542 } else {
4543 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4544 return true;
4545 }
4546 } else {
4547 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4548 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4549 &rotateAndCrop_u8, 1);
4550 return true;
4551 }
4552 }
4553 return false;
4554}
4555
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004556bool Camera3Device::RequestThread::overrideTestPattern(
4557 const sp<CaptureRequest> &request) {
4558 ATRACE_CALL();
4559
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004560 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004561
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004562 Mutex::Autolock l(mTriggerMutex);
4563
4564 bool changed = false;
4565
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004566 // For a multi-camera, the physical cameras support the same set of
4567 // test pattern modes as the logical camera.
4568 for (auto& settings : request->mSettingsList) {
4569 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004570
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004571 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4572 int32_t testPatternData[4] = {
4573 settings.mOriginalTestPatternData[0],
4574 settings.mOriginalTestPatternData[1],
4575 settings.mOriginalTestPatternData[2],
4576 settings.mOriginalTestPatternData[3]
4577 };
4578 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4579 testPatternMode = mCameraMute;
4580 testPatternData[0] = 0;
4581 testPatternData[1] = 0;
4582 testPatternData[2] = 0;
4583 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004584 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004585
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004586 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4587 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4588 if (testPatternEntry.count > 0) {
4589 if (testPatternEntry.data.i32[0] != testPatternMode) {
4590 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004591 changed = true;
4592 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004593 } else if (supportTestPatternModeKey) {
4594 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4595 &testPatternMode, 1);
4596 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004597 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004598
4599 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4600 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4601 if (testPatternColor.count >= 4) {
4602 for (size_t i = 0; i < 4; i++) {
4603 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4604 testPatternColor.data.i32[i] = testPatternData[i];
4605 changed = true;
4606 }
4607 }
4608 } else if (supportTestPatternDataKey) {
4609 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4610 testPatternData, 4);
4611 changed = true;
4612 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004613 }
4614
4615 return changed;
4616}
4617
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004618status_t Camera3Device::RequestThread::setHalInterface(
4619 sp<HalInterface> newHalInterface) {
4620 if (newHalInterface.get() == nullptr) {
4621 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4622 return DEAD_OBJECT;
4623 }
4624
4625 mInterface = newHalInterface;
4626
4627 return OK;
4628}
4629
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004630/**
4631 * PreparerThread inner class methods
4632 */
4633
4634Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004635 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004636 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004637}
4638
4639Camera3Device::PreparerThread::~PreparerThread() {
4640 Thread::requestExitAndWait();
4641 if (mCurrentStream != nullptr) {
4642 mCurrentStream->cancelPrepare();
4643 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4644 mCurrentStream.clear();
4645 }
4646 clear();
4647}
4648
Ruben Brunkc78ac262015-08-13 17:58:46 -07004649status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004650 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004651 status_t res;
4652
4653 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004654 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004655
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004656 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004657 if (res == OK) {
4658 // No preparation needed, fire listener right off
4659 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004660 if (listener != NULL) {
4661 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004662 }
4663 return OK;
4664 } else if (res != NOT_ENOUGH_DATA) {
4665 return res;
4666 }
4667
4668 // Need to prepare, start up thread if necessary
4669 if (!mActive) {
4670 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4671 // isn't running
4672 Thread::requestExitAndWait();
4673 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4674 if (res != OK) {
4675 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004676 if (listener != NULL) {
4677 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004678 }
4679 return res;
4680 }
4681 mCancelNow = false;
4682 mActive = true;
4683 ALOGV("%s: Preparer stream started", __FUNCTION__);
4684 }
4685
4686 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004687 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004688 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4689
4690 return OK;
4691}
4692
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004693void Camera3Device::PreparerThread::pause() {
4694 ATRACE_CALL();
4695
4696 Mutex::Autolock l(mLock);
4697
4698 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4699 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4700 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4701 int currentMaxCount = mCurrentMaxCount;
4702 mPendingStreams.clear();
4703 mCancelNow = true;
4704 while (mActive) {
4705 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4706 if (res == TIMED_OUT) {
4707 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4708 return;
4709 } else if (res != OK) {
4710 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4711 return;
4712 }
4713 }
4714
4715 //Check whether the prepare thread was able to complete the current
4716 //stream. In case work is still pending emplace it along with the rest
4717 //of the streams in the pending list.
4718 if (currentStream != nullptr) {
4719 if (!mCurrentPrepareComplete) {
4720 pendingStreams.emplace(currentMaxCount, currentStream);
4721 }
4722 }
4723
4724 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4725 for (const auto& it : mPendingStreams) {
4726 it.second->cancelPrepare();
4727 }
4728}
4729
4730status_t Camera3Device::PreparerThread::resume() {
4731 ATRACE_CALL();
4732 status_t res;
4733
4734 Mutex::Autolock l(mLock);
4735 sp<NotificationListener> listener = mListener.promote();
4736
4737 if (mActive) {
4738 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4739 return NO_INIT;
4740 }
4741
4742 auto it = mPendingStreams.begin();
4743 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004744 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004745 if (res == OK) {
4746 if (listener != NULL) {
4747 listener->notifyPrepared(it->second->getId());
4748 }
4749 it = mPendingStreams.erase(it);
4750 } else if (res != NOT_ENOUGH_DATA) {
4751 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4752 res, strerror(-res));
4753 it = mPendingStreams.erase(it);
4754 } else {
4755 it++;
4756 }
4757 }
4758
4759 if (mPendingStreams.empty()) {
4760 return OK;
4761 }
4762
4763 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4764 if (res != OK) {
4765 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4766 __FUNCTION__, res, strerror(-res));
4767 return res;
4768 }
4769 mCancelNow = false;
4770 mActive = true;
4771 ALOGV("%s: Preparer stream started", __FUNCTION__);
4772
4773 return OK;
4774}
4775
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004776status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004777 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004778 Mutex::Autolock l(mLock);
4779
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004780 for (const auto& it : mPendingStreams) {
4781 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004782 }
4783 mPendingStreams.clear();
4784 mCancelNow = true;
4785
4786 return OK;
4787}
4788
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004789void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004790 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004791 Mutex::Autolock l(mLock);
4792 mListener = listener;
4793}
4794
4795bool Camera3Device::PreparerThread::threadLoop() {
4796 status_t res;
4797 {
4798 Mutex::Autolock l(mLock);
4799 if (mCurrentStream == nullptr) {
4800 // End thread if done with work
4801 if (mPendingStreams.empty()) {
4802 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4803 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4804 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4805 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004806 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004807 return false;
4808 }
4809
4810 // Get next stream to prepare
4811 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004812 mCurrentStream = it->second;
4813 mCurrentMaxCount = it->first;
4814 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004815 mPendingStreams.erase(it);
4816 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4817 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4818 } else if (mCancelNow) {
4819 mCurrentStream->cancelPrepare();
4820 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4821 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4822 mCurrentStream.clear();
4823 mCancelNow = false;
4824 return true;
4825 }
4826 }
4827
4828 res = mCurrentStream->prepareNextBuffer();
4829 if (res == NOT_ENOUGH_DATA) return true;
4830 if (res != OK) {
4831 // Something bad happened; try to recover by cancelling prepare and
4832 // signalling listener anyway
4833 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4834 mCurrentStream->getId(), res, strerror(-res));
4835 mCurrentStream->cancelPrepare();
4836 }
4837
4838 // This stream has finished, notify listener
4839 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004840 sp<NotificationListener> listener = mListener.promote();
4841 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004842 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4843 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004844 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004845 }
4846
4847 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4848 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004849 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004850
4851 return true;
4852}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004853
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004854status_t Camera3Device::RequestBufferStateMachine::initialize(
4855 sp<camera3::StatusTracker> statusTracker) {
4856 if (statusTracker == nullptr) {
4857 ALOGE("%s: statusTracker is null", __FUNCTION__);
4858 return BAD_VALUE;
4859 }
4860
4861 std::lock_guard<std::mutex> lock(mLock);
4862 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004863 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004864 return OK;
4865}
4866
4867bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4868 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004869 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004870 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004871 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004872 return true;
4873 }
4874 return false;
4875}
4876
4877void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4878 std::lock_guard<std::mutex> lock(mLock);
4879 if (!mRequestBufferOngoing) {
4880 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4881 return;
4882 }
4883 mRequestBufferOngoing = false;
4884 if (mStatus == RB_STATUS_PENDING_STOP) {
4885 checkSwitchToStopLocked();
4886 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004887 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004888}
4889
4890void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4891 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004892 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004893 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004894 return;
4895}
4896
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004897void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004898 std::lock_guard<std::mutex> lock(mLock);
4899 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004900 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4901 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004902 mInflightMapEmpty = false;
4903 if (mStatus == RB_STATUS_STOPPED) {
4904 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004905 }
4906 return;
4907}
4908
4909void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4910 std::lock_guard<std::mutex> lock(mLock);
4911 mRequestThreadPaused = true;
4912 if (mStatus == RB_STATUS_PENDING_STOP) {
4913 checkSwitchToStopLocked();
4914 }
4915 return;
4916}
4917
4918void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4919 std::lock_guard<std::mutex> lock(mLock);
4920 mInflightMapEmpty = true;
4921 if (mStatus == RB_STATUS_PENDING_STOP) {
4922 checkSwitchToStopLocked();
4923 }
4924 return;
4925}
4926
4927void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4928 std::lock_guard<std::mutex> lock(mLock);
4929 if (!checkSwitchToStopLocked()) {
4930 mStatus = RB_STATUS_PENDING_STOP;
4931 }
4932 return;
4933}
4934
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004935bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4936 std::lock_guard<std::mutex> lock(mLock);
4937 if (mRequestBufferOngoing) {
4938 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4939 __FUNCTION__);
4940 return false;
4941 }
4942 mSwitchedToOffline = true;
4943 mInflightMapEmpty = true;
4944 mRequestThreadPaused = true;
4945 mStatus = RB_STATUS_STOPPED;
4946 return true;
4947}
4948
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004949void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4950 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4951 if (statusTracker != nullptr) {
4952 if (active) {
4953 statusTracker->markComponentActive(mRequestBufferStatusId);
4954 } else {
4955 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4956 }
4957 }
4958}
4959
4960bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4961 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4962 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004963 return true;
4964 }
4965 return false;
4966}
4967
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004968bool Camera3Device::startRequestBuffer() {
4969 return mRequestBufferSM.startRequestBuffer();
4970}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004971
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004972void Camera3Device::endRequestBuffer() {
4973 mRequestBufferSM.endRequestBuffer();
4974}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004975
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004976nsecs_t Camera3Device::getWaitDuration() {
4977 return kBaseGetBufferWait + getExpectedInFlightDuration();
4978}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004979
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004980void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4981 mInterface->getInflightBufferKeys(out);
4982}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004983
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004984void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4985 mInterface->getInflightRequestBufferKeys(out);
4986}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004987
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004988std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
4989 std::vector<sp<Camera3StreamInterface>> ret;
4990 bool hasInputStream = mInputStream != nullptr;
4991 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
4992 if (hasInputStream) {
4993 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07004994 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004995 for (size_t i = 0; i < mOutputStreams.size(); i++) {
4996 ret.push_back(mOutputStreams[i]);
4997 }
4998 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
4999 ret.push_back(mDeletedStreams[i]);
5000 }
5001 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005002}
5003
Emilian Peevcc0b7952020-01-07 13:54:47 -08005004void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5005 ATRACE_CALL();
5006
5007 if (offlineStreamIds == nullptr) {
5008 return;
5009 }
5010
5011 Mutex::Autolock il(mInterfaceLock);
5012
5013 auto streamIds = mOutputStreams.getStreamIds();
5014 bool hasInputStream = mInputStream != nullptr;
5015 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5016 offlineStreamIds->push_back(mInputStream->getId());
5017 }
5018
5019 for (const auto & streamId : streamIds) {
5020 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5021 // Streams that use the camera buffer manager are currently not supported in
5022 // offline mode
5023 if (stream->getOfflineProcessingSupport() &&
5024 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5025 offlineStreamIds->push_back(streamId);
5026 }
5027 }
5028}
5029
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005030status_t Camera3Device::setRotateAndCropAutoBehavior(
5031 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5032 ATRACE_CALL();
5033 Mutex::Autolock il(mInterfaceLock);
5034 Mutex::Autolock l(mLock);
5035 if (mRequestThread == nullptr) {
5036 return INVALID_OPERATION;
5037 }
5038 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5039}
5040
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005041bool Camera3Device::supportsCameraMute() {
5042 Mutex::Autolock il(mInterfaceLock);
5043 Mutex::Autolock l(mLock);
5044
5045 return mSupportCameraMute;
5046}
5047
5048status_t Camera3Device::setCameraMute(bool enabled) {
5049 ATRACE_CALL();
5050 Mutex::Autolock il(mInterfaceLock);
5051 Mutex::Autolock l(mLock);
5052
5053 if (mRequestThread == nullptr || !mSupportCameraMute) {
5054 return INVALID_OPERATION;
5055 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005056 int32_t muteMode =
5057 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5058 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5059 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5060 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005061}
5062
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005063status_t Camera3Device::injectCamera(const String8& injectedCamId,
5064 sp<CameraProviderManager> manager) {
5065 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5066 ATRACE_CALL();
5067 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005068 // When the camera device is active, injectCamera() and stopInjection() will call
5069 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5070 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5071 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5072 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5073 // waitUntilStateThenRelock().
5074 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005075
5076 status_t res = NO_ERROR;
5077 if (mInjectionMethods->isInjecting()) {
5078 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5079 return OK;
5080 } else {
5081 res = mInjectionMethods->stopInjection();
5082 if (res != OK) {
5083 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5084 __FUNCTION__, res);
5085 return res;
5086 }
5087 }
5088 }
5089
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005090 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005091 if (res != OK) {
5092 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5093 __FUNCTION__, res);
5094 return res;
5095 }
5096
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005097 // When the second display of android is cast to the remote device, and the opened camera is
5098 // also cast to the second display, in this case, because the camera has configured the streams
5099 // at this time, we can directly call injectCamera() to replace the internal camera with
5100 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005101 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5102 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5103
5104 camera3::camera_stream_configuration injectionConfig;
5105 std::vector<uint32_t> injectionBufferSizes;
5106 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5107 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5108 || injectionBufferSizes.size() <= 0) {
5109 ALOGE("Failed to inject camera due to abandoned configuration! "
5110 "mOperatingMode: %d injectionConfig.num_streams: %d "
5111 "injectionBufferSizes.size(): %zu", mOperatingMode,
5112 injectionConfig.num_streams, injectionBufferSizes.size());
5113 return DEAD_OBJECT;
5114 }
5115
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005116 res = mInjectionMethods->injectCamera(
5117 injectionConfig, injectionBufferSizes);
5118 if (res != OK) {
5119 ALOGE("Can't finish inject camera process!");
5120 return res;
5121 }
5122 }
5123
5124 return OK;
5125}
5126
5127status_t Camera3Device::stopInjection() {
5128 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5129 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005130 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005131 return mInjectionMethods->stopInjection();
5132}
5133
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005134}; // namespace android