blob: 992027a120c569ce065b241447d00740ea36f51f [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,
Emilian Peev2295df72021-11-12 18:14:10 -0800981 uint64_t consumerUsage, int dynamicRangeProfile) {
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,
Emilian Peev2295df72021-11-12 18:14:10 -0800994 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800995}
996
997static bool isRawFormat(int format) {
998 switch (format) {
999 case HAL_PIXEL_FORMAT_RAW16:
1000 case HAL_PIXEL_FORMAT_RAW12:
1001 case HAL_PIXEL_FORMAT_RAW10:
1002 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1003 return true;
1004 default:
1005 return false;
1006 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001007}
1008
1009status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1010 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001011 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001012 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001013 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Emilian Peev2295df72021-11-12 18:14:10 -08001014 uint64_t consumerUsage, int dynamicRangeProfile) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001015 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001016
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001017 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001018 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001019 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001020 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wang83bff122020-11-20 15:51:39 -08001021 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d",
1022 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
1023 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001024
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001025 status_t res;
1026 bool wasActive = false;
1027
1028 switch (mStatus) {
1029 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001030 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001031 return INVALID_OPERATION;
1032 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001033 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001034 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001035 case STATUS_UNCONFIGURED:
1036 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001037 // OK
1038 break;
1039 case STATUS_ACTIVE:
1040 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001041 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001042 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001043 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001044 return res;
1045 }
1046 wasActive = true;
1047 break;
1048 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001049 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001050 return INVALID_OPERATION;
1051 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001052 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001053
1054 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001055
Shuzhen Wang0129d522016-10-30 22:43:41 -07001056 if (consumers.size() == 0 && !hasDeferredConsumer) {
1057 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1058 return BAD_VALUE;
1059 }
Zhijun He5d677d12016-05-29 16:52:39 -07001060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001062 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1063 return BAD_VALUE;
1064 }
1065
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001066 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1067 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1068 // be found in only one sensor pixel mode.
1069 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1070 return BAD_VALUE;
1071 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001072 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001073 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001074 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001075 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001076 if (blobBufferSize <= 0) {
1077 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1078 return BAD_VALUE;
1079 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001080 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1081 blobBufferSize = width * height;
1082 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001083 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001084 if (blobBufferSize <= 0) {
1085 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1086 return BAD_VALUE;
1087 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001088 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001089 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001090 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001091 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001092 isMultiResolution, dynamicRangeProfile);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001093 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001094 bool maxResolution =
1095 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1096 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001097 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1098 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001099 if (rawOpaqueBufferSize <= 0) {
1100 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1101 return BAD_VALUE;
1102 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001103 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001104 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001105 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001106 isMultiResolution, dynamicRangeProfile);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001107 } else if (isShared) {
1108 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1109 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001110 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001111 mUseHalBufManager, dynamicRangeProfile);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001112 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001113 newStream = new Camera3OutputStream(mNextStreamId,
1114 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001115 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001116 isMultiResolution, dynamicRangeProfile);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001117 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001118 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001119 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001120 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Emilian Peev2295df72021-11-12 18:14:10 -08001121 isMultiResolution, dynamicRangeProfile);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001122 }
Emilian Peev40ead602017-09-26 15:46:36 +01001123
1124 size_t consumerCount = consumers.size();
1125 for (size_t i = 0; i < consumerCount; i++) {
1126 int id = newStream->getSurfaceId(consumers[i]);
1127 if (id < 0) {
1128 SET_ERR_L("Invalid surface id");
1129 return BAD_VALUE;
1130 }
1131 if (surfaceIds != nullptr) {
1132 surfaceIds->push_back(id);
1133 }
1134 }
1135
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001136 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001137
Emilian Peev08dd2452017-04-06 16:55:14 +01001138 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001139
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001140 newStream->setImageDumpMask(mImageDumpMask);
1141
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001142 res = mOutputStreams.add(mNextStreamId, newStream);
1143 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001144 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001145 return res;
1146 }
1147
Shuzhen Wang316781a2020-08-18 18:11:01 -07001148 mSessionStatsBuilder.addStream(mNextStreamId);
1149
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001150 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001151 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001152
1153 // Continue captures if active at start
1154 if (wasActive) {
1155 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001156 // Reuse current operating mode and session parameters for new stream config
1157 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001158 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001159 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1160 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001161 return res;
1162 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001163 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001164 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001165 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001166 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001167}
1168
Emilian Peev710c1422017-08-30 11:19:38 +01001169status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001170 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001171 if (nullptr == streamInfo) {
1172 return BAD_VALUE;
1173 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001174 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001175 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177 switch (mStatus) {
1178 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001179 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001180 return INVALID_OPERATION;
1181 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001182 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001183 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001184 case STATUS_UNCONFIGURED:
1185 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186 case STATUS_ACTIVE:
1187 // OK
1188 break;
1189 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001190 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001191 return INVALID_OPERATION;
1192 }
1193
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001194 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1195 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001196 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001197 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 }
1199
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001200 streamInfo->width = stream->getWidth();
1201 streamInfo->height = stream->getHeight();
1202 streamInfo->format = stream->getFormat();
1203 streamInfo->dataSpace = stream->getDataSpace();
1204 streamInfo->formatOverridden = stream->isFormatOverridden();
1205 streamInfo->originalFormat = stream->getOriginalFormat();
1206 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1207 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001208 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210}
1211
1212status_t Camera3Device::setStreamTransform(int id,
1213 int transform) {
1214 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001215 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001217
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 switch (mStatus) {
1219 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001220 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 return INVALID_OPERATION;
1222 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001223 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 case STATUS_UNCONFIGURED:
1226 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 case STATUS_ACTIVE:
1228 // OK
1229 break;
1230 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001231 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 return INVALID_OPERATION;
1233 }
1234
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001235 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1236 if (stream == nullptr) {
1237 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001238 return BAD_VALUE;
1239 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001240 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001241}
1242
1243status_t Camera3Device::deleteStream(int id) {
1244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001245 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001246 Mutex::Autolock l(mLock);
1247 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001249 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001250
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 // CameraDevice semantics require device to already be idle before
1252 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001254 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001255 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 }
1257
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001258 if (mStatus == STATUS_ERROR) {
1259 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1260 __FUNCTION__, mId.string());
1261 return -EBUSY;
1262 }
1263
Igor Murashkin2fba5842013-04-22 14:03:54 -07001264 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001265 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 if (mInputStream != NULL && id == mInputStream->getId()) {
1267 deletedStream = mInputStream;
1268 mInputStream.clear();
1269 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001270 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001271 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 return BAD_VALUE;
1273 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001274 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001275 }
1276
1277 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001278 if (stream != nullptr) {
1279 deletedStream = stream;
1280 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001281 }
1282
1283 // Free up the stream endpoint so that it can be used by some other stream
1284 res = deletedStream->disconnect();
1285 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001286 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001287 // fall through since we want to still list the stream as deleted.
1288 }
1289 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001290 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001291
1292 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001293}
1294
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001295status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001296 ATRACE_CALL();
1297 ALOGV("%s: E", __FUNCTION__);
1298
1299 Mutex::Autolock il(mInterfaceLock);
1300 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001301
Emilian Peev811d2952018-05-25 11:08:40 +01001302 // In case the client doesn't include any session parameter, try a
1303 // speculative configuration using the values from the last cached
1304 // default request.
1305 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001306 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001307 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1308 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1309 mLastTemplateId);
1310 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1311 operatingMode);
1312 }
1313
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001314 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1315}
1316
1317status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1318 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001319 //Filter out any incoming session parameters
1320 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001321 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1322 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001323 CameraMetadata filteredParams(availableSessionKeys.count);
1324 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1325 filteredParams.getAndLock());
1326 set_camera_metadata_vendor_id(meta, mVendorTagId);
1327 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001328 if (availableSessionKeys.count > 0) {
1329 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1330 camera_metadata_ro_entry entry = params.find(
1331 availableSessionKeys.data.i32[i]);
1332 if (entry.count > 0) {
1333 filteredParams.update(entry);
1334 }
1335 }
1336 }
1337
1338 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001339}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001340
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001341status_t Camera3Device::getInputBufferProducer(
1342 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001343 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001344 Mutex::Autolock il(mInterfaceLock);
1345 Mutex::Autolock l(mLock);
1346
1347 if (producer == NULL) {
1348 return BAD_VALUE;
1349 } else if (mInputStream == NULL) {
1350 return INVALID_OPERATION;
1351 }
1352
1353 return mInputStream->getInputBufferProducer(producer);
1354}
1355
Emilian Peevf4816702020-04-03 15:44:51 -07001356status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001357 CameraMetadata *request) {
1358 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001359 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001360
Emilian Peevf4816702020-04-03 15:44:51 -07001361 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001362 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001363 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001364 return BAD_VALUE;
1365 }
1366
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001367 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001369 {
1370 Mutex::Autolock l(mLock);
1371 switch (mStatus) {
1372 case STATUS_ERROR:
1373 CLOGE("Device has encountered a serious error");
1374 return INVALID_OPERATION;
1375 case STATUS_UNINITIALIZED:
1376 CLOGE("Device is not initialized!");
1377 return INVALID_OPERATION;
1378 case STATUS_UNCONFIGURED:
1379 case STATUS_CONFIGURED:
1380 case STATUS_ACTIVE:
1381 // OK
1382 break;
1383 default:
1384 SET_ERR_L("Unexpected status: %d", mStatus);
1385 return INVALID_OPERATION;
1386 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001387
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001388 if (!mRequestTemplateCache[templateId].isEmpty()) {
1389 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001390 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001391 return OK;
1392 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001393 }
1394
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001395 camera_metadata_t *rawRequest;
1396 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001397 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001398
1399 {
1400 Mutex::Autolock l(mLock);
1401 if (res == BAD_VALUE) {
1402 ALOGI("%s: template %d is not supported on this camera device",
1403 __FUNCTION__, templateId);
1404 return res;
1405 } else if (res != OK) {
1406 CLOGE("Unable to construct request template %d: %s (%d)",
1407 templateId, strerror(-res), res);
1408 return res;
1409 }
1410
1411 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1412 mRequestTemplateCache[templateId].acquire(rawRequest);
1413
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001414 // Override the template request with zoomRatioMapper
1415 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1416 &mRequestTemplateCache[templateId]);
1417 if (res != OK) {
1418 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1419 templateId, strerror(-res), res);
1420 return res;
1421 }
1422
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001423 // Fill in JPEG_QUALITY if not available
1424 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1425 static const uint8_t kDefaultJpegQuality = 95;
1426 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1427 &kDefaultJpegQuality, 1);
1428 }
1429
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001430 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001431 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001432 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001433 return OK;
1434}
1435
1436status_t Camera3Device::waitUntilDrained() {
1437 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001438 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001439 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001440 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001441
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001442 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001443}
1444
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001445status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446 switch (mStatus) {
1447 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449 ALOGV("%s: Already idle", __FUNCTION__);
1450 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001451 case STATUS_CONFIGURED:
1452 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001453 case STATUS_ERROR:
1454 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001455 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456 break;
1457 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001458 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 return INVALID_OPERATION;
1460 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001461 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1462 maxExpectedDuration);
1463 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001464 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001465 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001466 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1467 res);
1468 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001469 return res;
1470}
1471
Ruben Brunk183f0562015-08-12 12:55:02 -07001472void Camera3Device::internalUpdateStatusLocked(Status status) {
1473 mStatus = status;
1474 mRecentStatusUpdates.add(mStatus);
1475 mStatusChanged.broadcast();
1476}
1477
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001479status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001480 if (mRequestThread.get() != nullptr) {
1481 mRequestThread->setPaused(true);
1482 } else {
1483 return NO_INIT;
1484 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001485
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001486 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1487 maxExpectedDuration);
1488 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001489 if (res != OK) {
1490 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001491 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 }
1493
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001494 return res;
1495}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497// Resume after internalPauseAndWaitLocked
1498status_t Camera3Device::internalResumeLocked() {
1499 status_t res;
1500
1501 mRequestThread->setPaused(false);
1502
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001503 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1504 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001505 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1506 if (res != OK) {
1507 SET_ERR_L("Can't transition to active in %f seconds!",
1508 kActiveTimeout/1e9);
1509 }
1510 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001512}
1513
Ruben Brunk183f0562015-08-12 12:55:02 -07001514status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001516
1517 size_t startIndex = 0;
1518 if (mStatusWaiters == 0) {
1519 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1520 // this status list
1521 mRecentStatusUpdates.clear();
1522 } else {
1523 // If other threads are waiting on updates to this status list, set the position of the
1524 // first element that this list will check rather than clearing the list.
1525 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 }
1527
Ruben Brunk183f0562015-08-12 12:55:02 -07001528 mStatusWaiters++;
1529
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001530 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001531 if (!active && mUseHalBufManager) {
1532 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001533 if (mStatus == STATUS_ACTIVE) {
1534 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001535 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001536 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001537 mRequestBufferSM.onWaitUntilIdle();
1538 }
1539
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 bool stateSeen = false;
1541 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001542 if (active == (mStatus == STATUS_ACTIVE)) {
1543 // Desired state is current
1544 break;
1545 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546
1547 res = mStatusChanged.waitRelative(mLock, timeout);
1548 if (res != OK) break;
1549
Ruben Brunk183f0562015-08-12 12:55:02 -07001550 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1551 // transitions.
1552 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1553 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1554 __FUNCTION__);
1555
1556 // Encountered desired state since we began waiting
1557 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1559 stateSeen = true;
1560 break;
1561 }
1562 }
1563 } while (!stateSeen);
1564
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001565 if (signalPipelineDrain) {
1566 mRequestThread->resetPipelineDrain();
1567 }
1568
Ruben Brunk183f0562015-08-12 12:55:02 -07001569 mStatusWaiters--;
1570
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 return res;
1572}
1573
1574
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001575status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001577 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001578
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001579 if (listener != NULL && mListener != NULL) {
1580 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1581 }
1582 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001583 mRequestThread->setNotificationListener(listener);
1584 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001585
1586 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001587}
1588
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001589bool Camera3Device::willNotify3A() {
1590 return false;
1591}
1592
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001593status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001594 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001595 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001596
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001597 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001598 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1599 if (st == std::cv_status::timeout) {
1600 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001601 }
1602 }
1603 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001604}
1605
Jianing Weicb0652e2014-03-12 18:29:36 -07001606status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001607 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001608 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001609
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001610 if (mResultQueue.empty()) {
1611 return NOT_ENOUGH_DATA;
1612 }
1613
Jianing Weicb0652e2014-03-12 18:29:36 -07001614 if (frame == NULL) {
1615 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1616 return BAD_VALUE;
1617 }
1618
1619 CaptureResult &result = *(mResultQueue.begin());
1620 frame->mResultExtras = result.mResultExtras;
1621 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001622 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001623 mResultQueue.erase(mResultQueue.begin());
1624
1625 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626}
1627
1628status_t Camera3Device::triggerAutofocus(uint32_t id) {
1629 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001632 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1633 // Mix-in this trigger into the next request and only the next request.
1634 RequestTrigger trigger[] = {
1635 {
1636 ANDROID_CONTROL_AF_TRIGGER,
1637 ANDROID_CONTROL_AF_TRIGGER_START
1638 },
1639 {
1640 ANDROID_CONTROL_AF_TRIGGER_ID,
1641 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001642 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001643 };
1644
1645 return mRequestThread->queueTrigger(trigger,
1646 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647}
1648
1649status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1650 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001651 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001652
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001653 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1654 // Mix-in this trigger into the next request and only the next request.
1655 RequestTrigger trigger[] = {
1656 {
1657 ANDROID_CONTROL_AF_TRIGGER,
1658 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1659 },
1660 {
1661 ANDROID_CONTROL_AF_TRIGGER_ID,
1662 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001663 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001664 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001665
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001666 return mRequestThread->queueTrigger(trigger,
1667 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001668}
1669
1670status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1671 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001673
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001674 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1675 // Mix-in this trigger into the next request and only the next request.
1676 RequestTrigger trigger[] = {
1677 {
1678 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1679 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1680 },
1681 {
1682 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1683 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001684 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001685 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001686
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001687 return mRequestThread->queueTrigger(trigger,
1688 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689}
1690
Jianing Weicb0652e2014-03-12 18:29:36 -07001691status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001692 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001693 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001694 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001695
Zhijun He7ef20392014-04-21 16:04:17 -07001696 {
1697 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001698
1699 // b/116514106 "disconnect()" can get called twice for the same device. The
1700 // camera device will not be initialized during the second run.
1701 if (mStatus == STATUS_UNINITIALIZED) {
1702 return OK;
1703 }
1704
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001705 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001706
1707 // Stop session and stream counter
1708 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001709 }
1710
Emilian Peev08dd2452017-04-06 16:55:14 +01001711 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001712}
1713
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001714status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001715 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1716}
1717
1718status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001719 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001720 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001721 Mutex::Autolock il(mInterfaceLock);
1722 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001723
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001724 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1725 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001726 CLOGE("Stream %d does not exist", streamId);
1727 return BAD_VALUE;
1728 }
1729
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001730 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001731 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001732 return BAD_VALUE;
1733 }
1734
1735 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001736 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001737 return BAD_VALUE;
1738 }
1739
Ruben Brunkc78ac262015-08-13 17:58:46 -07001740 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001741}
1742
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001743status_t Camera3Device::tearDown(int streamId) {
1744 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001745 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001746 Mutex::Autolock il(mInterfaceLock);
1747 Mutex::Autolock l(mLock);
1748
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001749 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1750 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001751 CLOGE("Stream %d does not exist", streamId);
1752 return BAD_VALUE;
1753 }
1754
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001755 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1756 CLOGE("Stream %d is a target of a in-progress request", streamId);
1757 return BAD_VALUE;
1758 }
1759
1760 return stream->tearDown();
1761}
1762
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001763status_t Camera3Device::addBufferListenerForStream(int streamId,
1764 wp<Camera3StreamBufferListener> listener) {
1765 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001766 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001767 Mutex::Autolock il(mInterfaceLock);
1768 Mutex::Autolock l(mLock);
1769
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001770 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1771 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001772 CLOGE("Stream %d does not exist", streamId);
1773 return BAD_VALUE;
1774 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001775 stream->addBufferListener(listener);
1776
1777 return OK;
1778}
1779
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001780/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001781 * Methods called by subclasses
1782 */
1783
1784void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001785 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001786 std::vector<int> streamIds;
1787 std::vector<hardware::CameraStreamStats> streamStats;
1788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 {
1790 // Need mLock to safely update state and synchronize to current
1791 // state of methods in flight.
1792 Mutex::Autolock l(mLock);
1793 // We can get various system-idle notices from the status tracker
1794 // while starting up. Only care about them if we've actually sent
1795 // in some requests recently.
1796 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1797 return;
1798 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001799 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1800 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001801 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802
1803 // Skip notifying listener if we're doing some user-transparent
1804 // state changes
1805 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001806
1807 // Populate stream statistics in case of Idle
1808 if (idle) {
1809 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1810 auto stream = mOutputStreams[i];
1811 if (stream.get() == nullptr) continue;
1812 streamIds.push_back(stream->getId());
1813 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1814 int64_t usage = 0LL;
1815 if (camera3Stream != nullptr) {
1816 usage = camera3Stream->getUsage();
1817 }
1818 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1819 stream->getFormat(), stream->getDataSpace(), usage,
1820 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001821 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
1822 stream->getDynamicRangeProfile());
Shuzhen Wang316781a2020-08-18 18:11:01 -07001823 }
1824 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001826
1827 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001829 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001830 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001832 status_t res = OK;
1833 if (listener != nullptr) {
1834 if (idle) {
1835 // Get session stats from the builder, and notify the listener.
1836 int64_t requestCount, resultErrorCount;
1837 bool deviceError;
1838 std::map<int, StreamStats> streamStatsMap;
1839 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1840 &deviceError, &streamStatsMap);
1841 for (size_t i = 0; i < streamIds.size(); i++) {
1842 int streamId = streamIds[i];
1843 auto stats = streamStatsMap.find(streamId);
1844 if (stats != streamStatsMap.end()) {
1845 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1846 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1847 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1848 streamStats[i].mHistogramType =
1849 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1850 streamStats[i].mHistogramBins.assign(
1851 stats->second.mCaptureLatencyBins.begin(),
1852 stats->second.mCaptureLatencyBins.end());
1853 streamStats[i].mHistogramCounts.assign(
1854 stats->second.mCaptureLatencyHistogram.begin(),
1855 stats->second.mCaptureLatencyHistogram.end());
1856 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001857 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001858 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1859 } else {
1860 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001861 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001862 }
1863 if (res != OK) {
1864 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1865 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866 }
1867}
1868
Shuzhen Wang758c2152017-01-10 18:26:18 -08001869status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001870 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001871 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001872 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1873 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001874
1875 if (surfaceIds == nullptr) {
1876 return BAD_VALUE;
1877 }
1878
Zhijun He5d677d12016-05-29 16:52:39 -07001879 Mutex::Autolock il(mInterfaceLock);
1880 Mutex::Autolock l(mLock);
1881
Shuzhen Wang758c2152017-01-10 18:26:18 -08001882 if (consumers.size() == 0) {
1883 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001884 return BAD_VALUE;
1885 }
1886
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001887 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1888 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001889 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001890 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001891 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001892
1893 // isConsumerConfigurationDeferred will be off after setConsumers
1894 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001895 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001896 if (res != OK) {
1897 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1898 return res;
1899 }
1900
Emilian Peev40ead602017-09-26 15:46:36 +01001901 for (auto &consumer : consumers) {
1902 int id = stream->getSurfaceId(consumer);
1903 if (id < 0) {
1904 CLOGE("Invalid surface id!");
1905 return BAD_VALUE;
1906 }
1907 surfaceIds->push_back(id);
1908 }
1909
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001910 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001911 if (!stream->isConfiguring()) {
1912 CLOGE("Stream %d was already fully configured.", streamId);
1913 return INVALID_OPERATION;
1914 }
Zhijun He5d677d12016-05-29 16:52:39 -07001915
Shuzhen Wang0129d522016-10-30 22:43:41 -07001916 res = stream->finishConfiguration();
1917 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001918 // If finishConfiguration fails due to abandoned surface, do not set
1919 // device to error state.
1920 bool isSurfaceAbandoned =
1921 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1922 if (!isSurfaceAbandoned) {
1923 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1924 stream->getId(), strerror(-res), res);
1925 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001926 return res;
1927 }
Zhijun He5d677d12016-05-29 16:52:39 -07001928 }
1929
1930 return OK;
1931}
1932
Emilian Peev40ead602017-09-26 15:46:36 +01001933status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1934 const std::vector<OutputStreamInfo> &outputInfo,
1935 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1936 Mutex::Autolock il(mInterfaceLock);
1937 Mutex::Autolock l(mLock);
1938
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001939 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1940 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001941 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001942 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001943 }
1944
1945 for (const auto &it : removedSurfaceIds) {
1946 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1947 CLOGE("Shared surface still part of a pending request!");
1948 return -EBUSY;
1949 }
1950 }
1951
Emilian Peev40ead602017-09-26 15:46:36 +01001952 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1953 if (res != OK) {
1954 CLOGE("Stream %d failed to update stream (error %d %s) ",
1955 streamId, res, strerror(-res));
1956 if (res == UNKNOWN_ERROR) {
1957 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1958 __FUNCTION__);
1959 }
1960 return res;
1961 }
1962
1963 return res;
1964}
1965
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001966status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1967 Mutex::Autolock il(mInterfaceLock);
1968 Mutex::Autolock l(mLock);
1969
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001970 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1971 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001972 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1973 return BAD_VALUE;
1974 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001975
1976 if (dropping) {
1977 mSessionStatsBuilder.stopCounter(streamId);
1978 } else {
1979 mSessionStatsBuilder.startCounter(streamId);
1980 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001981 return stream->dropBuffers(dropping);
1982}
1983
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001984/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001985 * Camera3Device private methods
1986 */
1987
1988sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00001989 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001990 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001991
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001992 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00001993 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001994
1995 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00001996 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001997 if (inputStreams.count > 0) {
1998 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07001999 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002000 CLOGE("Request references unknown input stream %d",
2001 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002002 return NULL;
2003 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002004
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002005 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002006 SET_ERR_L("%s: input stream %d is not configured!",
2007 __FUNCTION__, mInputStream->getId());
2008 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002009 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002010 // Check if stream prepare is blocking requests.
2011 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002012 CLOGE("Request references an input stream that's being prepared!");
2013 return NULL;
2014 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002015
2016 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002017 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002018 }
2019
2020 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002021 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002022 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002023 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002024 return NULL;
2025 }
2026
2027 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002028 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2029 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002030 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002031 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002032 return NULL;
2033 }
Zhijun He5d677d12016-05-29 16:52:39 -07002034 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002035 auto iter = surfaceMap.find(streams.data.i32[i]);
2036 if (iter != surfaceMap.end()) {
2037 const std::vector<size_t>& surfaces = iter->second;
2038 for (const auto& surface : surfaces) {
2039 if (stream->isConsumerConfigurationDeferred(surface)) {
2040 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2041 "due to deferred consumer", stream->getId(), surface);
2042 return NULL;
2043 }
2044 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002045 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002046 }
2047
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002049 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2050 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002052 // Check if stream prepare is blocking requests.
2053 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002054 CLOGE("Request references an output stream that's being prepared!");
2055 return NULL;
2056 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002057
2058 newRequest->mOutputStreams.push(stream);
2059 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002060 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002061 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002063 auto rotateAndCropEntry =
2064 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2065 if (rotateAndCropEntry.count > 0 &&
2066 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2067 newRequest->mRotateAndCropAuto = true;
2068 } else {
2069 newRequest->mRotateAndCropAuto = false;
2070 }
2071
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002072 auto zoomRatioEntry =
2073 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2074 if (zoomRatioEntry.count > 0 &&
2075 zoomRatioEntry.data.f[0] == 1.0f) {
2076 newRequest->mZoomRatioIs1x = true;
2077 } else {
2078 newRequest->mZoomRatioIs1x = false;
2079 }
2080
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002081 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002082 for (auto& settings : newRequest->mSettingsList) {
2083 auto testPatternModeEntry =
2084 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2085 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2086 testPatternModeEntry.data.i32[0] :
2087 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002088
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002089 auto testPatternDataEntry =
2090 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2091 if (testPatternDataEntry.count >= 4) {
2092 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2093 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2094 } else {
2095 settings.mOriginalTestPatternData[0] = 0;
2096 settings.mOriginalTestPatternData[1] = 0;
2097 settings.mOriginalTestPatternData[2] = 0;
2098 settings.mOriginalTestPatternData[3] = 0;
2099 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002100 }
2101 }
2102
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002104}
2105
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002106void Camera3Device::cancelStreamsConfigurationLocked() {
2107 int res = OK;
2108 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2109 res = mInputStream->cancelConfiguration();
2110 if (res != OK) {
2111 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2112 mInputStream->getId(), strerror(-res), res);
2113 }
2114 }
2115
2116 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002117 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002118 if (outputStream->isConfiguring()) {
2119 res = outputStream->cancelConfiguration();
2120 if (res != OK) {
2121 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2122 outputStream->getId(), strerror(-res), res);
2123 }
2124 }
2125 }
2126
2127 // Return state to that at start of call, so that future configures
2128 // properly clean things up
2129 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2130 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002131
2132 res = mPreparerThread->resume();
2133 if (res != OK) {
2134 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2135 }
2136}
2137
Emilian Peev0d0191e2020-04-21 17:01:18 -07002138bool Camera3Device::checkAbandonedStreamsLocked() {
2139 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2140 return true;
2141 }
2142
2143 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2144 auto stream = mOutputStreams[i];
2145 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2146 return true;
2147 }
2148 }
2149
2150 return false;
2151}
2152
Emilian Peev3bead5f2020-05-28 17:29:08 -07002153bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002154 ATRACE_CALL();
2155 bool ret = false;
2156
Shuzhen Wang316781a2020-08-18 18:11:01 -07002157 nsecs_t startTime = systemTime();
2158
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002159 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002160 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2161
2162 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002163 if (checkAbandonedStreamsLocked()) {
2164 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2165 __FUNCTION__);
2166 return true;
2167 }
2168
Emilian Peev3bead5f2020-05-28 17:29:08 -07002169 status_t rc = NO_ERROR;
2170 bool markClientActive = false;
2171 if (mStatus == STATUS_ACTIVE) {
2172 markClientActive = true;
2173 mPauseStateNotify = true;
2174 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2175
2176 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2177 }
2178
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002179 if (rc == NO_ERROR) {
2180 mNeedConfig = true;
2181 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2182 if (rc == NO_ERROR) {
2183 ret = true;
2184 mPauseStateNotify = false;
2185 //Moving to active state while holding 'mLock' is important.
2186 //There could be pending calls to 'create-/deleteStream' which
2187 //will trigger another stream configuration while the already
2188 //present streams end up with outstanding buffers that will
2189 //not get drained.
2190 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002191 } else if (rc == DEAD_OBJECT) {
2192 // DEAD_OBJECT can be returned if either the consumer surface is
2193 // abandoned, or the HAL has died.
2194 // - If the HAL has died, configureStreamsLocked call will set
2195 // device to error state,
2196 // - If surface is abandoned, we should not set device to error
2197 // state.
2198 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002199 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002200 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002201 }
2202 } else {
2203 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2204 }
2205
Shuzhen Wang316781a2020-08-18 18:11:01 -07002206 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2207 ns2ms(systemTime() - startTime));
2208
Emilian Peev3bead5f2020-05-28 17:29:08 -07002209 if (markClientActive) {
2210 mStatusTracker->markComponentActive(clientStatusId);
2211 }
2212
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002213 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002214}
2215
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002216status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002217 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002218 ATRACE_CALL();
2219 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002220
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002221 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002222 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 return INVALID_OPERATION;
2224 }
2225
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002226 if (operatingMode < 0) {
2227 CLOGE("Invalid operating mode: %d", operatingMode);
2228 return BAD_VALUE;
2229 }
2230
2231 bool isConstrainedHighSpeed =
2232 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2233 operatingMode;
2234
2235 if (mOperatingMode != operatingMode) {
2236 mNeedConfig = true;
2237 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2238 mOperatingMode = operatingMode;
2239 }
2240
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002241 // In case called from configureStreams, abort queued input buffers not belonging to
2242 // any pending requests.
2243 if (mInputStream != NULL && notifyRequestThread) {
2244 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002245 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002246 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002247 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002248 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002249 if (res != OK) {
2250 // Exhausted acquiring all input buffers.
2251 break;
2252 }
2253
Emilian Peevf4816702020-04-03 15:44:51 -07002254 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002255 res = mInputStream->returnInputBuffer(inputBuffer);
2256 if (res != OK) {
2257 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2258 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2259 }
2260 }
2261 }
2262
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002263 if (!mNeedConfig) {
2264 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2265 return OK;
2266 }
2267
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002268 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002269 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002270 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2271 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002272 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002273 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002274 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002275 }
2276
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002277 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002278 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002280 mPreparerThread->pause();
2281
Emilian Peevf4816702020-04-03 15:44:51 -07002282 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002283 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002285 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002286
Emilian Peevf4816702020-04-03 15:44:51 -07002287 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002289 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002290
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291
2292 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002293 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294 inputStream = mInputStream->startConfiguration();
2295 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002296 CLOGE("Can't start input stream configuration");
2297 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298 return INVALID_OPERATION;
2299 }
2300 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002301
2302 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002303 }
2304
Shuzhen Wang99080502021-03-07 21:08:20 -08002305 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002306 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002308
2309 // Don't configure bidi streams twice, nor add them twice to the list
2310 if (mOutputStreams[i].get() ==
2311 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2312
2313 config.num_streams--;
2314 continue;
2315 }
2316
Emilian Peevf4816702020-04-03 15:44:51 -07002317 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002318 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002320 CLOGE("Can't start output stream configuration");
2321 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002322 return INVALID_OPERATION;
2323 }
2324 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002325
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002326 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002327 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2328 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002329 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2330 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002331 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2332 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002333 } else if (outputStream->data_space ==
2334 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2335 bufferSizes[k] = outputStream->width * outputStream->height;
2336 } else {
2337 ALOGW("%s: Blob dataSpace %d not supported",
2338 __FUNCTION__, outputStream->data_space);
2339 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002340 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002341
2342 if (mOutputStreams[i]->isMultiResolution()) {
2343 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2344 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2345 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2346 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002347
2348 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2349 composerSurfacePresent = true;
2350 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002351 }
2352
2353 config.streams = streams.editArray();
2354
2355 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002356 // max_buffers, usage, and priv fields, as well as data_space and format
2357 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002358
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002359 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002360 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002361 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002362
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002363 if (res == BAD_VALUE) {
2364 // HAL rejected this set of streams as unsupported, clean up config
2365 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002366 CLOGE("Set of requested inputs/outputs not supported by HAL");
2367 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002368 return BAD_VALUE;
2369 } else if (res != OK) {
2370 // Some other kind of error from configure_streams - this is not
2371 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002372 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2373 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002374 return res;
2375 }
2376
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002377 // Finish all stream configuration immediately.
2378 // TODO: Try to relax this later back to lazy completion, which should be
2379 // faster
2380
Igor Murashkin073f8572013-05-02 14:59:28 -07002381 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002382 bool streamReConfigured = false;
2383 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002384 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002385 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002386 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002387 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002388 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2389 return DEAD_OBJECT;
2390 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002391 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002392 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002393 if (streamReConfigured) {
2394 mInterface->onStreamReConfigured(mInputStream->getId());
2395 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002396 }
2397
2398 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002399 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002400 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002401 bool streamReConfigured = false;
2402 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002403 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002404 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002405 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002406 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002407 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2408 return DEAD_OBJECT;
2409 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002410 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002411 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002412 if (streamReConfigured) {
2413 mInterface->onStreamReConfigured(outputStream->getId());
2414 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002415 }
2416 }
2417
Emilian Peeve23f1d92021-09-20 14:56:01 -07002418 mRequestThread->setComposerSurface(composerSurfacePresent);
2419
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 // Request thread needs to know to avoid using repeat-last-settings protocol
2421 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002422 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002423 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2424 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002425 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002426
Zhijun He90f7c372016-08-16 16:19:43 -07002427 char value[PROPERTY_VALUE_MAX];
2428 property_get("camera.fifo.disable", value, "0");
2429 int32_t disableFifo = atoi(value);
2430 if (disableFifo != 1) {
2431 // Boost priority of request thread to SCHED_FIFO.
2432 pid_t requestThreadTid = mRequestThread->getTid();
2433 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002434 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002435 if (res != OK) {
2436 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2437 strerror(-res), res);
2438 } else {
2439 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2440 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002441 }
2442
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002443 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002444 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2445 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2446 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2447 sessionParams.unlock(newSessionParams);
2448 mSessionParams.unlock(currentSessionParams);
2449 if (updateSessionParams) {
2450 mSessionParams = sessionParams;
2451 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002453 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002454
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002455 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002456 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002457
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002458 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002459
Zhijun He0a210512014-07-24 13:45:15 -07002460 // tear down the deleted streams after configure streams.
2461 mDeletedStreams.clear();
2462
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002463 auto rc = mPreparerThread->resume();
2464 if (rc != OK) {
2465 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2466 return rc;
2467 }
2468
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002469 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002470 mRequestBufferSM.onStreamsConfigured();
2471 }
2472
Cliff Wu3b268182021-07-06 15:44:43 +08002473 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002474 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002475 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002476 // configure the injection streams.
2477 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002478 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002479 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2480 res = mInjectionMethods->injectCamera(config, bufferSizes);
2481 if (res != OK) {
2482 ALOGE("Can't finish inject camera process!");
2483 return res;
2484 }
Cliff Wu3b268182021-07-06 15:44:43 +08002485 } else {
2486 // First run configureStreamsLocked() and then call injectCamera() case:
2487 // If the stream configuration has been completed and camera deive is active, but the
2488 // injection camera has not been injected yet, we need to store the stream configuration of
2489 // the internal camera (because the stream configuration of the injection camera is based
2490 // on the internal camera). When injecting occurs later, this configuration can be used by
2491 // the injection camera.
2492 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2493 " injection camera has not been injected yet.", __FUNCTION__);
2494 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002495 }
2496
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002498}
2499
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002500status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002501 ATRACE_CALL();
2502 status_t res;
2503
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002504 if (mFakeStreamId != NO_STREAM) {
2505 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002506 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002507 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002508 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002509 return INVALID_OPERATION;
2510 }
2511
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002512 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002513
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002514 sp<Camera3OutputStreamInterface> fakeStream =
2515 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002516
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002517 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002518 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002519 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002520 return res;
2521 }
2522
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002523 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002524 mNextStreamId++;
2525
2526 return OK;
2527}
2528
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002529status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002530 ATRACE_CALL();
2531 status_t res;
2532
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002533 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002534 if (mOutputStreams.size() == 1) return OK;
2535
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002536 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002537
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002538 // Ok, have a fake stream and there's at least one other output stream,
2539 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002540
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002541 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002542 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002543 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002544 return INVALID_OPERATION;
2545 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002546 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002547
2548 // Free up the stream endpoint so that it can be used by some other stream
2549 res = deletedStream->disconnect();
2550 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002551 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002552 // fall through since we want to still list the stream as deleted.
2553 }
2554 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556
2557 return res;
2558}
2559
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002560void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002561 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002562 Mutex::Autolock l(mLock);
2563 va_list args;
2564 va_start(args, fmt);
2565
2566 setErrorStateLockedV(fmt, args);
2567
2568 va_end(args);
2569}
2570
2571void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002572 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002573 Mutex::Autolock l(mLock);
2574 setErrorStateLockedV(fmt, args);
2575}
2576
2577void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2578 va_list args;
2579 va_start(args, fmt);
2580
2581 setErrorStateLockedV(fmt, args);
2582
2583 va_end(args);
2584}
2585
2586void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002587 // Print out all error messages to log
2588 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002589 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002590
2591 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002592 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002593
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002594 mErrorCause = errorCause;
2595
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002596 if (mRequestThread != nullptr) {
2597 mRequestThread->setPaused(true);
2598 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002599 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002600
2601 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002602 sp<NotificationListener> listener = mListener.promote();
2603 if (listener != NULL) {
2604 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002605 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002606 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002607 }
2608
2609 // Save stack trace. View by dumping it later.
2610 CameraTraces::saveTrace();
2611 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002612}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002613
2614/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002615 * In-flight request management
2616 */
2617
Jianing Weicb0652e2014-03-12 18:29:36 -07002618status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002619 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002620 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002621 const std::set<std::set<String8>>& physicalCameraIds,
2622 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2623 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002624 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002625 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002626 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002627
2628 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002629 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002630 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002631 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002632 if (res < 0) return res;
2633
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002634 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002635 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2636 // avoid a deadlock during reprocess requests.
2637 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002638 if (mStatusTracker != nullptr) {
2639 mStatusTracker->markComponentActive(mInFlightStatusId);
2640 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002641 }
2642
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002643 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002644 return OK;
2645}
2646
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002647void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002648 // Indicate idle inFlightMap to the status tracker
2649 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002650 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002651 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2652 // avoid a deadlock during reprocess requests.
2653 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002654 if (mStatusTracker != nullptr) {
2655 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2656 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002657 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002658 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002659}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002660
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002661void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002662 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002663 // something has likely gone wrong. This might still be legit only if application send in
2664 // a long burst of long exposure requests.
2665 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2666 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2667 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2668 mInFlightMap.size(), mExpectedInflightDuration);
2669 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2670 kInFlightWarnLimitHighSpeed) {
2671 CLOGW("In-flight list too large for high speed configuration: %zu,"
2672 "total inflight duration %" PRIu64,
2673 mInFlightMap.size(), mExpectedInflightDuration);
2674 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002675 }
2676}
2677
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002678void Camera3Device::onInflightMapFlushedLocked() {
2679 mExpectedInflightDuration = 0;
2680}
2681
2682void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002683 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002684 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2685 mInFlightMap.removeItemsAt(idx, 1);
2686
2687 onInflightEntryRemovedLocked(duration);
2688}
2689
2690
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002691void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002692 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002693 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002694 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002695 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002696 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002697 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002698
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002699 FlushInflightReqStates states {
2700 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002701 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002702
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002703 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002704}
2705
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002706CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002707 ALOGV("%s", __FUNCTION__);
2708
Igor Murashkin1e479c02013-09-06 16:55:14 -07002709 CameraMetadata retVal;
2710
2711 if (mRequestThread != NULL) {
2712 retVal = mRequestThread->getLatestRequest();
2713 }
2714
Igor Murashkin1e479c02013-09-06 16:55:14 -07002715 return retVal;
2716}
2717
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002718void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002719 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002720 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002721 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2722 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002723
2724 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002725 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002726}
2727
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002728/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002729 * HalInterface inner class methods
2730 */
2731
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002732void Camera3Device::HalInterface::cleanupNativeHandles(
2733 std::vector<native_handle_t*> *handles, bool closeFd) {
2734 if (handles == nullptr) {
2735 return;
2736 }
2737 if (closeFd) {
2738 for (auto& handle : *handles) {
2739 native_handle_close(handle);
2740 }
2741 }
2742 for (auto& handle : *handles) {
2743 native_handle_delete(handle);
2744 }
2745 handles->clear();
2746 return;
2747}
2748
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002749void Camera3Device::HalInterface::getInflightBufferKeys(
2750 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002751 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002752 return;
2753}
2754
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002755void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2756 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002757 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002758 return;
2759}
2760
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002761bool Camera3Device::HalInterface::verifyBufferIds(
2762 int32_t streamId, std::vector<uint64_t>& bufIds) {
2763 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002764}
2765
2766status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002767 int32_t frameNumber, int32_t streamId,
2768 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002769 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002770}
2771
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002772status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002773 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002774 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002775}
2776
2777// Find and pop a buffer_handle_t based on bufferId
2778status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002779 uint64_t bufferId,
2780 /*out*/ buffer_handle_t** buffer,
2781 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002782 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002783}
2784
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002785std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2786 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002787 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002788}
2789
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002790uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2791 const native_handle_t* handle) {
2792 return mBufferRecords.removeOneBufferCache(streamId, handle);
2793}
2794
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002795void Camera3Device::HalInterface::onBufferFreed(
2796 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002797 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2798 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2799 if (bufferId != BUFFER_ID_NO_BUFFER) {
2800 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002801 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002802}
2803
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002804void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002805 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2806 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2807 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002808 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2809 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002810}
2811
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002812/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002813 * RequestThread inner class methods
2814 */
2815
2816Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002817 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002818 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002819 bool useHalBufManager,
2820 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002821 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002822 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002823 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002825 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002826 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002827 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828 mReconfigured(false),
2829 mDoPause(false),
2830 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002831 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002832 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002833 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002834 mCurrentAfTriggerId(0),
2835 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002836 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002837 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002838 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002839 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002840 mRepeatingLastFrameNumber(
2841 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002842 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002843 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002844 mRequestLatency(kRequestLatencyBinSize),
2845 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002846 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002847 mUseHalBufManager(useHalBufManager),
2848 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002849 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002850}
2851
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002852Camera3Device::RequestThread::~RequestThread() {}
2853
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002854void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002855 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002856 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857 Mutex::Autolock l(mRequestLock);
2858 mListener = listener;
2859}
2860
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002861void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002862 const CameraMetadata& sessionParams,
2863 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002864 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002865 Mutex::Autolock l(mRequestLock);
2866 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002867 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002868 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002869 // Prepare video stream for high speed recording.
2870 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002871 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002872}
2873
Jianing Wei90e59c92014-03-12 18:29:36 -07002874status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002875 List<sp<CaptureRequest> > &requests,
2876 /*out*/
2877 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002878 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002879 Mutex::Autolock l(mRequestLock);
2880 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2881 ++it) {
2882 mRequestQueue.push_back(*it);
2883 }
2884
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002885 if (lastFrameNumber != NULL) {
2886 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2887 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2888 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2889 *lastFrameNumber);
2890 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002891
Jianing Wei90e59c92014-03-12 18:29:36 -07002892 unpauseForNewRequests();
2893
2894 return OK;
2895}
2896
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002897
2898status_t Camera3Device::RequestThread::queueTrigger(
2899 RequestTrigger trigger[],
2900 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002901 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002902 Mutex::Autolock l(mTriggerMutex);
2903 status_t ret;
2904
2905 for (size_t i = 0; i < count; ++i) {
2906 ret = queueTriggerLocked(trigger[i]);
2907
2908 if (ret != OK) {
2909 return ret;
2910 }
2911 }
2912
2913 return OK;
2914}
2915
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002916const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2917 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002918 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919 if (d != nullptr) return d->mId;
2920 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002921}
2922
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002923status_t Camera3Device::RequestThread::queueTriggerLocked(
2924 RequestTrigger trigger) {
2925
2926 uint32_t tag = trigger.metadataTag;
2927 ssize_t index = mTriggerMap.indexOfKey(tag);
2928
2929 switch (trigger.getTagType()) {
2930 case TYPE_BYTE:
2931 // fall-through
2932 case TYPE_INT32:
2933 break;
2934 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002935 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2936 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002937 return INVALID_OPERATION;
2938 }
2939
2940 /**
2941 * Collect only the latest trigger, since we only have 1 field
2942 * in the request settings per trigger tag, and can't send more than 1
2943 * trigger per request.
2944 */
2945 if (index != NAME_NOT_FOUND) {
2946 mTriggerMap.editValueAt(index) = trigger;
2947 } else {
2948 mTriggerMap.add(tag, trigger);
2949 }
2950
2951 return OK;
2952}
2953
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002954status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002955 const RequestList &requests,
2956 /*out*/
2957 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002958 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002959 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002960 if (lastFrameNumber != NULL) {
2961 *lastFrameNumber = mRepeatingLastFrameNumber;
2962 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002963 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002964 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002965 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2966 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002967
2968 unpauseForNewRequests();
2969
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002970 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971 return OK;
2972}
2973
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002974bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002975 if (mRepeatingRequests.empty()) {
2976 return false;
2977 }
2978 int32_t requestId = requestIn->mResultExtras.requestId;
2979 const RequestList &repeatRequests = mRepeatingRequests;
2980 // All repeating requests are guaranteed to have same id so only check first quest
2981 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2982 return (firstRequest->mResultExtras.requestId == requestId);
2983}
2984
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002985status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002986 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002987 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07002988 return clearRepeatingRequestsLocked(lastFrameNumber);
2989
2990}
2991
2992status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08002993 std::vector<int32_t> streamIds;
2994 for (const auto& request : mRepeatingRequests) {
2995 for (const auto& stream : request->mOutputStreams) {
2996 streamIds.push_back(stream->getId());
2997 }
2998 }
2999
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003000 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003001 if (lastFrameNumber != NULL) {
3002 *lastFrameNumber = mRepeatingLastFrameNumber;
3003 }
Emilian Peev2295df72021-11-12 18:14:10 -08003004
3005 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3006
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003007 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003008 return OK;
3009}
3010
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003011status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003012 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003013 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003014 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003015 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003016
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003017 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003018
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003019 // Send errors for all requests pending in the request queue, including
3020 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003021 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003022 if (listener != NULL) {
3023 for (RequestList::iterator it = mRequestQueue.begin();
3024 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003025 // Abort the input buffers for reprocess requests.
3026 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003027 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003028 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003029 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003030 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003031 if (res != OK) {
3032 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3033 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3034 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003035 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003036 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3037 if (res != OK) {
3038 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3039 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3040 }
3041 }
3042 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003043 // Set the frame number this request would have had, if it
3044 // had been submitted; this frame number will not be reused.
3045 // The requestId and burstId fields were set when the request was
3046 // submitted originally (in convertMetadataListToRequestListLocked)
3047 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003048 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003049 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003050 }
3051 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003052 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003053
3054 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003055 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003056 if (lastFrameNumber != NULL) {
3057 *lastFrameNumber = mRepeatingLastFrameNumber;
3058 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003059 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003060 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003061 return OK;
3062}
3063
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003064status_t Camera3Device::RequestThread::flush() {
3065 ATRACE_CALL();
3066 Mutex::Autolock l(mFlushLock);
3067
Emilian Peev08dd2452017-04-06 16:55:14 +01003068 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003069}
3070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003071void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003072 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003073 Mutex::Autolock l(mPauseLock);
3074 mDoPause = paused;
3075 mDoPauseSignal.signal();
3076}
3077
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003078status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3079 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003080 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003081 Mutex::Autolock l(mLatestRequestMutex);
3082 status_t res;
3083 while (mLatestRequestId != requestId) {
3084 nsecs_t startTime = systemTime();
3085
3086 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3087 if (res != OK) return res;
3088
3089 timeout -= (systemTime() - startTime);
3090 }
3091
3092 return OK;
3093}
3094
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003095void Camera3Device::RequestThread::requestExit() {
3096 // Call parent to set up shutdown
3097 Thread::requestExit();
3098 // The exit from any possible waits
3099 mDoPauseSignal.signal();
3100 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003101
3102 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3103 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003104}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003105
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003106void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003107 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003108 bool surfaceAbandoned = false;
3109 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003110 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003111 {
3112 Mutex::Autolock l(mRequestLock);
3113 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3114 // repeating requests.
3115 for (const auto& request : mRepeatingRequests) {
3116 for (const auto& s : request->mOutputStreams) {
3117 if (s->isAbandoned()) {
3118 surfaceAbandoned = true;
3119 clearRepeatingRequestsLocked(&lastFrameNumber);
3120 break;
3121 }
3122 }
3123 if (surfaceAbandoned) {
3124 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003125 }
3126 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003127 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003128 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003129
3130 if (listener != NULL && surfaceAbandoned) {
3131 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003132 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003133}
3134
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003135bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003136 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003137 status_t res;
3138 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003139 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003140 uint32_t numRequestProcessed = 0;
3141 for (size_t i = 0; i < batchSize; i++) {
3142 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003143 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003144 }
3145
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003146 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3147
3148 bool triggerRemoveFailed = false;
3149 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3150 for (size_t i = 0; i < numRequestProcessed; i++) {
3151 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3152 nextRequest.submitted = true;
3153
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003154 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003155
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003156 if (!triggerRemoveFailed) {
3157 // Remove any previously queued triggers (after unlock)
3158 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3159 if (removeTriggerRes != OK) {
3160 triggerRemoveFailed = true;
3161 triggerFailedRequest = nextRequest;
3162 }
3163 }
3164 }
3165
3166 if (triggerRemoveFailed) {
3167 SET_ERR("RequestThread: Unable to remove triggers "
3168 "(capture request %d, HAL device: %s (%d)",
3169 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3170 cleanUpFailedRequests(/*sendRequestError*/ false);
3171 return false;
3172 }
3173
3174 if (res != OK) {
3175 // Should only get a failure here for malformed requests or device-level
3176 // errors, so consider all errors fatal. Bad metadata failures should
3177 // come through notify.
3178 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3179 mNextRequests[numRequestProcessed].halRequest.frame_number,
3180 strerror(-res), res);
3181 cleanUpFailedRequests(/*sendRequestError*/ false);
3182 return false;
3183 }
3184 return true;
3185}
3186
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003187nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3188 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3189 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3190 find_camera_metadata_ro_entry(request,
3191 ANDROID_CONTROL_AE_MODE,
3192 &e);
3193 if (e.count == 0) return maxExpectedDuration;
3194
3195 switch (e.data.u8[0]) {
3196 case ANDROID_CONTROL_AE_MODE_OFF:
3197 find_camera_metadata_ro_entry(request,
3198 ANDROID_SENSOR_EXPOSURE_TIME,
3199 &e);
3200 if (e.count > 0) {
3201 maxExpectedDuration = e.data.i64[0];
3202 }
3203 find_camera_metadata_ro_entry(request,
3204 ANDROID_SENSOR_FRAME_DURATION,
3205 &e);
3206 if (e.count > 0) {
3207 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3208 }
3209 break;
3210 default:
3211 find_camera_metadata_ro_entry(request,
3212 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3213 &e);
3214 if (e.count > 1) {
3215 maxExpectedDuration = 1e9 / e.data.u8[0];
3216 }
3217 break;
3218 }
3219
3220 return maxExpectedDuration;
3221}
3222
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003223bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3224 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3225 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3226 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3227 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3228 return true;
3229 }
3230
3231 return false;
3232}
3233
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003234void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3235 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003236 camera_capture_request_t& halRequest = nextRequest.halRequest;
3237 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003238 Mutex::Autolock al(mLatestRequestMutex);
3239
Shuzhen Wang83bff122020-11-20 15:51:39 -08003240 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003241 mLatestRequest.acquire(cloned);
3242
3243 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003244 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3245 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3246 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003247 CameraMetadata(cloned));
3248 }
3249
3250 sp<Camera3Device> parent = mParent.promote();
3251 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003252 int32_t inputStreamId = -1;
3253 if (halRequest.input_buffer != nullptr) {
3254 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3255 }
3256
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003257 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003258 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003259 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3260 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003261 }
3262 }
3263
Shuzhen Wang83bff122020-11-20 15:51:39 -08003264 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003265 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003266 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003267 }
3268
Shuzhen Wang83bff122020-11-20 15:51:39 -08003269 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003270}
3271
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003272bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3273 ATRACE_CALL();
3274 bool updatesDetected = false;
3275
Emilian Peev4ec17882019-01-24 17:16:58 -08003276 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003277 for (auto tag : mSessionParamKeys) {
3278 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003279 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003280
3281 if (entry.count > 0) {
3282 bool isDifferent = false;
3283 if (lastEntry.count > 0) {
3284 // Have a last value, compare to see if changed
3285 if (lastEntry.type == entry.type &&
3286 lastEntry.count == entry.count) {
3287 // Same type and count, compare values
3288 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3289 size_t entryBytes = bytesPerValue * lastEntry.count;
3290 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3291 if (cmp != 0) {
3292 isDifferent = true;
3293 }
3294 } else {
3295 // Count or type has changed
3296 isDifferent = true;
3297 }
3298 } else {
3299 // No last entry, so always consider to be different
3300 isDifferent = true;
3301 }
3302
3303 if (isDifferent) {
3304 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003305 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3306 updatesDetected = true;
3307 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003308 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003309 }
3310 } else if (lastEntry.count > 0) {
3311 // Value has been removed
3312 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003313 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003314 updatesDetected = true;
3315 }
3316 }
3317
Emilian Peev4ec17882019-01-24 17:16:58 -08003318 bool reconfigureRequired;
3319 if (updatesDetected) {
3320 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3321 updatedParams);
3322 mLatestSessionParams = updatedParams;
3323 } else {
3324 reconfigureRequired = false;
3325 }
3326
3327 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003328}
3329
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003330bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003331 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003332 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003333 // Any function called from threadLoop() must not hold mInterfaceLock since
3334 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3335 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003336
3337 // Handle paused state.
3338 if (waitIfPaused()) {
3339 return true;
3340 }
3341
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003342 // Wait for the next batch of requests.
3343 waitForNextRequestBatch();
3344 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003345 return true;
3346 }
3347
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003348 // Get the latest request ID, if any
3349 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003350 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003351 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003352 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003353 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003354 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003355 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3356 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003357 }
3358
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003359 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3360 // or a single request from streaming or burst. In either case the first element
3361 // should contain the latest camera settings that we need to check for any session
3362 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003363 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003364 res = OK;
3365
3366 //Input stream buffers are already acquired at this point so an input stream
3367 //will not be able to move to idle state unless we force it.
3368 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3369 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3370 if (res != OK) {
3371 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3372 cleanUpFailedRequests(/*sendRequestError*/ false);
3373 return false;
3374 }
3375 }
3376
3377 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003378 sp<Camera3Device> parent = mParent.promote();
3379 if (parent != nullptr) {
3380 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003381 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003382 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003383
3384 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3385 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3386 if (res != OK) {
3387 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3388 cleanUpFailedRequests(/*sendRequestError*/ false);
3389 return false;
3390 }
3391 }
3392 }
3393 }
3394
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003395 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003396 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003397 if (res == TIMED_OUT) {
3398 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003399 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003400 // Check if any stream is abandoned.
3401 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003402 return true;
3403 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003404 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003405 return false;
3406 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003407
Zhijun Hecc27e112013-10-03 16:12:43 -07003408 // Inform waitUntilRequestProcessed thread of a new request ID
3409 {
3410 Mutex::Autolock al(mLatestRequestMutex);
3411
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003412 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003413 mLatestRequestSignal.signal();
3414 }
3415
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003416 // Submit a batch of requests to HAL.
3417 // Use flush lock only when submitting multilple requests in a batch.
3418 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3419 // which may take a long time to finish so synchronizing flush() and
3420 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3421 // For now, only synchronize for high speed recording and we should figure something out for
3422 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003423 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003424
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003425 if (useFlushLock) {
3426 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003427 }
3428
Zhijun Hef0645c12016-08-02 00:58:11 -07003429 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003430 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003431
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003432 sp<Camera3Device> parent = mParent.promote();
3433 if (parent != nullptr) {
3434 parent->mRequestBufferSM.onSubmittingRequest();
3435 }
3436
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003437 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003438 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003439 submitRequestSuccess = sendRequestsBatch();
3440
Shuzhen Wang686f6442017-06-20 16:16:04 -07003441 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3442 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003443
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003444 if (useFlushLock) {
3445 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003446 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003447
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003448 // Unset as current request
3449 {
3450 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003451 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003452 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003453 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003454
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003455 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003456}
3457
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003458status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3459 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3460 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3461 ANDROID_SCALER_CROP_REGION_SET};
3462 if (request == nullptr) {
3463 ALOGE("%s request metadata nullptr", __FUNCTION__);
3464 return BAD_VALUE;
3465 }
3466 status_t res = OK;
3467 for (const auto &key : kFwkOnlyRegionKeys) {
3468 if (request->exists(key)) {
3469 res = request->erase(key);
3470 if (res != OK) {
3471 return res;
3472 }
3473 }
3474 }
3475 return OK;
3476}
3477
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003478status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003479 ATRACE_CALL();
3480
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003481 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003482 for (size_t i = 0; i < mNextRequests.size(); i++) {
3483 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003484 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003485 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3486 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003487
3488 // Prepare a request to HAL
3489 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3490
3491 // Insert any queued triggers (before metadata is locked)
3492 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003493 if (res < 0) {
3494 SET_ERR("RequestThread: Unable to insert triggers "
3495 "(capture request %d, HAL device: %s (%d)",
3496 halRequest->frame_number, strerror(-res), res);
3497 return INVALID_OPERATION;
3498 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003499
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003500 int triggerCount = res;
3501 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3502 mPrevTriggers = triggerCount;
3503
Emilian Peeve23f1d92021-09-20 14:56:01 -07003504 // Do not override rotate&crop for stream configurations that include
3505 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3506 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3507 bool rotateAndCropChanged = mComposerOutput ? false :
3508 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003509 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003510
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003511 // If the request is the same as last, or we had triggers now or last time or
3512 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003513 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003514 (mPrevRequest != captureRequest || triggersMixedIn ||
3515 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003516 // Request settings are all the same within one batch, so only treat the first
3517 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003518 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003519 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003520 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003521 /**
3522 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003523 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003524 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003525 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003526 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003527 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003528 "(capture request %d, HAL device: %s (%d)",
3529 halRequest->frame_number, strerror(-res), res);
3530 return INVALID_OPERATION;
3531 }
3532
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003533 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003534 sp<Camera3Device> parent = mParent.promote();
3535 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003536 List<PhysicalCameraSettings>::iterator it;
3537 for (it = captureRequest->mSettingsList.begin();
3538 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003539 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3540 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003541 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3542 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3543 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3544 res);
3545 return INVALID_OPERATION;
3546 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003547 continue;
3548 }
3549
3550 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3551 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3552 updateCaptureRequest(&(it->metadata));
3553 if (res != OK) {
3554 SET_ERR("RequestThread: Unable to correct capture requests "
3555 "for scaler crop region and metering regions for request "
3556 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3557 res);
3558 return INVALID_OPERATION;
3559 }
3560 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003561 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3562 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3563 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3564 res);
3565 return INVALID_OPERATION;
3566 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003567 }
3568 }
3569
3570 // Correct metadata regions for distortion correction if enabled
3571 for (it = captureRequest->mSettingsList.begin();
3572 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003573 if (parent->mDistortionMappers.find(it->cameraId) ==
3574 parent->mDistortionMappers.end()) {
3575 continue;
3576 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003577
3578 if (!captureRequest->mDistortionCorrectionUpdated) {
3579 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3580 &(it->metadata));
3581 if (res != OK) {
3582 SET_ERR("RequestThread: Unable to correct capture requests "
3583 "for lens distortion for request %d: %s (%d)",
3584 halRequest->frame_number, strerror(-res), res);
3585 return INVALID_OPERATION;
3586 }
3587 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003588 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003589 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003590
3591 for (it = captureRequest->mSettingsList.begin();
3592 it != captureRequest->mSettingsList.end(); it++) {
3593 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3594 parent->mZoomRatioMappers.end()) {
3595 continue;
3596 }
3597
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003598 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003599 cameraIdsWithZoom.insert(it->cameraId);
3600 }
3601
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003602 if (!captureRequest->mZoomRatioUpdated) {
3603 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3604 &(it->metadata));
3605 if (res != OK) {
3606 SET_ERR("RequestThread: Unable to correct capture requests "
3607 "for zoom ratio for request %d: %s (%d)",
3608 halRequest->frame_number, strerror(-res), res);
3609 return INVALID_OPERATION;
3610 }
3611 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003612 }
3613 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003614 if (captureRequest->mRotateAndCropAuto &&
3615 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003616 for (it = captureRequest->mSettingsList.begin();
3617 it != captureRequest->mSettingsList.end(); it++) {
3618 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3619 if (mapper != parent->mRotateAndCropMappers.end()) {
3620 res = mapper->second.updateCaptureRequest(&(it->metadata));
3621 if (res != OK) {
3622 SET_ERR("RequestThread: Unable to correct capture requests "
3623 "for rotate-and-crop for request %d: %s (%d)",
3624 halRequest->frame_number, strerror(-res), res);
3625 return INVALID_OPERATION;
3626 }
3627 }
3628 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003629 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003630 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003631 }
3632 }
3633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003634 /**
3635 * The request should be presorted so accesses in HAL
3636 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3637 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003638 captureRequest->mSettingsList.begin()->metadata.sort();
3639 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003640 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003641 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003642 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3643
3644 IF_ALOGV() {
3645 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3646 find_camera_metadata_ro_entry(
3647 halRequest->settings,
3648 ANDROID_CONTROL_AF_TRIGGER,
3649 &e
3650 );
3651 if (e.count > 0) {
3652 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3653 __FUNCTION__,
3654 halRequest->frame_number,
3655 e.data.u8[0]);
3656 }
3657 }
3658 } else {
3659 // leave request.settings NULL to indicate 'reuse latest given'
3660 ALOGVV("%s: Request settings are REUSED",
3661 __FUNCTION__);
3662 }
3663
Emilian Peevaebbe412018-01-15 13:53:24 +00003664 if (captureRequest->mSettingsList.size() > 1) {
3665 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3666 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003667 if (newRequest) {
3668 halRequest->physcam_settings =
3669 new const camera_metadata* [halRequest->num_physcam_settings];
3670 } else {
3671 halRequest->physcam_settings = nullptr;
3672 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003673 auto it = ++captureRequest->mSettingsList.begin();
3674 size_t i = 0;
3675 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3676 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003677 if (newRequest) {
3678 it->metadata.sort();
3679 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3680 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003681 }
3682 }
3683
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003684 uint32_t totalNumBuffers = 0;
3685
3686 // Fill in buffers
3687 if (captureRequest->mInputStream != NULL) {
3688 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003689
3690 halRequest->input_width = captureRequest->mInputBufferSize.width;
3691 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003692 totalNumBuffers += 1;
3693 } else {
3694 halRequest->input_buffer = NULL;
3695 }
3696
Emilian Peevf4816702020-04-03 15:44:51 -07003697 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003698 captureRequest->mOutputStreams.size());
3699 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003700 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003701
3702 sp<Camera3Device> parent = mParent.promote();
3703 if (parent == NULL) {
3704 // Should not happen, and nowhere to send errors to, so just log it
3705 CLOGE("RequestThread: Parent is gone");
3706 return INVALID_OPERATION;
3707 }
3708 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3709
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003710 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003711 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003712 sp<Camera3OutputStreamInterface> outputStream =
3713 captureRequest->mOutputStreams.editItemAt(j);
3714 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003715
3716 // Prepare video buffers for high speed recording on the first video request.
3717 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3718 // Only try to prepare video stream on the first video request.
3719 mPrepareVideoStream = false;
3720
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003721 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3722 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003723 while (res == NOT_ENOUGH_DATA) {
3724 res = outputStream->prepareNextBuffer();
3725 }
3726 if (res != OK) {
3727 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3728 __FUNCTION__, strerror(-res), res);
3729 outputStream->cancelPrepare();
3730 }
3731 }
3732
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003733 std::vector<size_t> uniqueSurfaceIds;
3734 res = outputStream->getUniqueSurfaceIds(
3735 captureRequest->mOutputSurfaces[streamId],
3736 &uniqueSurfaceIds);
3737 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3738 if (res != OK && res != INVALID_OPERATION) {
3739 ALOGE("%s: failed to query stream %d unique surface IDs",
3740 __FUNCTION__, streamId);
3741 return res;
3742 }
3743 if (res == OK) {
3744 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3745 }
3746
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003747 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003748 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003749 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003750 return TIMED_OUT;
3751 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003752 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003753 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003754 buffer.stream = outputStream->asHalStream();
3755 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003756 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003757 buffer.acquire_fence = -1;
3758 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003759 // Mark the output stream as unpreparable to block clients from calling
3760 // 'prepare' after this request reaches CameraHal and before the respective
3761 // buffers are requested.
3762 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003763 } else {
3764 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3765 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003766 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003767 if (res != OK) {
3768 // Can't get output buffer from gralloc queue - this could be due to
3769 // abandoned queue or other consumer misbehavior, so not a fatal
3770 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003771 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003772 " %s (%d)", strerror(-res), res);
3773
3774 return TIMED_OUT;
3775 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003776 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003777
3778 {
3779 sp<Camera3Device> parent = mParent.promote();
3780 if (parent != nullptr) {
3781 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3782 for (const auto& settings : captureRequest->mSettingsList) {
3783 if ((streamCameraId.isEmpty() &&
3784 parent->getId() == settings.cameraId.c_str()) ||
3785 streamCameraId == settings.cameraId.c_str()) {
3786 outputStream->fireBufferRequestForFrameNumber(
3787 captureRequest->mResultExtras.frameNumber,
3788 settings.metadata);
3789 }
3790 }
3791 }
3792 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003793
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003794 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003795 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3796 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3797 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3798 } else if (!physicalCameraId.isEmpty()) {
3799 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003800 }
3801 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003802 }
3803 totalNumBuffers += halRequest->num_output_buffers;
3804
3805 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003806 // If this request list is for constrained high speed recording (not
3807 // preview), and the current request is not the last one in the batch,
3808 // do not send callback to the app.
3809 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003810 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003811 hasCallback = false;
3812 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003813 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003814 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003815 const camera_metadata_t* settings = halRequest->settings;
3816 bool shouldUnlockSettings = false;
3817 if (settings == nullptr) {
3818 shouldUnlockSettings = true;
3819 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3820 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003821 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3822 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003823 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003824 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3825 isStillCapture = true;
3826 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3827 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003828
Emilian Peevaf8416e2021-02-04 17:52:43 -08003829 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003830 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003831 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3832 isZslCapture = true;
3833 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003834 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003835 res = parent->registerInFlight(halRequest->frame_number,
3836 totalNumBuffers, captureRequest->mResultExtras,
3837 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003838 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003839 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003840 requestedPhysicalCameras, isStillCapture, isZslCapture,
3841 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003842 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003843 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003844 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3845 ", burstId = %" PRId32 ".",
3846 __FUNCTION__,
3847 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3848 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003849
3850 if (shouldUnlockSettings) {
3851 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3852 }
3853
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003854 if (res != OK) {
3855 SET_ERR("RequestThread: Unable to register new in-flight request:"
3856 " %s (%d)", strerror(-res), res);
3857 return INVALID_OPERATION;
3858 }
3859 }
3860
3861 return OK;
3862}
3863
Igor Murashkin1e479c02013-09-06 16:55:14 -07003864CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003865 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003866 Mutex::Autolock al(mLatestRequestMutex);
3867
3868 ALOGV("RequestThread::%s", __FUNCTION__);
3869
3870 return mLatestRequest;
3871}
3872
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003873bool Camera3Device::RequestThread::isStreamPending(
3874 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003875 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003876 Mutex::Autolock l(mRequestLock);
3877
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003878 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003879 if (!nextRequest.submitted) {
3880 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3881 if (stream == s) return true;
3882 }
3883 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003884 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003885 }
3886
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003887 for (const auto& request : mRequestQueue) {
3888 for (const auto& s : request->mOutputStreams) {
3889 if (stream == s) return true;
3890 }
3891 if (stream == request->mInputStream) return true;
3892 }
3893
3894 for (const auto& request : mRepeatingRequests) {
3895 for (const auto& s : request->mOutputStreams) {
3896 if (stream == s) return true;
3897 }
3898 if (stream == request->mInputStream) return true;
3899 }
3900
3901 return false;
3902}
Jianing Weicb0652e2014-03-12 18:29:36 -07003903
Emilian Peev40ead602017-09-26 15:46:36 +01003904bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3905 ATRACE_CALL();
3906 Mutex::Autolock l(mRequestLock);
3907
3908 for (const auto& nextRequest : mNextRequests) {
3909 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3910 if (s.first == streamId) {
3911 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3912 if (it != s.second.end()) {
3913 return true;
3914 }
3915 }
3916 }
3917 }
3918
3919 for (const auto& request : mRequestQueue) {
3920 for (const auto& s : request->mOutputSurfaces) {
3921 if (s.first == streamId) {
3922 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3923 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003924 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003925 }
3926 }
3927 }
3928 }
3929
3930 for (const auto& request : mRepeatingRequests) {
3931 for (const auto& s : request->mOutputSurfaces) {
3932 if (s.first == streamId) {
3933 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3934 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003935 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003936 }
3937 }
3938 }
3939 }
3940
3941 return false;
3942}
3943
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003944void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3945 if (!mUseHalBufManager) {
3946 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3947 return;
3948 }
3949
3950 Mutex::Autolock pl(mPauseLock);
3951 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003952 mInterface->signalPipelineDrain(streamIds);
3953 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003954 }
3955 // If request thread is still busy, wait until paused then notify HAL
3956 mNotifyPipelineDrain = true;
3957 mStreamIdsToBeDrained = streamIds;
3958}
3959
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003960void Camera3Device::RequestThread::resetPipelineDrain() {
3961 Mutex::Autolock pl(mPauseLock);
3962 mNotifyPipelineDrain = false;
3963 mStreamIdsToBeDrained.clear();
3964}
3965
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003966void Camera3Device::RequestThread::clearPreviousRequest() {
3967 Mutex::Autolock l(mRequestLock);
3968 mPrevRequest.clear();
3969}
3970
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003971status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3972 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3973 ATRACE_CALL();
3974 Mutex::Autolock l(mTriggerMutex);
3975 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3976 return BAD_VALUE;
3977 }
3978 mRotateAndCropOverride = rotateAndCropValue;
3979 return OK;
3980}
3981
Emilian Peeve23f1d92021-09-20 14:56:01 -07003982status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3983 ATRACE_CALL();
3984 Mutex::Autolock l(mTriggerMutex);
3985 mComposerOutput = composerSurfacePresent;
3986 return OK;
3987}
3988
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003989status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003990 ATRACE_CALL();
3991 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07003992 if (muteMode != mCameraMute) {
3993 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003994 mCameraMuteChanged = true;
3995 }
3996 return OK;
3997}
3998
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003999nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004000 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004001 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004002 return mExpectedInflightDuration > kMinInflightDuration ?
4003 mExpectedInflightDuration : kMinInflightDuration;
4004}
4005
Emilian Peevaebbe412018-01-15 13:53:24 +00004006void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004007 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004008 if ((request == nullptr) || (halRequest == nullptr)) {
4009 ALOGE("%s: Invalid request!", __FUNCTION__);
4010 return;
4011 }
4012
4013 if (halRequest->num_physcam_settings > 0) {
4014 if (halRequest->physcam_id != nullptr) {
4015 delete [] halRequest->physcam_id;
4016 halRequest->physcam_id = nullptr;
4017 }
4018 if (halRequest->physcam_settings != nullptr) {
4019 auto it = ++(request->mSettingsList.begin());
4020 size_t i = 0;
4021 for (; it != request->mSettingsList.end(); it++, i++) {
4022 it->metadata.unlock(halRequest->physcam_settings[i]);
4023 }
4024 delete [] halRequest->physcam_settings;
4025 halRequest->physcam_settings = nullptr;
4026 }
4027 }
4028}
4029
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004030void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4031 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004032 return;
4033 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004034
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004035 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004036 // Skip the ones that have been submitted successfully.
4037 if (nextRequest.submitted) {
4038 continue;
4039 }
4040
4041 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004042 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4043 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004044
4045 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004046 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004047 }
4048
Emilian Peevaebbe412018-01-15 13:53:24 +00004049 cleanupPhysicalSettings(captureRequest, halRequest);
4050
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004051 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004052 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004053 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4054 }
4055
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004056 // No output buffer can be returned when using HAL buffer manager
4057 if (!mUseHalBufManager) {
4058 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4059 //Buffers that failed processing could still have
4060 //valid acquire fence.
4061 int acquireFence = (*outputBuffers)[i].acquire_fence;
4062 if (0 <= acquireFence) {
4063 close(acquireFence);
4064 outputBuffers->editItemAt(i).acquire_fence = -1;
4065 }
Emilian Peevf4816702020-04-03 15:44:51 -07004066 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004067 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4068 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004069 /*timestampIncreasing*/true, std::vector<size_t> (),
4070 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004071 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072 }
4073
4074 if (sendRequestError) {
4075 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004076 sp<NotificationListener> listener = mListener.promote();
4077 if (listener != NULL) {
4078 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004079 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004080 captureRequest->mResultExtras);
4081 }
4082 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004083
4084 // Remove yet-to-be submitted inflight request from inflightMap
4085 {
4086 sp<Camera3Device> parent = mParent.promote();
4087 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004088 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004089 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4090 if (idx >= 0) {
4091 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4092 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4093 parent->removeInFlightMapEntryLocked(idx);
4094 }
4095 }
4096 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004097 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004098
4099 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004100 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004101}
4102
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004103void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004104 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004105 // Optimized a bit for the simple steady-state case (single repeating
4106 // request), to avoid putting that request in the queue temporarily.
4107 Mutex::Autolock l(mRequestLock);
4108
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004109 assert(mNextRequests.empty());
4110
4111 NextRequest nextRequest;
4112 nextRequest.captureRequest = waitForNextRequestLocked();
4113 if (nextRequest.captureRequest == nullptr) {
4114 return;
4115 }
4116
Emilian Peevf4816702020-04-03 15:44:51 -07004117 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004118 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004119 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004120
4121 // Wait for additional requests
4122 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4123
4124 for (size_t i = 1; i < batchSize; i++) {
4125 NextRequest additionalRequest;
4126 additionalRequest.captureRequest = waitForNextRequestLocked();
4127 if (additionalRequest.captureRequest == nullptr) {
4128 break;
4129 }
4130
Emilian Peevf4816702020-04-03 15:44:51 -07004131 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004133 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004134 }
4135
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004136 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004137 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004138 mNextRequests.size(), batchSize);
4139 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004140 }
4141
4142 return;
4143}
4144
4145sp<Camera3Device::CaptureRequest>
4146 Camera3Device::RequestThread::waitForNextRequestLocked() {
4147 status_t res;
4148 sp<CaptureRequest> nextRequest;
4149
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004150 while (mRequestQueue.empty()) {
4151 if (!mRepeatingRequests.empty()) {
4152 // Always atomically enqueue all requests in a repeating request
4153 // list. Guarantees a complete in-sequence set of captures to
4154 // application.
4155 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004156 if (mFirstRepeating) {
4157 mFirstRepeating = false;
4158 } else {
4159 for (auto& request : requests) {
4160 // For repeating requests, override timestamp request using
4161 // the time a request is inserted into the request queue,
4162 // because the original repeating request will have an old
4163 // fixed timestamp.
4164 request->mRequestTimeNs = systemTime();
4165 }
4166 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004167 RequestList::const_iterator firstRequest =
4168 requests.begin();
4169 nextRequest = *firstRequest;
4170 mRequestQueue.insert(mRequestQueue.end(),
4171 ++firstRequest,
4172 requests.end());
4173 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004174
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004175 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004176
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004177 break;
4178 }
4179
4180 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4181
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004182 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4183 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004184 Mutex::Autolock pl(mPauseLock);
4185 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004186 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004187 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004188 if (mNotifyPipelineDrain) {
4189 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4190 mNotifyPipelineDrain = false;
4191 mStreamIdsToBeDrained.clear();
4192 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004193 // Let the tracker know
4194 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4195 if (statusTracker != 0) {
4196 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4197 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004198 sp<Camera3Device> parent = mParent.promote();
4199 if (parent != nullptr) {
4200 parent->mRequestBufferSM.onRequestThreadPaused();
4201 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004202 }
4203 // Stop waiting for now and let thread management happen
4204 return NULL;
4205 }
4206 }
4207
4208 if (nextRequest == NULL) {
4209 // Don't have a repeating request already in hand, so queue
4210 // must have an entry now.
4211 RequestList::iterator firstRequest =
4212 mRequestQueue.begin();
4213 nextRequest = *firstRequest;
4214 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004215 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4216 sp<NotificationListener> listener = mListener.promote();
4217 if (listener != NULL) {
4218 listener->notifyRequestQueueEmpty();
4219 }
4220 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004221 }
4222
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004223 // In case we've been unpaused by setPaused clearing mDoPause, need to
4224 // update internal pause state (capture/setRepeatingRequest unpause
4225 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004226 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004227 if (mPaused) {
4228 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4229 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4230 if (statusTracker != 0) {
4231 statusTracker->markComponentActive(mStatusId);
4232 }
4233 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234 mPaused = false;
4235
4236 // Check if we've reconfigured since last time, and reset the preview
4237 // request if so. Can't use 'NULL request == repeat' across configure calls.
4238 if (mReconfigured) {
4239 mPrevRequest.clear();
4240 mReconfigured = false;
4241 }
4242
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004243 if (nextRequest != NULL) {
4244 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004245 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4246 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004247
4248 // Since RequestThread::clear() removes buffers from the input stream,
4249 // get the right buffer here before unlocking mRequestLock
4250 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004251 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4252 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004253 if (res != OK) {
4254 // Can't get input buffer from gralloc queue - this could be due to
4255 // disconnected queue or other producer misbehavior, so not a fatal
4256 // error
4257 ALOGE("%s: Can't get input buffer, skipping request:"
4258 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004259
4260 sp<NotificationListener> listener = mListener.promote();
4261 if (listener != NULL) {
4262 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004263 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004264 nextRequest->mResultExtras);
4265 }
4266 return NULL;
4267 }
4268 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004269 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004270
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004271 return nextRequest;
4272}
4273
4274bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004275 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276 status_t res;
4277 Mutex::Autolock l(mPauseLock);
4278 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004279 if (mPaused == false) {
4280 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004281 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004282 if (mNotifyPipelineDrain) {
4283 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4284 mNotifyPipelineDrain = false;
4285 mStreamIdsToBeDrained.clear();
4286 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004287 // Let the tracker know
4288 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4289 if (statusTracker != 0) {
4290 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4291 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004292 sp<Camera3Device> parent = mParent.promote();
4293 if (parent != nullptr) {
4294 parent->mRequestBufferSM.onRequestThreadPaused();
4295 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004296 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004299 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004300 return true;
4301 }
4302 }
4303 // We don't set mPaused to false here, because waitForNextRequest needs
4304 // to further manage the paused state in case of starvation.
4305 return false;
4306}
4307
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004308void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004309 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004310 // With work to do, mark thread as unpaused.
4311 // If paused by request (setPaused), don't resume, to avoid
4312 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004313 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004314 Mutex::Autolock p(mPauseLock);
4315 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004316 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4317 if (mPaused) {
4318 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4319 if (statusTracker != 0) {
4320 statusTracker->markComponentActive(mStatusId);
4321 }
4322 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004323 mPaused = false;
4324 }
4325}
4326
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004327void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4328 sp<Camera3Device> parent = mParent.promote();
4329 if (parent != NULL) {
4330 va_list args;
4331 va_start(args, fmt);
4332
4333 parent->setErrorStateV(fmt, args);
4334
4335 va_end(args);
4336 }
4337}
4338
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004339status_t Camera3Device::RequestThread::insertTriggers(
4340 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004341 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004342 Mutex::Autolock al(mTriggerMutex);
4343
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004344 sp<Camera3Device> parent = mParent.promote();
4345 if (parent == NULL) {
4346 CLOGE("RequestThread: Parent is gone");
4347 return DEAD_OBJECT;
4348 }
4349
Emilian Peevaebbe412018-01-15 13:53:24 +00004350 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004351 size_t count = mTriggerMap.size();
4352
4353 for (size_t i = 0; i < count; ++i) {
4354 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004355 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004356
4357 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4358 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4359 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004360 if (isAeTrigger) {
4361 request->mResultExtras.precaptureTriggerId = triggerId;
4362 mCurrentPreCaptureTriggerId = triggerId;
4363 } else {
4364 request->mResultExtras.afTriggerId = triggerId;
4365 mCurrentAfTriggerId = triggerId;
4366 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004367 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004368 }
4369
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004370 camera_metadata_entry entry = metadata.find(tag);
4371
4372 if (entry.count > 0) {
4373 /**
4374 * Already has an entry for this trigger in the request.
4375 * Rewrite it with our requested trigger value.
4376 */
4377 RequestTrigger oldTrigger = trigger;
4378
4379 oldTrigger.entryValue = entry.data.u8[0];
4380
4381 mTriggerReplacedMap.add(tag, oldTrigger);
4382 } else {
4383 /**
4384 * More typical, no trigger entry, so we just add it
4385 */
4386 mTriggerRemovedMap.add(tag, trigger);
4387 }
4388
4389 status_t res;
4390
4391 switch (trigger.getTagType()) {
4392 case TYPE_BYTE: {
4393 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4394 res = metadata.update(tag,
4395 &entryValue,
4396 /*count*/1);
4397 break;
4398 }
4399 case TYPE_INT32:
4400 res = metadata.update(tag,
4401 &trigger.entryValue,
4402 /*count*/1);
4403 break;
4404 default:
4405 ALOGE("%s: Type not supported: 0x%x",
4406 __FUNCTION__,
4407 trigger.getTagType());
4408 return INVALID_OPERATION;
4409 }
4410
4411 if (res != OK) {
4412 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4413 ", value %d", __FUNCTION__, trigger.getTagName(),
4414 trigger.entryValue);
4415 return res;
4416 }
4417
4418 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4419 trigger.getTagName(),
4420 trigger.entryValue);
4421 }
4422
4423 mTriggerMap.clear();
4424
4425 return count;
4426}
4427
4428status_t Camera3Device::RequestThread::removeTriggers(
4429 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004430 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004431 Mutex::Autolock al(mTriggerMutex);
4432
Emilian Peevaebbe412018-01-15 13:53:24 +00004433 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004434
4435 /**
4436 * Replace all old entries with their old values.
4437 */
4438 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4439 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4440
4441 status_t res;
4442
4443 uint32_t tag = trigger.metadataTag;
4444 switch (trigger.getTagType()) {
4445 case TYPE_BYTE: {
4446 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4447 res = metadata.update(tag,
4448 &entryValue,
4449 /*count*/1);
4450 break;
4451 }
4452 case TYPE_INT32:
4453 res = metadata.update(tag,
4454 &trigger.entryValue,
4455 /*count*/1);
4456 break;
4457 default:
4458 ALOGE("%s: Type not supported: 0x%x",
4459 __FUNCTION__,
4460 trigger.getTagType());
4461 return INVALID_OPERATION;
4462 }
4463
4464 if (res != OK) {
4465 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4466 ", trigger value %d", __FUNCTION__,
4467 trigger.getTagName(), trigger.entryValue);
4468 return res;
4469 }
4470 }
4471 mTriggerReplacedMap.clear();
4472
4473 /**
4474 * Remove all new entries.
4475 */
4476 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4477 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4478 status_t res = metadata.erase(trigger.metadataTag);
4479
4480 if (res != OK) {
4481 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4482 ", trigger value %d", __FUNCTION__,
4483 trigger.getTagName(), trigger.entryValue);
4484 return res;
4485 }
4486 }
4487 mTriggerRemovedMap.clear();
4488
4489 return OK;
4490}
4491
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004492status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004493 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004494 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004495 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004496 status_t res;
4497
Emilian Peevaebbe412018-01-15 13:53:24 +00004498 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004499
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004500 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004501 // exists
4502 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4503 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4504 if (afTrigger.count > 0 &&
4505 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4506 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004507 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004508 if (res != OK) return res;
4509 }
4510
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004511 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004512 // if none already exists
4513 camera_metadata_entry pcTrigger =
4514 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4515 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4516 if (pcTrigger.count > 0 &&
4517 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4518 pcId.count == 0) {
4519 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004520 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004521 if (res != OK) return res;
4522 }
4523
4524 return OK;
4525}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004526
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004527bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4528 const sp<CaptureRequest> &request) {
4529 ATRACE_CALL();
4530
4531 if (request->mRotateAndCropAuto) {
4532 Mutex::Autolock l(mTriggerMutex);
4533 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4534
4535 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4536 if (rotateAndCropEntry.count > 0) {
4537 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4538 return false;
4539 } else {
4540 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4541 return true;
4542 }
4543 } else {
4544 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4545 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4546 &rotateAndCrop_u8, 1);
4547 return true;
4548 }
4549 }
4550 return false;
4551}
4552
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004553bool Camera3Device::RequestThread::overrideTestPattern(
4554 const sp<CaptureRequest> &request) {
4555 ATRACE_CALL();
4556
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004557 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004558
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004559 Mutex::Autolock l(mTriggerMutex);
4560
4561 bool changed = false;
4562
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004563 // For a multi-camera, the physical cameras support the same set of
4564 // test pattern modes as the logical camera.
4565 for (auto& settings : request->mSettingsList) {
4566 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004567
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004568 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4569 int32_t testPatternData[4] = {
4570 settings.mOriginalTestPatternData[0],
4571 settings.mOriginalTestPatternData[1],
4572 settings.mOriginalTestPatternData[2],
4573 settings.mOriginalTestPatternData[3]
4574 };
4575 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4576 testPatternMode = mCameraMute;
4577 testPatternData[0] = 0;
4578 testPatternData[1] = 0;
4579 testPatternData[2] = 0;
4580 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004581 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004582
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004583 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4584 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4585 if (testPatternEntry.count > 0) {
4586 if (testPatternEntry.data.i32[0] != testPatternMode) {
4587 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004588 changed = true;
4589 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004590 } else if (supportTestPatternModeKey) {
4591 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4592 &testPatternMode, 1);
4593 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004594 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004595
4596 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4597 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4598 if (testPatternColor.count >= 4) {
4599 for (size_t i = 0; i < 4; i++) {
4600 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4601 testPatternColor.data.i32[i] = testPatternData[i];
4602 changed = true;
4603 }
4604 }
4605 } else if (supportTestPatternDataKey) {
4606 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4607 testPatternData, 4);
4608 changed = true;
4609 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004610 }
4611
4612 return changed;
4613}
4614
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004615status_t Camera3Device::RequestThread::setHalInterface(
4616 sp<HalInterface> newHalInterface) {
4617 if (newHalInterface.get() == nullptr) {
4618 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4619 return DEAD_OBJECT;
4620 }
4621
4622 mInterface = newHalInterface;
4623
4624 return OK;
4625}
4626
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004627/**
4628 * PreparerThread inner class methods
4629 */
4630
4631Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004632 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004633 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004634}
4635
4636Camera3Device::PreparerThread::~PreparerThread() {
4637 Thread::requestExitAndWait();
4638 if (mCurrentStream != nullptr) {
4639 mCurrentStream->cancelPrepare();
4640 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4641 mCurrentStream.clear();
4642 }
4643 clear();
4644}
4645
Ruben Brunkc78ac262015-08-13 17:58:46 -07004646status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004647 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004648 status_t res;
4649
4650 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004651 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004652
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004653 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004654 if (res == OK) {
4655 // No preparation needed, fire listener right off
4656 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004657 if (listener != NULL) {
4658 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004659 }
4660 return OK;
4661 } else if (res != NOT_ENOUGH_DATA) {
4662 return res;
4663 }
4664
4665 // Need to prepare, start up thread if necessary
4666 if (!mActive) {
4667 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4668 // isn't running
4669 Thread::requestExitAndWait();
4670 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4671 if (res != OK) {
4672 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004673 if (listener != NULL) {
4674 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004675 }
4676 return res;
4677 }
4678 mCancelNow = false;
4679 mActive = true;
4680 ALOGV("%s: Preparer stream started", __FUNCTION__);
4681 }
4682
4683 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004684 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004685 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4686
4687 return OK;
4688}
4689
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004690void Camera3Device::PreparerThread::pause() {
4691 ATRACE_CALL();
4692
4693 Mutex::Autolock l(mLock);
4694
4695 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4696 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4697 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4698 int currentMaxCount = mCurrentMaxCount;
4699 mPendingStreams.clear();
4700 mCancelNow = true;
4701 while (mActive) {
4702 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4703 if (res == TIMED_OUT) {
4704 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4705 return;
4706 } else if (res != OK) {
4707 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4708 return;
4709 }
4710 }
4711
4712 //Check whether the prepare thread was able to complete the current
4713 //stream. In case work is still pending emplace it along with the rest
4714 //of the streams in the pending list.
4715 if (currentStream != nullptr) {
4716 if (!mCurrentPrepareComplete) {
4717 pendingStreams.emplace(currentMaxCount, currentStream);
4718 }
4719 }
4720
4721 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4722 for (const auto& it : mPendingStreams) {
4723 it.second->cancelPrepare();
4724 }
4725}
4726
4727status_t Camera3Device::PreparerThread::resume() {
4728 ATRACE_CALL();
4729 status_t res;
4730
4731 Mutex::Autolock l(mLock);
4732 sp<NotificationListener> listener = mListener.promote();
4733
4734 if (mActive) {
4735 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4736 return NO_INIT;
4737 }
4738
4739 auto it = mPendingStreams.begin();
4740 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004741 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004742 if (res == OK) {
4743 if (listener != NULL) {
4744 listener->notifyPrepared(it->second->getId());
4745 }
4746 it = mPendingStreams.erase(it);
4747 } else if (res != NOT_ENOUGH_DATA) {
4748 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4749 res, strerror(-res));
4750 it = mPendingStreams.erase(it);
4751 } else {
4752 it++;
4753 }
4754 }
4755
4756 if (mPendingStreams.empty()) {
4757 return OK;
4758 }
4759
4760 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4761 if (res != OK) {
4762 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4763 __FUNCTION__, res, strerror(-res));
4764 return res;
4765 }
4766 mCancelNow = false;
4767 mActive = true;
4768 ALOGV("%s: Preparer stream started", __FUNCTION__);
4769
4770 return OK;
4771}
4772
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004773status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004774 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004775 Mutex::Autolock l(mLock);
4776
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004777 for (const auto& it : mPendingStreams) {
4778 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004779 }
4780 mPendingStreams.clear();
4781 mCancelNow = true;
4782
4783 return OK;
4784}
4785
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004786void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004787 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004788 Mutex::Autolock l(mLock);
4789 mListener = listener;
4790}
4791
4792bool Camera3Device::PreparerThread::threadLoop() {
4793 status_t res;
4794 {
4795 Mutex::Autolock l(mLock);
4796 if (mCurrentStream == nullptr) {
4797 // End thread if done with work
4798 if (mPendingStreams.empty()) {
4799 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4800 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4801 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4802 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004803 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004804 return false;
4805 }
4806
4807 // Get next stream to prepare
4808 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004809 mCurrentStream = it->second;
4810 mCurrentMaxCount = it->first;
4811 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004812 mPendingStreams.erase(it);
4813 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4814 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4815 } else if (mCancelNow) {
4816 mCurrentStream->cancelPrepare();
4817 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4818 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4819 mCurrentStream.clear();
4820 mCancelNow = false;
4821 return true;
4822 }
4823 }
4824
4825 res = mCurrentStream->prepareNextBuffer();
4826 if (res == NOT_ENOUGH_DATA) return true;
4827 if (res != OK) {
4828 // Something bad happened; try to recover by cancelling prepare and
4829 // signalling listener anyway
4830 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4831 mCurrentStream->getId(), res, strerror(-res));
4832 mCurrentStream->cancelPrepare();
4833 }
4834
4835 // This stream has finished, notify listener
4836 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004837 sp<NotificationListener> listener = mListener.promote();
4838 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004839 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4840 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004841 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004842 }
4843
4844 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4845 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004846 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004847
4848 return true;
4849}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004850
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004851status_t Camera3Device::RequestBufferStateMachine::initialize(
4852 sp<camera3::StatusTracker> statusTracker) {
4853 if (statusTracker == nullptr) {
4854 ALOGE("%s: statusTracker is null", __FUNCTION__);
4855 return BAD_VALUE;
4856 }
4857
4858 std::lock_guard<std::mutex> lock(mLock);
4859 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004860 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004861 return OK;
4862}
4863
4864bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4865 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004866 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004867 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004868 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004869 return true;
4870 }
4871 return false;
4872}
4873
4874void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4875 std::lock_guard<std::mutex> lock(mLock);
4876 if (!mRequestBufferOngoing) {
4877 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4878 return;
4879 }
4880 mRequestBufferOngoing = false;
4881 if (mStatus == RB_STATUS_PENDING_STOP) {
4882 checkSwitchToStopLocked();
4883 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004884 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004885}
4886
4887void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4888 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004889 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004890 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004891 return;
4892}
4893
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004894void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004895 std::lock_guard<std::mutex> lock(mLock);
4896 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004897 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4898 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004899 mInflightMapEmpty = false;
4900 if (mStatus == RB_STATUS_STOPPED) {
4901 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004902 }
4903 return;
4904}
4905
4906void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4907 std::lock_guard<std::mutex> lock(mLock);
4908 mRequestThreadPaused = true;
4909 if (mStatus == RB_STATUS_PENDING_STOP) {
4910 checkSwitchToStopLocked();
4911 }
4912 return;
4913}
4914
4915void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4916 std::lock_guard<std::mutex> lock(mLock);
4917 mInflightMapEmpty = true;
4918 if (mStatus == RB_STATUS_PENDING_STOP) {
4919 checkSwitchToStopLocked();
4920 }
4921 return;
4922}
4923
4924void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4925 std::lock_guard<std::mutex> lock(mLock);
4926 if (!checkSwitchToStopLocked()) {
4927 mStatus = RB_STATUS_PENDING_STOP;
4928 }
4929 return;
4930}
4931
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004932bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4933 std::lock_guard<std::mutex> lock(mLock);
4934 if (mRequestBufferOngoing) {
4935 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4936 __FUNCTION__);
4937 return false;
4938 }
4939 mSwitchedToOffline = true;
4940 mInflightMapEmpty = true;
4941 mRequestThreadPaused = true;
4942 mStatus = RB_STATUS_STOPPED;
4943 return true;
4944}
4945
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004946void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4947 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4948 if (statusTracker != nullptr) {
4949 if (active) {
4950 statusTracker->markComponentActive(mRequestBufferStatusId);
4951 } else {
4952 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4953 }
4954 }
4955}
4956
4957bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4958 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4959 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004960 return true;
4961 }
4962 return false;
4963}
4964
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004965bool Camera3Device::startRequestBuffer() {
4966 return mRequestBufferSM.startRequestBuffer();
4967}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004968
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004969void Camera3Device::endRequestBuffer() {
4970 mRequestBufferSM.endRequestBuffer();
4971}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004972
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004973nsecs_t Camera3Device::getWaitDuration() {
4974 return kBaseGetBufferWait + getExpectedInFlightDuration();
4975}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004976
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004977void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4978 mInterface->getInflightBufferKeys(out);
4979}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004980
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004981void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4982 mInterface->getInflightRequestBufferKeys(out);
4983}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004984
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004985std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
4986 std::vector<sp<Camera3StreamInterface>> ret;
4987 bool hasInputStream = mInputStream != nullptr;
4988 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
4989 if (hasInputStream) {
4990 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07004991 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004992 for (size_t i = 0; i < mOutputStreams.size(); i++) {
4993 ret.push_back(mOutputStreams[i]);
4994 }
4995 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
4996 ret.push_back(mDeletedStreams[i]);
4997 }
4998 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07004999}
5000
Emilian Peevcc0b7952020-01-07 13:54:47 -08005001void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5002 ATRACE_CALL();
5003
5004 if (offlineStreamIds == nullptr) {
5005 return;
5006 }
5007
5008 Mutex::Autolock il(mInterfaceLock);
5009
5010 auto streamIds = mOutputStreams.getStreamIds();
5011 bool hasInputStream = mInputStream != nullptr;
5012 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5013 offlineStreamIds->push_back(mInputStream->getId());
5014 }
5015
5016 for (const auto & streamId : streamIds) {
5017 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5018 // Streams that use the camera buffer manager are currently not supported in
5019 // offline mode
5020 if (stream->getOfflineProcessingSupport() &&
5021 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5022 offlineStreamIds->push_back(streamId);
5023 }
5024 }
5025}
5026
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005027status_t Camera3Device::setRotateAndCropAutoBehavior(
5028 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5029 ATRACE_CALL();
5030 Mutex::Autolock il(mInterfaceLock);
5031 Mutex::Autolock l(mLock);
5032 if (mRequestThread == nullptr) {
5033 return INVALID_OPERATION;
5034 }
5035 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5036}
5037
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005038bool Camera3Device::supportsCameraMute() {
5039 Mutex::Autolock il(mInterfaceLock);
5040 Mutex::Autolock l(mLock);
5041
5042 return mSupportCameraMute;
5043}
5044
5045status_t Camera3Device::setCameraMute(bool enabled) {
5046 ATRACE_CALL();
5047 Mutex::Autolock il(mInterfaceLock);
5048 Mutex::Autolock l(mLock);
5049
5050 if (mRequestThread == nullptr || !mSupportCameraMute) {
5051 return INVALID_OPERATION;
5052 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005053 int32_t muteMode =
5054 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5055 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5056 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5057 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005058}
5059
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005060status_t Camera3Device::injectCamera(const String8& injectedCamId,
5061 sp<CameraProviderManager> manager) {
5062 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5063 ATRACE_CALL();
5064 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005065 // When the camera device is active, injectCamera() and stopInjection() will call
5066 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5067 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5068 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5069 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5070 // waitUntilStateThenRelock().
5071 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005072
5073 status_t res = NO_ERROR;
5074 if (mInjectionMethods->isInjecting()) {
5075 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5076 return OK;
5077 } else {
5078 res = mInjectionMethods->stopInjection();
5079 if (res != OK) {
5080 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5081 __FUNCTION__, res);
5082 return res;
5083 }
5084 }
5085 }
5086
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005087 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005088 if (res != OK) {
5089 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5090 __FUNCTION__, res);
5091 return res;
5092 }
5093
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005094 // When the second display of android is cast to the remote device, and the opened camera is
5095 // also cast to the second display, in this case, because the camera has configured the streams
5096 // at this time, we can directly call injectCamera() to replace the internal camera with
5097 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005098 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5099 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5100
5101 camera3::camera_stream_configuration injectionConfig;
5102 std::vector<uint32_t> injectionBufferSizes;
5103 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5104 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5105 || injectionBufferSizes.size() <= 0) {
5106 ALOGE("Failed to inject camera due to abandoned configuration! "
5107 "mOperatingMode: %d injectionConfig.num_streams: %d "
5108 "injectionBufferSizes.size(): %zu", mOperatingMode,
5109 injectionConfig.num_streams, injectionBufferSizes.size());
5110 return DEAD_OBJECT;
5111 }
5112
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005113 res = mInjectionMethods->injectCamera(
5114 injectionConfig, injectionBufferSizes);
5115 if (res != OK) {
5116 ALOGE("Can't finish inject camera process!");
5117 return res;
5118 }
5119 }
5120
5121 return OK;
5122}
5123
5124status_t Camera3Device::stopInjection() {
5125 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5126 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005127 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005128 return mInjectionMethods->stopInjection();
5129}
5130
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005131}; // namespace android