blob: 1309369f04f279046deb1c409a75d59a5eb263d8 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080068#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080069#include <tuple>
70
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080071using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080072using namespace android::hardware::camera;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080073
74namespace android {
75
Austin Borger3560b7e2022-10-27 12:20:29 -070076Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool overrideToPortrait,
77 bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080078 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070079 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080080 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070081 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070082 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070083 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070084 mUsePartialResult(false),
85 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080086 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080087 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070088 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070089 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070090 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070092 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000094 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010095 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070096 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070097 mNeedFixupMonochromeTags(false),
Austin Borger3560b7e2022-10-27 12:20:29 -070098 mOverrideForPerfClass(overrideForPerfClass),
99 mOverrideToPortrait(overrideToPortrait)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
105Camera3Device::~Camera3Device()
106{
107 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700109 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800110}
111
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800112const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800113 return mId;
114}
115
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800116status_t Camera3Device::initializeCommonLocked() {
117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700118 /** Start up status tracker thread */
119 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800120 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700121 if (res != OK) {
122 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
123 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700125 mStatusTracker.clear();
126 return res;
127 }
128
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700129 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700130 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700132 if (mUseHalBufManager) {
133 res = mRequestBufferSM.initialize(mStatusTracker);
134 if (res != OK) {
135 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
136 strerror(-res), res);
137 mInterface->close();
138 mStatusTracker.clear();
139 return res;
140 }
141 }
142
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800143 /** Create buffer manager */
144 mBufferManager = new Camera3BufferManager();
145
146 Vector<int32_t> sessionParamKeys;
147 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
148 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
149 if (sessionKeysEntry.count > 0) {
150 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
151 }
152
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700153 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
154 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
155 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
156 if (availableTestPatternModes.data.i32[i] ==
157 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
158 mSupportCameraMute = true;
159 mSupportTestPatternSolidColor = true;
160 break;
161 } else if (availableTestPatternModes.data.i32[i] ==
162 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
163 mSupportCameraMute = true;
164 mSupportTestPatternSolidColor = false;
165 }
166 }
167
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700168 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800169 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700170 this, mStatusTracker, mInterface, sessionParamKeys,
Austin Borger3560b7e2022-10-27 12:20:29 -0700171 mUseHalBufManager, mSupportCameraMute, mOverrideToPortrait);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800172 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800173 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700174 SET_ERR_L("Unable to start request queue thread: %s (%d)",
175 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800176 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800177 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800178 return res;
179 }
180
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700181 mPreparerThread = new PreparerThread();
182
Ruben Brunk183f0562015-08-12 12:55:02 -0700183 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800184 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400185 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700186 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700187 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800188 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800189
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800190 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800191 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 camera_metadata_entry timestampSource =
193 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
194 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
195 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800196 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800197 }
198
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700199 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100200 camera_metadata_entry partialResultsCount =
201 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
202 if (partialResultsCount.count > 0) {
203 mNumPartialResults = partialResultsCount.data.i32[0];
204 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700205 }
206
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800207 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
208 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700209 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700210 if (res != OK) {
211 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
212 return res;
213 }
214 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800215
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800216 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800218
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700219 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
220 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
221 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
222 }
223
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800224 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
225 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
226 }
227
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800228 // Hidl/AidlCamera3DeviceInjectionMethods
229 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800230
Ravneet74cd3732022-03-30 05:33:03 +0000231 /** Start watchdog thread */
232 mCameraServiceWatchdog = new CameraServiceWatchdog();
233 res = mCameraServiceWatchdog->run("CameraServiceWatchdog");
234 if (res != OK) {
235 SET_ERR_L("Unable to start camera service watchdog thread: %s (%d)",
236 strerror(-res), res);
237 return res;
238 }
239
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800240 return OK;
241}
242
243status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700244 return disconnectImpl();
245}
246
247status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800248 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700249 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800250
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700251 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700252 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700253 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800254 Mutex::Autolock il(mInterfaceLock);
255 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
256 {
257 Mutex::Autolock l(mLock);
258 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700259
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800260 if (mStatus == STATUS_ACTIVE ||
261 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
262 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800264 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800266 } else {
267 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
268 if (res != OK) {
269 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
270 maxExpectedDuration);
271 // Continue to close device even in case of error
272 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700273 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700274 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800275
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800276 if (mStatus == STATUS_ERROR) {
277 CLOGE("Shutting down in an error state");
278 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800280 if (mStatusTracker != NULL) {
281 mStatusTracker->requestExit();
282 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700283
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800284 if (mRequestThread != NULL) {
285 mRequestThread->requestExit();
286 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800288 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
289 for (size_t i = 0; i < mOutputStreams.size(); i++) {
290 streams.push_back(mOutputStreams[i]);
291 }
292 if (mInputStream != nullptr) {
293 streams.push_back(mInputStream);
294 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700295 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800297 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
298 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
300 // HAL may be in a bad state, so waiting for request thread
301 // (which may be stuck in the HAL processCaptureRequest call)
302 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800303 // give up mInterfaceLock here and then lock it again. Could this lead
304 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 mRequestThread->join();
306 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800308 Mutex::Autolock il(mInterfaceLock);
309 if (mStatusTracker != NULL) {
310 mStatusTracker->join();
311 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800313 if (mInjectionMethods->isInjecting()) {
314 mInjectionMethods->stopInjection();
315 }
316
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800317 HalInterface* interface;
318 {
319 Mutex::Autolock l(mLock);
320 mRequestThread.clear();
321 Mutex::Autolock stLock(mTrackerLock);
322 mStatusTracker.clear();
323 interface = mInterface.get();
324 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700325
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800326 // Call close without internal mutex held, as the HAL close may need to
327 // wait on assorted callbacks,etc, to complete before it can return.
Ravneet98ffa752022-03-02 07:22:46 +0000328 mCameraServiceWatchdog->WATCH(interface->close());
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800330 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800331
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800332 {
333 Mutex::Autolock l(mLock);
334 mInterface->clear();
335 mOutputStreams.clear();
336 mInputStream.clear();
337 mDeletedStreams.clear();
338 mBufferManager.clear();
339 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
340 }
341
342 for (auto& weakStream : streams) {
343 sp<Camera3StreamInterface> stream = weakStream.promote();
344 if (stream != nullptr) {
345 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
346 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
347 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700348 }
349 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700350 ALOGI("%s: X", __FUNCTION__);
Ravneet98ffa752022-03-02 07:22:46 +0000351
352 if (mCameraServiceWatchdog != NULL) {
353 mCameraServiceWatchdog->requestExit();
354 mCameraServiceWatchdog.clear();
355 }
356
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700357 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800358}
359
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700360// For dumping/debugging only -
361// try to acquire a lock a few times, eventually give up to proceed with
362// debug/dump operations
363bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
364 bool gotLock = false;
365 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
366 if (lock.tryLock() == NO_ERROR) {
367 gotLock = true;
368 break;
369 } else {
370 usleep(kDumpSleepDuration);
371 }
372 }
373 return gotLock;
374}
375
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800376nsecs_t Camera3Device::getMonoToBoottimeOffset() {
377 // try three times to get the clock offset, choose the one
378 // with the minimum gap in measurements.
379 const int tries = 3;
380 nsecs_t bestGap, measured;
381 for (int i = 0; i < tries; ++i) {
382 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
383 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
384 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
385 const nsecs_t gap = tmono2 - tmono;
386 if (i == 0 || gap < bestGap) {
387 bestGap = gap;
388 measured = tbase - ((tmono + tmono2) >> 1);
389 }
390 }
391 return measured;
392}
393
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800394ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
395 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700396 // Get max jpeg size (area-wise) for default sensor pixel mode
397 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800398 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700399 /*isUltraHighResolutionSensor*/false);
400 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
401 // not ultra high res sensor
402 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800403 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700404 /*isUltraHighResolution*/true);
405 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
407 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700408 return BAD_VALUE;
409 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700410 bool useMaxSensorPixelModeThreshold = false;
411 if (uhrMaxJpegResolution.width != 0 &&
412 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
413 // Use the ultra high res max jpeg size and max jpeg buffer size
414 useMaxSensorPixelModeThreshold = true;
415 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700416
Zhijun Hef7da0962014-04-24 13:27:56 -0700417 // Get max jpeg buffer size
418 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800419 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800421 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
422 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700423 return BAD_VALUE;
424 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700425 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700426
427 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
428 if (useMaxSensorPixelModeThreshold) {
429 maxJpegBufferSize =
430 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
431 maxDefaultJpegResolution, maxJpegBufferSize);
432 chosenMaxJpegResolution = uhrMaxJpegResolution;
433 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800434 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700435
436 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700437 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700438 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800439 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
440 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700441 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800442 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
443 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700444 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700445 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700446 return jpegBufferSize;
447}
448
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800449ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700450 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800451 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700452 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800453 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
454 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700455 return BAD_VALUE;
456 }
457 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
458 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
459 return maxBytesForPointCloud;
460}
461
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800462ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
463 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800464 const int PER_CONFIGURATION_SIZE = 3;
465 const int WIDTH_OFFSET = 0;
466 const int HEIGHT_OFFSET = 1;
467 const int SIZE_OFFSET = 2;
468 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800469 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800470 camera3::SessionConfigurationUtils::getAppropriateModeTag(
471 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
472 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800473 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800474 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800475 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
476 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800477 return BAD_VALUE;
478 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700479
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800480 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
481 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
482 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
483 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
484 }
485 }
486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
488 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800489 return BAD_VALUE;
490}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700491
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800492status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
493 ATRACE_CALL();
494 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700495
496 // Try to lock, but continue in case of failure (to avoid blocking in
497 // deadlocks)
498 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
499 bool gotLock = tryLockSpinRightRound(mLock);
500
501 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
503 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700504 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800505 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
506 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700507
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800508 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700509
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800510 String16 templatesOption("-t");
511 int n = args.size();
512 for (int i = 0; i < n; i++) {
513 if (args[i] == templatesOption) {
514 dumpTemplates = true;
515 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000516 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700517 if (i + 1 < n) {
518 String8 monitorTags = String8(args[i + 1]);
519 if (monitorTags == "off") {
520 mTagMonitor.disableMonitoring();
521 } else {
522 mTagMonitor.parseTagsToMonitor(monitorTags);
523 }
524 } else {
525 mTagMonitor.disableMonitoring();
526 }
527 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800528 }
529
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800530 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800531
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800532 const char *status =
533 mStatus == STATUS_ERROR ? "ERROR" :
534 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700535 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
536 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800537 mStatus == STATUS_ACTIVE ? "ACTIVE" :
538 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700539
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800540 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700541 if (mStatus == STATUS_ERROR) {
542 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
543 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800544 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800545 const char *mode =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000546 mOperatingMode == CAMERA_STREAM_CONFIGURATION_NORMAL_MODE ? "NORMAL" :
547 mOperatingMode == CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE ?
548 "CONSTRAINED_HIGH_SPEED" : "CUSTOM";
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800549 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800550
551 if (mInputStream != NULL) {
552 write(fd, lines.string(), lines.size());
553 mInputStream->dump(fd, args);
554 } else {
555 lines.appendFormat(" No input stream.\n");
556 write(fd, lines.string(), lines.size());
557 }
558 for (size_t i = 0; i < mOutputStreams.size(); i++) {
559 mOutputStreams[i]->dump(fd,args);
560 }
561
Zhijun He431503c2016-03-07 17:30:16 -0800562 if (mBufferManager != NULL) {
563 lines = String8(" Camera3 Buffer Manager:\n");
564 write(fd, lines.string(), lines.size());
565 mBufferManager->dump(fd, args);
566 }
Zhijun He125684a2015-12-26 15:07:30 -0800567
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700568 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700569 if (mInFlightLock.try_lock()) {
570 if (mInFlightMap.size() == 0) {
571 lines.append(" None\n");
572 } else {
573 for (size_t i = 0; i < mInFlightMap.size(); i++) {
574 InFlightRequest r = mInFlightMap.valueAt(i);
575 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
576 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
577 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
578 r.numBuffersLeft);
579 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700580 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700581 mInFlightLock.unlock();
582 } else {
583 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700584 }
585 write(fd, lines.string(), lines.size());
586
Shuzhen Wang686f6442017-06-20 16:16:04 -0700587 if (mRequestThread != NULL) {
588 mRequestThread->dumpCaptureRequestLatency(fd,
589 " ProcessCaptureRequest latency histogram:");
590 }
591
Igor Murashkin1e479c02013-09-06 16:55:14 -0700592 {
593 lines = String8(" Last request sent:\n");
594 write(fd, lines.string(), lines.size());
595
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700596 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700597 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
598 }
599
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800600 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700601 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 "TEMPLATE_PREVIEW",
603 "TEMPLATE_STILL_CAPTURE",
604 "TEMPLATE_VIDEO_RECORD",
605 "TEMPLATE_VIDEO_SNAPSHOT",
606 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800607 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800608 };
609
Emilian Peevf4816702020-04-03 15:44:51 -0700610 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800611 camera_metadata_t *templateRequest = nullptr;
612 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700613 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800614 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800615 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800616 lines.append(" Not supported\n");
617 write(fd, lines.string(), lines.size());
618 } else {
619 write(fd, lines.string(), lines.size());
620 dump_indented_camera_metadata(templateRequest,
621 fd, /*verbosity*/2, /*indentation*/8);
622 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800623 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800624 }
625 }
626
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700627 mTagMonitor.dumpMonitoredMetadata(fd);
628
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800629 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800630 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800631 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800633 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800634
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700635 if (gotLock) mLock.unlock();
636 if (gotInterfaceLock) mInterfaceLock.unlock();
637
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800638 return OK;
639}
640
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700641status_t Camera3Device::startWatchingTags(const String8 &tags) {
642 mTagMonitor.parseTagsToMonitor(tags);
643 return OK;
644}
645
646status_t Camera3Device::stopWatchingTags() {
647 mTagMonitor.disableMonitoring();
648 return OK;
649}
650
651status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
652 mTagMonitor.getLatestMonitoredTagEvents(out);
653 return OK;
654}
655
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800656const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800657 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800658 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
659 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700660 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800661 mStatus == STATUS_ERROR ?
662 "when in error state" : "before init");
663 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700664 if (physicalId.isEmpty()) {
665 return mDeviceInfo;
666 } else {
667 std::string id(physicalId.c_str());
668 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
669 return mPhysicalDeviceInfoMap.at(id);
670 } else {
671 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
672 return mDeviceInfo;
673 }
674 }
675}
676
677const CameraMetadata& Camera3Device::info() const {
678 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800679 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800680}
681
Jianing Wei90e59c92014-03-12 18:29:36 -0700682status_t Camera3Device::checkStatusOkToCaptureLocked() {
683 switch (mStatus) {
684 case STATUS_ERROR:
685 CLOGE("Device has encountered a serious error");
686 return INVALID_OPERATION;
687 case STATUS_UNINITIALIZED:
688 CLOGE("Device not initialized");
689 return INVALID_OPERATION;
690 case STATUS_UNCONFIGURED:
691 case STATUS_CONFIGURED:
692 case STATUS_ACTIVE:
693 // OK
694 break;
695 default:
696 SET_ERR_L("Unexpected status: %d", mStatus);
697 return INVALID_OPERATION;
698 }
699 return OK;
700}
701
702status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000703 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700704 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700705 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700706 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700707 if (requestList == NULL) {
708 CLOGE("requestList cannot be NULL.");
709 return BAD_VALUE;
710 }
711
Jianing Weicb0652e2014-03-12 18:29:36 -0700712 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000713 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700714 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
715 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
716 ++metadataIt, ++surfaceMapIt) {
717 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700718 if (newRequest == 0) {
719 CLOGE("Can't create capture request");
720 return BAD_VALUE;
721 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700722
Shuzhen Wang9d066012016-09-30 11:30:20 -0700723 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700724 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700725
Jianing Weicb0652e2014-03-12 18:29:36 -0700726 // Setup burst Id and request Id
727 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800728 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
729 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700730 CLOGE("RequestID does not exist in metadata");
731 return BAD_VALUE;
732 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800733 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700734
Jianing Wei90e59c92014-03-12 18:29:36 -0700735 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700736
737 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700738 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700739 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
740 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
741 return BAD_VALUE;
742 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700743
744 // Setup batch size if this is a high speed video recording request.
745 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
746 auto firstRequest = requestList->begin();
747 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
748 if (outputStream->isVideoStream()) {
749 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800750 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700751 break;
752 }
753 }
754 }
755
Jianing Wei90e59c92014-03-12 18:29:36 -0700756 return OK;
757}
758
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800759status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800760 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761
Emilian Peevaebbe412018-01-15 13:53:24 +0000762 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700763 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000764 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700765
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800766 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700767}
768
Emilian Peevaebbe412018-01-15 13:53:24 +0000769void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700770 std::list<const SurfaceMap>& surfaceMaps,
771 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000772 PhysicalCameraSettingsList requestList;
773 requestList.push_back({std::string(getId().string()), request});
774 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700775
776 SurfaceMap surfaceMap;
777 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
778 // With no surface list passed in, stream and surface will have 1-to-1
779 // mapping. So the surface index is 0 for each stream in the surfaceMap.
780 for (size_t i = 0; i < streams.count; i++) {
781 surfaceMap[streams.data.i32[i]].push_back(0);
782 }
783 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800784}
785
Jianing Wei90e59c92014-03-12 18:29:36 -0700786status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000787 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700788 const std::list<const SurfaceMap> &surfaceMaps,
789 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700790 /*out*/
791 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700792 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700793 nsecs_t requestTimeNs = systemTime();
794
Jianing Wei90e59c92014-03-12 18:29:36 -0700795 Mutex::Autolock il(mInterfaceLock);
796 Mutex::Autolock l(mLock);
797
798 status_t res = checkStatusOkToCaptureLocked();
799 if (res != OK) {
800 // error logged by previous call
801 return res;
802 }
803
804 RequestList requestList;
805
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700807 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700808 if (res != OK) {
809 // error logged by previous call
810 return res;
811 }
812
813 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700814 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700815 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700816 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700817 }
818
819 if (res == OK) {
820 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
821 if (res != OK) {
822 SET_ERR_L("Can't transition to active in %f seconds!",
823 kActiveTimeout/1e9);
824 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800825 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700826 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 } else {
828 CLOGE("Cannot queue request. Impossible.");
829 return BAD_VALUE;
830 }
831
832 return res;
833}
834
Emilian Peevaebbe412018-01-15 13:53:24 +0000835status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700837 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700838 ATRACE_CALL();
839
Emilian Peevaebbe412018-01-15 13:53:24 +0000840 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700841}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800842
Jianing Weicb0652e2014-03-12 18:29:36 -0700843status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
844 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000849 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700850
Emilian Peevaebbe412018-01-15 13:53:24 +0000851 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700852 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853}
854
Emilian Peevaebbe412018-01-15 13:53:24 +0000855status_t Camera3Device::setStreamingRequestList(
856 const List<const PhysicalCameraSettingsList> &requestsList,
857 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700858 ATRACE_CALL();
859
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700861}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800862
863sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000864 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800865 status_t res;
866
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700867 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800868 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
869 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700871 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700872 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800873 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700874 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800875 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700876 } else if (mStatus == STATUS_UNCONFIGURED) {
877 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700878 CLOGE("No streams configured");
879 return NULL;
880 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800881 }
882
Shuzhen Wang0129d522016-10-30 22:43:41 -0700883 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800884 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800885}
886
Jianing Weicb0652e2014-03-12 18:29:36 -0700887status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800888 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700889 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800890 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800891
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800892 switch (mStatus) {
893 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700894 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800895 return INVALID_OPERATION;
896 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700897 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800898 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700899 case STATUS_UNCONFIGURED:
900 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800901 case STATUS_ACTIVE:
902 // OK
903 break;
904 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700905 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800906 return INVALID_OPERATION;
907 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800908 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700909
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700910 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800911}
912
913status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
914 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700915 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800916
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700917 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800918}
919
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700920status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800921 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700922 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700923 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700924 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700925 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800926 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
927 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700928
929 status_t res;
930 bool wasActive = false;
931
932 switch (mStatus) {
933 case STATUS_ERROR:
934 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
935 return INVALID_OPERATION;
936 case STATUS_UNINITIALIZED:
937 ALOGE("%s: Device not initialized", __FUNCTION__);
938 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700939 case STATUS_UNCONFIGURED:
940 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700941 // OK
942 break;
943 case STATUS_ACTIVE:
944 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700945 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700946 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700947 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700948 return res;
949 }
950 wasActive = true;
951 break;
952 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700953 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700954 return INVALID_OPERATION;
955 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700956 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700957
958 if (mInputStream != 0) {
959 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
960 return INVALID_OPERATION;
961 }
962
963 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
964 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700965 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700966
967 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800968 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700969
970 *id = mNextStreamId++;
971
972 // Continue captures if active at start
973 if (wasActive) {
974 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100975 // Reuse current operating mode and session parameters for new stream config
976 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700977 if (res != OK) {
978 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
979 __FUNCTION__, mNextStreamId, strerror(-res), res);
980 return res;
981 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700982 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700983 }
984
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800985 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700986 return OK;
987}
988
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700989status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700990 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700991 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800992 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800993 const std::unordered_set<int32_t> &sensorPixelModesUsed,
994 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800995 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
Emilian Peevc81a7592022-02-14 17:38:18 -0800996 int timestampBase, int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700997 ATRACE_CALL();
998
999 if (consumer == nullptr) {
1000 ALOGE("%s: consumer must not be null", __FUNCTION__);
1001 return BAD_VALUE;
1002 }
1003
1004 std::vector<sp<Surface>> consumers;
1005 consumers.push_back(consumer);
1006
1007 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001008 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001009 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001010 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001011}
1012
1013static bool isRawFormat(int format) {
1014 switch (format) {
1015 case HAL_PIXEL_FORMAT_RAW16:
1016 case HAL_PIXEL_FORMAT_RAW12:
1017 case HAL_PIXEL_FORMAT_RAW10:
1018 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1019 return true;
1020 default:
1021 return false;
1022 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001023}
1024
1025status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1026 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001027 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001028 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001029 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001030 uint64_t consumerUsage, int64_t dynamicRangeProfile, int64_t streamUseCase,
1031 int timestampBase, int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001032 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001033
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001034 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001035 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001036 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001037 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001038 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001039 " dynamicRangeProfile 0x%" PRIx64 ", streamUseCase %" PRId64 ", timestampBase %d,"
1040 " mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001041 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001042 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001043 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001044
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001045 status_t res;
1046 bool wasActive = false;
1047
1048 switch (mStatus) {
1049 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001050 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051 return INVALID_OPERATION;
1052 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001053 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001054 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001055 case STATUS_UNCONFIGURED:
1056 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001057 // OK
1058 break;
1059 case STATUS_ACTIVE:
1060 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001061 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001062 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001063 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001064 return res;
1065 }
1066 wasActive = true;
1067 break;
1068 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001069 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001070 return INVALID_OPERATION;
1071 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001072 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001073
1074 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001075
Shuzhen Wang0129d522016-10-30 22:43:41 -07001076 if (consumers.size() == 0 && !hasDeferredConsumer) {
1077 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1078 return BAD_VALUE;
1079 }
Zhijun He5d677d12016-05-29 16:52:39 -07001080
Shuzhen Wang0129d522016-10-30 22:43:41 -07001081 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001082 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1083 return BAD_VALUE;
1084 }
1085
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001086 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1087 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1088 // be found in only one sensor pixel mode.
1089 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1090 return BAD_VALUE;
1091 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001092 IPCTransport transport = getTransportType();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001093 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001094 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001095 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001096 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001097 if (blobBufferSize <= 0) {
1098 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1099 return BAD_VALUE;
1100 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001101 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1102 blobBufferSize = width * height;
1103 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001104 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001105 if (blobBufferSize <= 0) {
1106 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1107 return BAD_VALUE;
1108 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001109 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001110 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001111 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001112 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001113 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001114 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001115 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001116 bool maxResolution =
1117 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1118 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001119 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1120 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001121 if (rawOpaqueBufferSize <= 0) {
1122 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1123 return BAD_VALUE;
1124 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001125 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001126 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001127 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001128 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001129 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001130 } else if (isShared) {
1131 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1132 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001133 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001134 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001135 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001136 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001137 newStream = new Camera3OutputStream(mNextStreamId,
1138 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001139 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001140 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001141 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001142 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001143 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001144 width, height, format, dataSpace, rotation,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001145 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, transport, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001146 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001147 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001148 }
Emilian Peev40ead602017-09-26 15:46:36 +01001149
1150 size_t consumerCount = consumers.size();
1151 for (size_t i = 0; i < consumerCount; i++) {
1152 int id = newStream->getSurfaceId(consumers[i]);
1153 if (id < 0) {
1154 SET_ERR_L("Invalid surface id");
1155 return BAD_VALUE;
1156 }
1157 if (surfaceIds != nullptr) {
1158 surfaceIds->push_back(id);
1159 }
1160 }
1161
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001162 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001163
Emilian Peev08dd2452017-04-06 16:55:14 +01001164 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001165
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001166 newStream->setImageDumpMask(mImageDumpMask);
1167
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001168 res = mOutputStreams.add(mNextStreamId, newStream);
1169 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001170 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001171 return res;
1172 }
1173
Shuzhen Wang316781a2020-08-18 18:11:01 -07001174 mSessionStatsBuilder.addStream(mNextStreamId);
1175
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001177 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178
1179 // Continue captures if active at start
1180 if (wasActive) {
1181 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001182 // Reuse current operating mode and session parameters for new stream config
1183 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001184 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001185 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1186 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 return res;
1188 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001189 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001191 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001193}
1194
Emilian Peev710c1422017-08-30 11:19:38 +01001195status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001196 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001197 if (nullptr == streamInfo) {
1198 return BAD_VALUE;
1199 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001200 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001202
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 switch (mStatus) {
1204 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001205 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001206 return INVALID_OPERATION;
1207 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001208 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001210 case STATUS_UNCONFIGURED:
1211 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 case STATUS_ACTIVE:
1213 // OK
1214 break;
1215 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001216 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 return INVALID_OPERATION;
1218 }
1219
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001220 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1221 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001222 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001223 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 }
1225
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001226 streamInfo->width = stream->getWidth();
1227 streamInfo->height = stream->getHeight();
1228 streamInfo->format = stream->getFormat();
1229 streamInfo->dataSpace = stream->getDataSpace();
1230 streamInfo->formatOverridden = stream->isFormatOverridden();
1231 streamInfo->originalFormat = stream->getOriginalFormat();
1232 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1233 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001234 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001236}
1237
1238status_t Camera3Device::setStreamTransform(int id,
1239 int transform) {
1240 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001241 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001243
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 switch (mStatus) {
1245 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001246 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001247 return INVALID_OPERATION;
1248 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001249 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 case STATUS_UNCONFIGURED:
1252 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001253 case STATUS_ACTIVE:
1254 // OK
1255 break;
1256 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
1259 }
1260
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001261 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1262 if (stream == nullptr) {
1263 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001264 return BAD_VALUE;
1265 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001266 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001267}
1268
1269status_t Camera3Device::deleteStream(int id) {
1270 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001272 Mutex::Autolock l(mLock);
1273 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001274
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001275 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001276
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001277 // CameraDevice semantics require device to already be idle before
1278 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001280 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001281 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001282 }
1283
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001284 if (mStatus == STATUS_ERROR) {
1285 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1286 __FUNCTION__, mId.string());
1287 return -EBUSY;
1288 }
1289
Igor Murashkin2fba5842013-04-22 14:03:54 -07001290 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001291 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001292 if (mInputStream != NULL && id == mInputStream->getId()) {
1293 deletedStream = mInputStream;
1294 mInputStream.clear();
1295 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001296 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001297 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001298 return BAD_VALUE;
1299 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001300 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001301 }
1302
1303 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001304 if (stream != nullptr) {
1305 deletedStream = stream;
1306 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001307 }
1308
1309 // Free up the stream endpoint so that it can be used by some other stream
1310 res = deletedStream->disconnect();
1311 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001312 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001313 // fall through since we want to still list the stream as deleted.
1314 }
1315 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001316 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001317
1318 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001319}
1320
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001321status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001322 ATRACE_CALL();
1323 ALOGV("%s: E", __FUNCTION__);
1324
1325 Mutex::Autolock il(mInterfaceLock);
1326 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001327
Emilian Peev811d2952018-05-25 11:08:40 +01001328 // In case the client doesn't include any session parameter, try a
1329 // speculative configuration using the values from the last cached
1330 // default request.
1331 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001332 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001333 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1334 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1335 mLastTemplateId);
1336 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1337 operatingMode);
1338 }
1339
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001340 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1341}
1342
1343status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1344 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001345 //Filter out any incoming session parameters
1346 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001347 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1348 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001349 CameraMetadata filteredParams(availableSessionKeys.count);
1350 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1351 filteredParams.getAndLock());
1352 set_camera_metadata_vendor_id(meta, mVendorTagId);
1353 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001354 if (availableSessionKeys.count > 0) {
1355 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1356 camera_metadata_ro_entry entry = params.find(
1357 availableSessionKeys.data.i32[i]);
1358 if (entry.count > 0) {
1359 filteredParams.update(entry);
1360 }
1361 }
1362 }
1363
1364 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001365}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001366
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001367status_t Camera3Device::getInputBufferProducer(
1368 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001369 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001370 Mutex::Autolock il(mInterfaceLock);
1371 Mutex::Autolock l(mLock);
1372
1373 if (producer == NULL) {
1374 return BAD_VALUE;
1375 } else if (mInputStream == NULL) {
1376 return INVALID_OPERATION;
1377 }
1378
1379 return mInputStream->getInputBufferProducer(producer);
1380}
1381
Emilian Peevf4816702020-04-03 15:44:51 -07001382status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001383 CameraMetadata *request) {
1384 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001385 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001386
Emilian Peevf4816702020-04-03 15:44:51 -07001387 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001388 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001389 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001390 return BAD_VALUE;
1391 }
1392
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001395 {
1396 Mutex::Autolock l(mLock);
1397 switch (mStatus) {
1398 case STATUS_ERROR:
1399 CLOGE("Device has encountered a serious error");
1400 return INVALID_OPERATION;
1401 case STATUS_UNINITIALIZED:
1402 CLOGE("Device is not initialized!");
1403 return INVALID_OPERATION;
1404 case STATUS_UNCONFIGURED:
1405 case STATUS_CONFIGURED:
1406 case STATUS_ACTIVE:
1407 // OK
1408 break;
1409 default:
1410 SET_ERR_L("Unexpected status: %d", mStatus);
1411 return INVALID_OPERATION;
1412 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001413
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001414 if (!mRequestTemplateCache[templateId].isEmpty()) {
1415 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001416 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001417 return OK;
1418 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001419 }
1420
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001421 camera_metadata_t *rawRequest;
1422 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001423 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001424
1425 {
1426 Mutex::Autolock l(mLock);
1427 if (res == BAD_VALUE) {
1428 ALOGI("%s: template %d is not supported on this camera device",
1429 __FUNCTION__, templateId);
1430 return res;
1431 } else if (res != OK) {
1432 CLOGE("Unable to construct request template %d: %s (%d)",
1433 templateId, strerror(-res), res);
1434 return res;
1435 }
1436
1437 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1438 mRequestTemplateCache[templateId].acquire(rawRequest);
1439
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001440 // Override the template request with zoomRatioMapper
1441 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1442 &mRequestTemplateCache[templateId]);
1443 if (res != OK) {
1444 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1445 templateId, strerror(-res), res);
1446 return res;
1447 }
1448
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001449 // Fill in JPEG_QUALITY if not available
1450 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1451 static const uint8_t kDefaultJpegQuality = 95;
1452 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1453 &kDefaultJpegQuality, 1);
1454 }
1455
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001456 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001457 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001458 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001459 return OK;
1460}
1461
1462status_t Camera3Device::waitUntilDrained() {
1463 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001464 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001465 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001467
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001468 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001469}
1470
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001471status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 switch (mStatus) {
1473 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001474 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 ALOGV("%s: Already idle", __FUNCTION__);
1476 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001477 case STATUS_CONFIGURED:
1478 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 case STATUS_ERROR:
1480 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 break;
1483 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001484 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 return INVALID_OPERATION;
1486 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001487 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1488 maxExpectedDuration);
1489 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001490 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001491 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001492 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1493 res);
1494 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001495 return res;
1496}
1497
Ruben Brunk183f0562015-08-12 12:55:02 -07001498void Camera3Device::internalUpdateStatusLocked(Status status) {
1499 mStatus = status;
1500 mRecentStatusUpdates.add(mStatus);
1501 mStatusChanged.broadcast();
1502}
1503
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001505status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001506 if (mRequestThread.get() != nullptr) {
1507 mRequestThread->setPaused(true);
1508 } else {
1509 return NO_INIT;
1510 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001512 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1513 maxExpectedDuration);
1514 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 if (res != OK) {
1516 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001517 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 }
1519
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001520 return res;
1521}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523// Resume after internalPauseAndWaitLocked
1524status_t Camera3Device::internalResumeLocked() {
1525 status_t res;
1526
1527 mRequestThread->setPaused(false);
1528
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001529 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1530 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1532 if (res != OK) {
1533 SET_ERR_L("Can't transition to active in %f seconds!",
1534 kActiveTimeout/1e9);
1535 }
1536 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001538}
1539
Ruben Brunk183f0562015-08-12 12:55:02 -07001540status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001542
1543 size_t startIndex = 0;
1544 if (mStatusWaiters == 0) {
1545 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1546 // this status list
1547 mRecentStatusUpdates.clear();
1548 } else {
1549 // If other threads are waiting on updates to this status list, set the position of the
1550 // first element that this list will check rather than clearing the list.
1551 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 }
1553
Ruben Brunk183f0562015-08-12 12:55:02 -07001554 mStatusWaiters++;
1555
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001556 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001557 if (!active && mUseHalBufManager) {
1558 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001559 if (mStatus == STATUS_ACTIVE) {
1560 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001561 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001562 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001563 mRequestBufferSM.onWaitUntilIdle();
1564 }
1565
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001566 bool stateSeen = false;
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001567 nsecs_t startTime = systemTime();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001569 if (active == (mStatus == STATUS_ACTIVE)) {
1570 // Desired state is current
1571 break;
1572 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573
Avichal Rakesh976bb4d2022-05-02 15:23:00 -07001574 nsecs_t timeElapsed = systemTime() - startTime;
1575 nsecs_t timeToWait = timeout - timeElapsed;
1576 if (timeToWait <= 0) {
1577 // Thread woke up spuriously but has timed out since.
1578 // Force out of loop with TIMED_OUT result.
1579 res = TIMED_OUT;
1580 break;
1581 }
1582 res = mStatusChanged.waitRelative(mLock, timeToWait);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 if (res != OK) break;
1584
Ruben Brunk183f0562015-08-12 12:55:02 -07001585 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1586 // transitions.
1587 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1588 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1589 __FUNCTION__);
1590
1591 // Encountered desired state since we began waiting
1592 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001593 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1594 stateSeen = true;
1595 break;
1596 }
1597 }
1598 } while (!stateSeen);
1599
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001600 if (signalPipelineDrain) {
1601 mRequestThread->resetPipelineDrain();
1602 }
1603
Ruben Brunk183f0562015-08-12 12:55:02 -07001604 mStatusWaiters--;
1605
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001606 return res;
1607}
1608
1609
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001610status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001611 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001612 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001613
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001614 if (listener != NULL && mListener != NULL) {
1615 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1616 }
1617 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001618 mRequestThread->setNotificationListener(listener);
1619 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001620
1621 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001622}
1623
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001624bool Camera3Device::willNotify3A() {
1625 return false;
1626}
1627
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001628status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001629 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001630 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001631
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001632 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001633 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1634 if (st == std::cv_status::timeout) {
1635 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001636 }
1637 }
1638 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001639}
1640
Jianing Weicb0652e2014-03-12 18:29:36 -07001641status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001643 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001644
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001645 if (mResultQueue.empty()) {
1646 return NOT_ENOUGH_DATA;
1647 }
1648
Jianing Weicb0652e2014-03-12 18:29:36 -07001649 if (frame == NULL) {
1650 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1651 return BAD_VALUE;
1652 }
1653
1654 CaptureResult &result = *(mResultQueue.begin());
1655 frame->mResultExtras = result.mResultExtras;
1656 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001657 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001658 mResultQueue.erase(mResultQueue.begin());
1659
1660 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661}
1662
1663status_t Camera3Device::triggerAutofocus(uint32_t id) {
1664 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001665 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001666
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001667 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1668 // Mix-in this trigger into the next request and only the next request.
1669 RequestTrigger trigger[] = {
1670 {
1671 ANDROID_CONTROL_AF_TRIGGER,
1672 ANDROID_CONTROL_AF_TRIGGER_START
1673 },
1674 {
1675 ANDROID_CONTROL_AF_TRIGGER_ID,
1676 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001677 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001678 };
1679
1680 return mRequestThread->queueTrigger(trigger,
1681 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001682}
1683
1684status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1685 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001687
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001688 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1689 // Mix-in this trigger into the next request and only the next request.
1690 RequestTrigger trigger[] = {
1691 {
1692 ANDROID_CONTROL_AF_TRIGGER,
1693 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1694 },
1695 {
1696 ANDROID_CONTROL_AF_TRIGGER_ID,
1697 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001698 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001699 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001700
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001701 return mRequestThread->queueTrigger(trigger,
1702 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001703}
1704
1705status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1706 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001707 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001708
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001709 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1710 // Mix-in this trigger into the next request and only the next request.
1711 RequestTrigger trigger[] = {
1712 {
1713 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1714 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1715 },
1716 {
1717 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1718 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001719 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001720 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001721
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001722 return mRequestThread->queueTrigger(trigger,
1723 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724}
1725
Jianing Weicb0652e2014-03-12 18:29:36 -07001726status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001727 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001728 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001729 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001730
Zhijun He7ef20392014-04-21 16:04:17 -07001731 {
1732 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001733
1734 // b/116514106 "disconnect()" can get called twice for the same device. The
1735 // camera device will not be initialized during the second run.
1736 if (mStatus == STATUS_UNINITIALIZED) {
1737 return OK;
1738 }
1739
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001740 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001741
1742 // Stop session and stream counter
1743 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001744 }
1745
Ravneet98ffa752022-03-02 07:22:46 +00001746 // Calculate expected duration for flush with additional buffer time in ms for watchdog
Ravneet Dhanjal72c96652022-06-29 01:34:01 +00001747 uint64_t maxExpectedDuration = ns2ms(getExpectedInFlightDuration() + kBaseGetBufferWait);
Ravneet98ffa752022-03-02 07:22:46 +00001748 status_t res = mCameraServiceWatchdog->WATCH_CUSTOM_TIMER(mRequestThread->flush(),
1749 maxExpectedDuration / kCycleLengthMs, kCycleLengthMs);
1750
1751 return res;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001752}
1753
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001754status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001755 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1756}
1757
1758status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001759 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001760 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001761 Mutex::Autolock il(mInterfaceLock);
1762 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001763
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001764 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1765 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001766 CLOGE("Stream %d does not exist", streamId);
1767 return BAD_VALUE;
1768 }
1769
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001770 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001771 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001772 return BAD_VALUE;
1773 }
1774
1775 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001776 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001777 return BAD_VALUE;
1778 }
1779
Ruben Brunkc78ac262015-08-13 17:58:46 -07001780 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001781}
1782
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001783status_t Camera3Device::tearDown(int streamId) {
1784 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001785 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001786 Mutex::Autolock il(mInterfaceLock);
1787 Mutex::Autolock l(mLock);
1788
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001789 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1790 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001791 CLOGE("Stream %d does not exist", streamId);
1792 return BAD_VALUE;
1793 }
1794
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001795 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1796 CLOGE("Stream %d is a target of a in-progress request", streamId);
1797 return BAD_VALUE;
1798 }
1799
1800 return stream->tearDown();
1801}
1802
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001803status_t Camera3Device::addBufferListenerForStream(int streamId,
1804 wp<Camera3StreamBufferListener> listener) {
1805 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001806 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001807 Mutex::Autolock il(mInterfaceLock);
1808 Mutex::Autolock l(mLock);
1809
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001810 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1811 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001812 CLOGE("Stream %d does not exist", streamId);
1813 return BAD_VALUE;
1814 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001815 stream->addBufferListener(listener);
1816
1817 return OK;
1818}
1819
Austin Borger4a870a32022-02-25 01:48:41 +00001820float Camera3Device::getMaxPreviewFps(sp<camera3::Camera3OutputStreamInterface> stream) {
1821 camera_metadata_entry minDurations =
1822 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1823 for (size_t i = 0; i < minDurations.count; i += 4) {
1824 if (minDurations.data.i64[i] == stream->getFormat()
1825 && minDurations.data.i64[i+1] == stream->getWidth()
1826 && minDurations.data.i64[i+2] == stream->getHeight()) {
1827 int64_t minFrameDuration = minDurations.data.i64[i+3];
1828 return 1e9f / minFrameDuration;
1829 }
1830 }
1831 return 0.0f;
1832}
1833
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 * Methods called by subclasses
1836 */
1837
1838void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001839 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001840 std::vector<int> streamIds;
1841 std::vector<hardware::CameraStreamStats> streamStats;
Austin Borger4a870a32022-02-25 01:48:41 +00001842 float sessionMaxPreviewFps = 0.0f;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 {
1845 // Need mLock to safely update state and synchronize to current
1846 // state of methods in flight.
1847 Mutex::Autolock l(mLock);
1848 // We can get various system-idle notices from the status tracker
1849 // while starting up. Only care about them if we've actually sent
1850 // in some requests recently.
1851 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1852 return;
1853 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001854 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1855 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001856 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001857
1858 // Skip notifying listener if we're doing some user-transparent
1859 // state changes
1860 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001861
Austin Borger4a870a32022-02-25 01:48:41 +00001862 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1863 auto stream = mOutputStreams[i];
1864 if (stream.get() == nullptr) continue;
1865
1866 float streamMaxPreviewFps = getMaxPreviewFps(stream);
1867 sessionMaxPreviewFps = std::max(sessionMaxPreviewFps, streamMaxPreviewFps);
1868
1869 // Populate stream statistics in case of Idle
1870 if (idle) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001871 streamIds.push_back(stream->getId());
1872 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1873 int64_t usage = 0LL;
Shuzhen Wang8ed1e872022-03-08 16:34:33 -08001874 int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001875 if (camera3Stream != nullptr) {
1876 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001877 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001878 }
1879 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
Austin Borger4a870a32022-02-25 01:48:41 +00001880 stream->getFormat(), streamMaxPreviewFps, stream->getDataSpace(), usage,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001881 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001882 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001883 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001884 }
1885 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001886 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001887
1888 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001889 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001890 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001891 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001892 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001893 status_t res = OK;
1894 if (listener != nullptr) {
1895 if (idle) {
1896 // Get session stats from the builder, and notify the listener.
1897 int64_t requestCount, resultErrorCount;
1898 bool deviceError;
1899 std::map<int, StreamStats> streamStatsMap;
1900 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1901 &deviceError, &streamStatsMap);
1902 for (size_t i = 0; i < streamIds.size(); i++) {
1903 int streamId = streamIds[i];
1904 auto stats = streamStatsMap.find(streamId);
1905 if (stats != streamStatsMap.end()) {
1906 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1907 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1908 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1909 streamStats[i].mHistogramType =
1910 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1911 streamStats[i].mHistogramBins.assign(
1912 stats->second.mCaptureLatencyBins.begin(),
1913 stats->second.mCaptureLatencyBins.end());
1914 streamStats[i].mHistogramCounts.assign(
1915 stats->second.mCaptureLatencyHistogram.begin(),
1916 stats->second.mCaptureLatencyHistogram.end());
1917 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001918 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001919 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1920 } else {
Austin Borger4a870a32022-02-25 01:48:41 +00001921 res = listener->notifyActive(sessionMaxPreviewFps);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001922 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001923 }
1924 if (res != OK) {
1925 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1926 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001927 }
1928}
1929
Shuzhen Wang758c2152017-01-10 18:26:18 -08001930status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001931 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001932 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001933 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1934 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001935
1936 if (surfaceIds == nullptr) {
1937 return BAD_VALUE;
1938 }
1939
Zhijun He5d677d12016-05-29 16:52:39 -07001940 Mutex::Autolock il(mInterfaceLock);
1941 Mutex::Autolock l(mLock);
1942
Shuzhen Wang758c2152017-01-10 18:26:18 -08001943 if (consumers.size() == 0) {
1944 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001945 return BAD_VALUE;
1946 }
1947
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001948 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1949 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001950 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001951 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001952 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001953
1954 // isConsumerConfigurationDeferred will be off after setConsumers
1955 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001956 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001957 if (res != OK) {
1958 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1959 return res;
1960 }
1961
Emilian Peev40ead602017-09-26 15:46:36 +01001962 for (auto &consumer : consumers) {
1963 int id = stream->getSurfaceId(consumer);
1964 if (id < 0) {
1965 CLOGE("Invalid surface id!");
1966 return BAD_VALUE;
1967 }
1968 surfaceIds->push_back(id);
1969 }
1970
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001971 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001972 if (!stream->isConfiguring()) {
1973 CLOGE("Stream %d was already fully configured.", streamId);
1974 return INVALID_OPERATION;
1975 }
Zhijun He5d677d12016-05-29 16:52:39 -07001976
Shuzhen Wang0129d522016-10-30 22:43:41 -07001977 res = stream->finishConfiguration();
1978 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001979 // If finishConfiguration fails due to abandoned surface, do not set
1980 // device to error state.
1981 bool isSurfaceAbandoned =
1982 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1983 if (!isSurfaceAbandoned) {
1984 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1985 stream->getId(), strerror(-res), res);
1986 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001987 return res;
1988 }
Zhijun He5d677d12016-05-29 16:52:39 -07001989 }
1990
1991 return OK;
1992}
1993
Emilian Peev40ead602017-09-26 15:46:36 +01001994status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1995 const std::vector<OutputStreamInfo> &outputInfo,
1996 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1997 Mutex::Autolock il(mInterfaceLock);
1998 Mutex::Autolock l(mLock);
1999
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002000 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2001 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002002 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002003 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002004 }
2005
2006 for (const auto &it : removedSurfaceIds) {
2007 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2008 CLOGE("Shared surface still part of a pending request!");
2009 return -EBUSY;
2010 }
2011 }
2012
Emilian Peev40ead602017-09-26 15:46:36 +01002013 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2014 if (res != OK) {
2015 CLOGE("Stream %d failed to update stream (error %d %s) ",
2016 streamId, res, strerror(-res));
2017 if (res == UNKNOWN_ERROR) {
2018 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2019 __FUNCTION__);
2020 }
2021 return res;
2022 }
2023
2024 return res;
2025}
2026
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002027status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2028 Mutex::Autolock il(mInterfaceLock);
2029 Mutex::Autolock l(mLock);
2030
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002031 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2032 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002033 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2034 return BAD_VALUE;
2035 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002036
2037 if (dropping) {
2038 mSessionStatsBuilder.stopCounter(streamId);
2039 } else {
2040 mSessionStatsBuilder.startCounter(streamId);
2041 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002042 return stream->dropBuffers(dropping);
2043}
2044
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002045/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046 * Camera3Device private methods
2047 */
2048
2049sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002050 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002053 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002054 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002055
2056 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002057 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058 if (inputStreams.count > 0) {
2059 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002060 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002061 CLOGE("Request references unknown input stream %d",
2062 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002063 return NULL;
2064 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002065
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002066 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002067 SET_ERR_L("%s: input stream %d is not configured!",
2068 __FUNCTION__, mInputStream->getId());
2069 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002070 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002071 // Check if stream prepare is blocking requests.
2072 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002073 CLOGE("Request references an input stream that's being prepared!");
2074 return NULL;
2075 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076
2077 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002078 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002079 }
2080
2081 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002082 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002084 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002085 return NULL;
2086 }
2087
2088 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002089 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2090 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002091 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002092 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093 return NULL;
2094 }
Zhijun He5d677d12016-05-29 16:52:39 -07002095 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002096 auto iter = surfaceMap.find(streams.data.i32[i]);
2097 if (iter != surfaceMap.end()) {
2098 const std::vector<size_t>& surfaces = iter->second;
2099 for (const auto& surface : surfaces) {
2100 if (stream->isConsumerConfigurationDeferred(surface)) {
2101 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2102 "due to deferred consumer", stream->getId(), surface);
2103 return NULL;
2104 }
2105 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002106 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002107 }
2108
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002110 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2111 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002113 // Check if stream prepare is blocking requests.
2114 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002115 CLOGE("Request references an output stream that's being prepared!");
2116 return NULL;
2117 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002118
2119 newRequest->mOutputStreams.push(stream);
2120 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002121 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002122 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002124 auto rotateAndCropEntry =
2125 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2126 if (rotateAndCropEntry.count > 0 &&
2127 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2128 newRequest->mRotateAndCropAuto = true;
2129 } else {
2130 newRequest->mRotateAndCropAuto = false;
2131 }
2132
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002133 auto zoomRatioEntry =
2134 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2135 if (zoomRatioEntry.count > 0 &&
2136 zoomRatioEntry.data.f[0] == 1.0f) {
2137 newRequest->mZoomRatioIs1x = true;
2138 } else {
2139 newRequest->mZoomRatioIs1x = false;
2140 }
2141
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002142 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002143 for (auto& settings : newRequest->mSettingsList) {
2144 auto testPatternModeEntry =
2145 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2146 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2147 testPatternModeEntry.data.i32[0] :
2148 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002149
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002150 auto testPatternDataEntry =
2151 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2152 if (testPatternDataEntry.count >= 4) {
2153 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2154 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2155 } else {
2156 settings.mOriginalTestPatternData[0] = 0;
2157 settings.mOriginalTestPatternData[1] = 0;
2158 settings.mOriginalTestPatternData[2] = 0;
2159 settings.mOriginalTestPatternData[3] = 0;
2160 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002161 }
2162 }
2163
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002164 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002165}
2166
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002167void Camera3Device::cancelStreamsConfigurationLocked() {
2168 int res = OK;
2169 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2170 res = mInputStream->cancelConfiguration();
2171 if (res != OK) {
2172 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2173 mInputStream->getId(), strerror(-res), res);
2174 }
2175 }
2176
2177 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002178 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002179 if (outputStream->isConfiguring()) {
2180 res = outputStream->cancelConfiguration();
2181 if (res != OK) {
2182 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2183 outputStream->getId(), strerror(-res), res);
2184 }
2185 }
2186 }
2187
2188 // Return state to that at start of call, so that future configures
2189 // properly clean things up
2190 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2191 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002192
2193 res = mPreparerThread->resume();
2194 if (res != OK) {
2195 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2196 }
2197}
2198
Emilian Peev0d0191e2020-04-21 17:01:18 -07002199bool Camera3Device::checkAbandonedStreamsLocked() {
2200 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2201 return true;
2202 }
2203
2204 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2205 auto stream = mOutputStreams[i];
2206 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2207 return true;
2208 }
2209 }
2210
2211 return false;
2212}
2213
Emilian Peev3bead5f2020-05-28 17:29:08 -07002214bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002215 ATRACE_CALL();
2216 bool ret = false;
2217
Shuzhen Wang316781a2020-08-18 18:11:01 -07002218 nsecs_t startTime = systemTime();
2219
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002220 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002221 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2222
2223 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002224 if (checkAbandonedStreamsLocked()) {
2225 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2226 __FUNCTION__);
2227 return true;
2228 }
2229
Emilian Peev3bead5f2020-05-28 17:29:08 -07002230 status_t rc = NO_ERROR;
2231 bool markClientActive = false;
2232 if (mStatus == STATUS_ACTIVE) {
2233 markClientActive = true;
2234 mPauseStateNotify = true;
2235 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2236
2237 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2238 }
2239
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002240 if (rc == NO_ERROR) {
2241 mNeedConfig = true;
2242 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2243 if (rc == NO_ERROR) {
2244 ret = true;
2245 mPauseStateNotify = false;
2246 //Moving to active state while holding 'mLock' is important.
2247 //There could be pending calls to 'create-/deleteStream' which
2248 //will trigger another stream configuration while the already
2249 //present streams end up with outstanding buffers that will
2250 //not get drained.
2251 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002252 } else if (rc == DEAD_OBJECT) {
2253 // DEAD_OBJECT can be returned if either the consumer surface is
2254 // abandoned, or the HAL has died.
2255 // - If the HAL has died, configureStreamsLocked call will set
2256 // device to error state,
2257 // - If surface is abandoned, we should not set device to error
2258 // state.
2259 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002260 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002261 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002262 }
2263 } else {
2264 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2265 }
2266
Shuzhen Wang316781a2020-08-18 18:11:01 -07002267 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2268 ns2ms(systemTime() - startTime));
2269
Emilian Peev3bead5f2020-05-28 17:29:08 -07002270 if (markClientActive) {
2271 mStatusTracker->markComponentActive(clientStatusId);
2272 }
2273
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002274 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002275}
2276
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002277status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002278 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 ATRACE_CALL();
2280 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002281
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002282 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002283 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 return INVALID_OPERATION;
2285 }
2286
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002287 if (operatingMode < 0) {
2288 CLOGE("Invalid operating mode: %d", operatingMode);
2289 return BAD_VALUE;
2290 }
2291
2292 bool isConstrainedHighSpeed =
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00002293 CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE == operatingMode;
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002294
2295 if (mOperatingMode != operatingMode) {
2296 mNeedConfig = true;
2297 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2298 mOperatingMode = operatingMode;
2299 }
2300
Shuzhen Wangcddfdbf2022-06-15 14:22:02 -07002301 // Reset min expected duration when session is reconfigured.
2302 mMinExpectedDuration = 0;
2303
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002304 // In case called from configureStreams, abort queued input buffers not belonging to
2305 // any pending requests.
2306 if (mInputStream != NULL && notifyRequestThread) {
2307 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002308 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002309 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002310 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002311 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002312 if (res != OK) {
2313 // Exhausted acquiring all input buffers.
2314 break;
2315 }
2316
Emilian Peevf4816702020-04-03 15:44:51 -07002317 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002318 res = mInputStream->returnInputBuffer(inputBuffer);
2319 if (res != OK) {
2320 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2321 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2322 }
2323 }
2324 }
2325
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002326 if (!mNeedConfig) {
2327 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2328 return OK;
2329 }
2330
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002331 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002332 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002333 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2334 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002335 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002336 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002337 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002338 }
2339
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08002340 // Override stream use case based on "adb shell command"
2341 overrideStreamUseCaseLocked();
2342
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002344 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002345
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002346 mPreparerThread->pause();
2347
Emilian Peevf4816702020-04-03 15:44:51 -07002348 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002349 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002351 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002352
Emilian Peevf4816702020-04-03 15:44:51 -07002353 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002354 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002355 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002357
2358 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002359 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 inputStream = mInputStream->startConfiguration();
2361 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002362 CLOGE("Can't start input stream configuration");
2363 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364 return INVALID_OPERATION;
2365 }
2366 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002367
2368 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002369 }
2370
Shuzhen Wang99080502021-03-07 21:08:20 -08002371 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002372 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002373 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002374
2375 // Don't configure bidi streams twice, nor add them twice to the list
2376 if (mOutputStreams[i].get() ==
2377 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2378
2379 config.num_streams--;
2380 continue;
2381 }
2382
Emilian Peevf4816702020-04-03 15:44:51 -07002383 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002384 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002385 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002386 CLOGE("Can't start output stream configuration");
2387 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 return INVALID_OPERATION;
2389 }
2390 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002391
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002392 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002393 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2394 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002395 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2396 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002397 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2398 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002399 } else if (outputStream->data_space ==
2400 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2401 bufferSizes[k] = outputStream->width * outputStream->height;
2402 } else {
2403 ALOGW("%s: Blob dataSpace %d not supported",
2404 __FUNCTION__, outputStream->data_space);
2405 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002406 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002407
2408 if (mOutputStreams[i]->isMultiResolution()) {
2409 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2410 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2411 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2412 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002413
2414 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2415 composerSurfacePresent = true;
2416 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002417 }
2418
2419 config.streams = streams.editArray();
2420
2421 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002422 // max_buffers, usage, and priv fields, as well as data_space and format
2423 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002424
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002425 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002426 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002427 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002429 if (res == BAD_VALUE) {
2430 // HAL rejected this set of streams as unsupported, clean up config
2431 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002432 CLOGE("Set of requested inputs/outputs not supported by HAL");
2433 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002434 return BAD_VALUE;
2435 } else if (res != OK) {
2436 // Some other kind of error from configure_streams - this is not
2437 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002438 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2439 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440 return res;
2441 }
2442
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002443 // Finish all stream configuration immediately.
2444 // TODO: Try to relax this later back to lazy completion, which should be
2445 // faster
2446
Igor Murashkin073f8572013-05-02 14:59:28 -07002447 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002448 bool streamReConfigured = false;
2449 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002450 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002451 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002452 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002453 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002454 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2455 return DEAD_OBJECT;
2456 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002458 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002459 if (streamReConfigured) {
2460 mInterface->onStreamReConfigured(mInputStream->getId());
2461 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002462 }
2463
2464 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002465 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002466 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002467 bool streamReConfigured = false;
2468 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002469 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002470 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002471 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002472 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002473 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2474 return DEAD_OBJECT;
2475 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002476 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002477 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002478 if (streamReConfigured) {
2479 mInterface->onStreamReConfigured(outputStream->getId());
2480 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002481 }
2482 }
2483
Emilian Peeve23f1d92021-09-20 14:56:01 -07002484 mRequestThread->setComposerSurface(composerSurfacePresent);
2485
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002486 // Request thread needs to know to avoid using repeat-last-settings protocol
2487 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002488 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002489 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2490 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002491 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002492
Zhijun He90f7c372016-08-16 16:19:43 -07002493 char value[PROPERTY_VALUE_MAX];
2494 property_get("camera.fifo.disable", value, "0");
2495 int32_t disableFifo = atoi(value);
2496 if (disableFifo != 1) {
2497 // Boost priority of request thread to SCHED_FIFO.
2498 pid_t requestThreadTid = mRequestThread->getTid();
2499 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002500 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002501 if (res != OK) {
2502 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2503 strerror(-res), res);
2504 } else {
2505 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2506 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002507 }
2508
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002509 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002510 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2511 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2512 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2513 sessionParams.unlock(newSessionParams);
2514 mSessionParams.unlock(currentSessionParams);
2515 if (updateSessionParams) {
2516 mSessionParams = sessionParams;
2517 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002518
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002519 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002521 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002522 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002523
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002524 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002525
Zhijun He0a210512014-07-24 13:45:15 -07002526 // tear down the deleted streams after configure streams.
2527 mDeletedStreams.clear();
2528
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002529 auto rc = mPreparerThread->resume();
2530 if (rc != OK) {
2531 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2532 return rc;
2533 }
2534
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002535 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002536 mRequestBufferSM.onStreamsConfigured();
2537 }
2538
Cliff Wu3b268182021-07-06 15:44:43 +08002539 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002540 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002541 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002542 // configure the injection streams.
2543 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002544 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002545 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2546 res = mInjectionMethods->injectCamera(config, bufferSizes);
2547 if (res != OK) {
2548 ALOGE("Can't finish inject camera process!");
2549 return res;
2550 }
Cliff Wu3b268182021-07-06 15:44:43 +08002551 } else {
2552 // First run configureStreamsLocked() and then call injectCamera() case:
2553 // If the stream configuration has been completed and camera deive is active, but the
2554 // injection camera has not been injected yet, we need to store the stream configuration of
2555 // the internal camera (because the stream configuration of the injection camera is based
2556 // on the internal camera). When injecting occurs later, this configuration can be used by
2557 // the injection camera.
2558 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2559 " injection camera has not been injected yet.", __FUNCTION__);
2560 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002561 }
2562
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002563 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002564}
2565
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002566status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002567 ATRACE_CALL();
2568 status_t res;
2569
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002570 if (mFakeStreamId != NO_STREAM) {
2571 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002572 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002573 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002574 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002575 return INVALID_OPERATION;
2576 }
2577
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002578 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002579
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002580 sp<Camera3OutputStreamInterface> fakeStream =
2581 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002582
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002583 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002584 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002585 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002586 return res;
2587 }
2588
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002589 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002590 mNextStreamId++;
2591
2592 return OK;
2593}
2594
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002595status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002596 ATRACE_CALL();
2597 status_t res;
2598
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002599 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002600 if (mOutputStreams.size() == 1) return OK;
2601
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002602 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002603
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002604 // Ok, have a fake stream and there's at least one other output stream,
2605 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002606
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002607 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002608 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002609 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002610 return INVALID_OPERATION;
2611 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002612 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002613
2614 // Free up the stream endpoint so that it can be used by some other stream
2615 res = deletedStream->disconnect();
2616 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002617 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618 // fall through since we want to still list the stream as deleted.
2619 }
2620 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002621 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002622
2623 return res;
2624}
2625
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002626void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002627 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002628 Mutex::Autolock l(mLock);
2629 va_list args;
2630 va_start(args, fmt);
2631
2632 setErrorStateLockedV(fmt, args);
2633
2634 va_end(args);
2635}
2636
2637void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002638 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002639 Mutex::Autolock l(mLock);
2640 setErrorStateLockedV(fmt, args);
2641}
2642
2643void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2644 va_list args;
2645 va_start(args, fmt);
2646
2647 setErrorStateLockedV(fmt, args);
2648
2649 va_end(args);
2650}
2651
2652void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002653 // Print out all error messages to log
2654 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002655 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002656
2657 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002658 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002659
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002660 mErrorCause = errorCause;
2661
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002662 if (mRequestThread != nullptr) {
2663 mRequestThread->setPaused(true);
2664 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002665 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002666
2667 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002668 sp<NotificationListener> listener = mListener.promote();
2669 if (listener != NULL) {
2670 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002671 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002672 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002673 }
2674
2675 // Save stack trace. View by dumping it later.
2676 CameraTraces::saveTrace();
2677 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002678}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002679
2680/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002681 * In-flight request management
2682 */
2683
Jianing Weicb0652e2014-03-12 18:29:36 -07002684status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002685 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002686 bool hasAppCallback, nsecs_t minExpectedDuration, nsecs_t maxExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002687 bool isFixedFps, const std::set<std::set<String8>>& physicalCameraIds,
Shuzhen Wang99080502021-03-07 21:08:20 -08002688 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2689 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002690 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002691 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002692 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002693
2694 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002695 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07002696 hasAppCallback, minExpectedDuration, maxExpectedDuration, isFixedFps, physicalCameraIds,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08002697 isStillCapture, isZslCapture, rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs,
2698 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002699 if (res < 0) return res;
2700
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002701 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002702 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2703 // avoid a deadlock during reprocess requests.
2704 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002705 if (mStatusTracker != nullptr) {
2706 mStatusTracker->markComponentActive(mInFlightStatusId);
2707 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002708 }
2709
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002710 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002711 return OK;
2712}
2713
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002714void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002715 // Indicate idle inFlightMap to the status tracker
2716 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002717 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002718 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2719 // avoid a deadlock during reprocess requests.
2720 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002721 if (mStatusTracker != nullptr) {
2722 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2723 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002724 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002725 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002726}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002727
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002728void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002729 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002730 // something has likely gone wrong. This might still be legit only if application send in
2731 // a long burst of long exposure requests.
2732 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2733 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2734 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2735 mInFlightMap.size(), mExpectedInflightDuration);
2736 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2737 kInFlightWarnLimitHighSpeed) {
2738 CLOGW("In-flight list too large for high speed configuration: %zu,"
2739 "total inflight duration %" PRIu64,
2740 mInFlightMap.size(), mExpectedInflightDuration);
2741 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002742 }
2743}
2744
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002745void Camera3Device::onInflightMapFlushedLocked() {
2746 mExpectedInflightDuration = 0;
2747}
2748
2749void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002750 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002751 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2752 mInFlightMap.removeItemsAt(idx, 1);
2753
2754 onInflightEntryRemovedLocked(duration);
2755}
2756
2757
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002758void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002759 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002760 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002761 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002762 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002763 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002764 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002765
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002766 FlushInflightReqStates states {
2767 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002768 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002769
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002770 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002771}
2772
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002773CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002774 ALOGV("%s", __FUNCTION__);
2775
Igor Murashkin1e479c02013-09-06 16:55:14 -07002776 CameraMetadata retVal;
2777
2778 if (mRequestThread != NULL) {
2779 retVal = mRequestThread->getLatestRequest();
2780 }
2781
Igor Murashkin1e479c02013-09-06 16:55:14 -07002782 return retVal;
2783}
2784
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002785void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002786 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002787 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002788 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2789 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002790
2791 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002792 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002793}
2794
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002795void Camera3Device::cleanupNativeHandles(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002796 std::vector<native_handle_t*> *handles, bool closeFd) {
2797 if (handles == nullptr) {
2798 return;
2799 }
2800 if (closeFd) {
2801 for (auto& handle : *handles) {
2802 native_handle_close(handle);
2803 }
2804 }
2805 for (auto& handle : *handles) {
2806 native_handle_delete(handle);
2807 }
2808 handles->clear();
2809 return;
2810}
2811
Jayant Chowdhary35642f22022-01-08 00:39:39 +00002812/**
2813 * HalInterface inner class methods
2814 */
2815
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002816void Camera3Device::HalInterface::getInflightBufferKeys(
2817 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002818 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002819 return;
2820}
2821
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002822void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2823 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002824 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002825 return;
2826}
2827
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002828bool Camera3Device::HalInterface::verifyBufferIds(
2829 int32_t streamId, std::vector<uint64_t>& bufIds) {
2830 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002831}
2832
2833status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002834 int32_t frameNumber, int32_t streamId,
2835 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002836 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002837}
2838
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002839status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002840 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002841 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002842}
2843
2844// Find and pop a buffer_handle_t based on bufferId
2845status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002846 uint64_t bufferId,
2847 /*out*/ buffer_handle_t** buffer,
2848 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002849 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002850}
2851
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002852std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2853 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002854 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002855}
2856
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002857uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2858 const native_handle_t* handle) {
2859 return mBufferRecords.removeOneBufferCache(streamId, handle);
2860}
2861
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002862void Camera3Device::HalInterface::onBufferFreed(
2863 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002864 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2865 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2866 if (bufferId != BUFFER_ID_NO_BUFFER) {
2867 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002868 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002869}
2870
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002871void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002872 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2873 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2874 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002875 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2876 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002877}
2878
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002879/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880 * RequestThread inner class methods
2881 */
2882
2883Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002884 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002885 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002886 bool useHalBufManager,
Austin Borger3560b7e2022-10-27 12:20:29 -07002887 bool supportCameraMute,
2888 bool overrideToPortrait) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002889 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002890 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002891 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002892 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002893 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002894 mId(getId(parent)),
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07002895 mRequestClearing(false),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002896 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002897 mReconfigured(false),
2898 mDoPause(false),
2899 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002900 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002901 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002902 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002903 mCurrentAfTriggerId(0),
2904 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002905 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002906 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002907 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002908 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002909 mRepeatingLastFrameNumber(
2910 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002911 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002912 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002913 mRequestLatency(kRequestLatencyBinSize),
2914 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002915 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002916 mUseHalBufManager(useHalBufManager),
Austin Borger3560b7e2022-10-27 12:20:29 -07002917 mSupportCameraMute(supportCameraMute),
2918 mOverrideToPortrait(overrideToPortrait) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002919 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002920}
2921
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922Camera3Device::RequestThread::~RequestThread() {}
2923
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002924void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002925 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002927 Mutex::Autolock l(mRequestLock);
2928 mListener = listener;
2929}
2930
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002931void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002932 const CameraMetadata& sessionParams,
2933 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002934 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002935 Mutex::Autolock l(mRequestLock);
2936 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002937 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002938 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002939 // Prepare video stream for high speed recording.
2940 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002941 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002942}
2943
Jianing Wei90e59c92014-03-12 18:29:36 -07002944status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002945 List<sp<CaptureRequest> > &requests,
2946 /*out*/
2947 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002948 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002949 Mutex::Autolock l(mRequestLock);
2950 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2951 ++it) {
2952 mRequestQueue.push_back(*it);
2953 }
2954
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002955 if (lastFrameNumber != NULL) {
2956 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2957 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2958 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2959 *lastFrameNumber);
2960 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002961
Jianing Wei90e59c92014-03-12 18:29:36 -07002962 unpauseForNewRequests();
2963
2964 return OK;
2965}
2966
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002967
2968status_t Camera3Device::RequestThread::queueTrigger(
2969 RequestTrigger trigger[],
2970 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002971 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002972 Mutex::Autolock l(mTriggerMutex);
2973 status_t ret;
2974
2975 for (size_t i = 0; i < count; ++i) {
2976 ret = queueTriggerLocked(trigger[i]);
2977
2978 if (ret != OK) {
2979 return ret;
2980 }
2981 }
2982
2983 return OK;
2984}
2985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002986const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2987 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002988 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002989 if (d != nullptr) return d->mId;
2990 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002991}
2992
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002993status_t Camera3Device::RequestThread::queueTriggerLocked(
2994 RequestTrigger trigger) {
2995
2996 uint32_t tag = trigger.metadataTag;
2997 ssize_t index = mTriggerMap.indexOfKey(tag);
2998
2999 switch (trigger.getTagType()) {
3000 case TYPE_BYTE:
3001 // fall-through
3002 case TYPE_INT32:
3003 break;
3004 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003005 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3006 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003007 return INVALID_OPERATION;
3008 }
3009
3010 /**
3011 * Collect only the latest trigger, since we only have 1 field
3012 * in the request settings per trigger tag, and can't send more than 1
3013 * trigger per request.
3014 */
3015 if (index != NAME_NOT_FOUND) {
3016 mTriggerMap.editValueAt(index) = trigger;
3017 } else {
3018 mTriggerMap.add(tag, trigger);
3019 }
3020
3021 return OK;
3022}
3023
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003024status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003025 const RequestList &requests,
3026 /*out*/
3027 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003028 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003029 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003030 if (lastFrameNumber != NULL) {
3031 *lastFrameNumber = mRepeatingLastFrameNumber;
3032 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003033 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003034 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003035 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3036 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003037
3038 unpauseForNewRequests();
3039
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003041 return OK;
3042}
3043
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003044bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003045 if (mRepeatingRequests.empty()) {
3046 return false;
3047 }
3048 int32_t requestId = requestIn->mResultExtras.requestId;
3049 const RequestList &repeatRequests = mRepeatingRequests;
3050 // All repeating requests are guaranteed to have same id so only check first quest
3051 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3052 return (firstRequest->mResultExtras.requestId == requestId);
3053}
3054
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003055status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003056 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003057 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003058 return clearRepeatingRequestsLocked(lastFrameNumber);
3059
3060}
3061
3062status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003063 std::vector<int32_t> streamIds;
3064 for (const auto& request : mRepeatingRequests) {
3065 for (const auto& stream : request->mOutputStreams) {
3066 streamIds.push_back(stream->getId());
3067 }
3068 }
3069
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003070 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003071 if (lastFrameNumber != NULL) {
3072 *lastFrameNumber = mRepeatingLastFrameNumber;
3073 }
Emilian Peev2295df72021-11-12 18:14:10 -08003074
3075 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3076
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003077 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003078 return OK;
3079}
3080
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003081status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003082 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003083 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003084 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003085 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003086
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003087 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003088
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003089 // Send errors for all requests pending in the request queue, including
3090 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003091 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003092 if (listener != NULL) {
3093 for (RequestList::iterator it = mRequestQueue.begin();
3094 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003095 // Abort the input buffers for reprocess requests.
3096 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003097 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003098 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003099 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003100 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003101 if (res != OK) {
3102 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3103 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3104 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003105 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003106 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3107 if (res != OK) {
3108 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3109 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3110 }
3111 }
3112 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003113 // Set the frame number this request would have had, if it
3114 // had been submitted; this frame number will not be reused.
3115 // The requestId and burstId fields were set when the request was
3116 // submitted originally (in convertMetadataListToRequestListLocked)
3117 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003118 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003119 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003120 }
3121 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003122 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003123
3124 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003125 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003126 if (lastFrameNumber != NULL) {
3127 *lastFrameNumber = mRepeatingLastFrameNumber;
3128 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003129 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07003130 mRequestClearing = true;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003131 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003132 return OK;
3133}
3134
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003135status_t Camera3Device::RequestThread::flush() {
3136 ATRACE_CALL();
3137 Mutex::Autolock l(mFlushLock);
3138
Emilian Peev08dd2452017-04-06 16:55:14 +01003139 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003140}
3141
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003142void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003143 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003144 Mutex::Autolock l(mPauseLock);
3145 mDoPause = paused;
3146 mDoPauseSignal.signal();
3147}
3148
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003149status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3150 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003151 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003152 Mutex::Autolock l(mLatestRequestMutex);
3153 status_t res;
3154 while (mLatestRequestId != requestId) {
3155 nsecs_t startTime = systemTime();
3156
3157 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3158 if (res != OK) return res;
3159
3160 timeout -= (systemTime() - startTime);
3161 }
3162
3163 return OK;
3164}
3165
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003166void Camera3Device::RequestThread::requestExit() {
3167 // Call parent to set up shutdown
3168 Thread::requestExit();
3169 // The exit from any possible waits
3170 mDoPauseSignal.signal();
3171 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003172
3173 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3174 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003175}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003176
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003177void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003178 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003179 bool surfaceAbandoned = false;
3180 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003181 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003182 {
3183 Mutex::Autolock l(mRequestLock);
3184 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3185 // repeating requests.
3186 for (const auto& request : mRepeatingRequests) {
3187 for (const auto& s : request->mOutputStreams) {
3188 if (s->isAbandoned()) {
3189 surfaceAbandoned = true;
3190 clearRepeatingRequestsLocked(&lastFrameNumber);
3191 break;
3192 }
3193 }
3194 if (surfaceAbandoned) {
3195 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003196 }
3197 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003198 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003199 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003200
3201 if (listener != NULL && surfaceAbandoned) {
3202 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003203 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003204}
3205
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003206bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003207 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003208 status_t res;
3209 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003210 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003211 uint32_t numRequestProcessed = 0;
3212 for (size_t i = 0; i < batchSize; i++) {
3213 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003214 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003215 }
3216
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003217 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3218
3219 bool triggerRemoveFailed = false;
3220 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3221 for (size_t i = 0; i < numRequestProcessed; i++) {
3222 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3223 nextRequest.submitted = true;
3224
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003225 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003226
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003227 if (!triggerRemoveFailed) {
3228 // Remove any previously queued triggers (after unlock)
3229 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3230 if (removeTriggerRes != OK) {
3231 triggerRemoveFailed = true;
3232 triggerFailedRequest = nextRequest;
3233 }
3234 }
3235 }
3236
3237 if (triggerRemoveFailed) {
3238 SET_ERR("RequestThread: Unable to remove triggers "
3239 "(capture request %d, HAL device: %s (%d)",
3240 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3241 cleanUpFailedRequests(/*sendRequestError*/ false);
3242 return false;
3243 }
3244
3245 if (res != OK) {
3246 // Should only get a failure here for malformed requests or device-level
3247 // errors, so consider all errors fatal. Bad metadata failures should
3248 // come through notify.
3249 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3250 mNextRequests[numRequestProcessed].halRequest.frame_number,
3251 strerror(-res), res);
3252 cleanUpFailedRequests(/*sendRequestError*/ false);
3253 return false;
3254 }
3255 return true;
3256}
3257
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003258Camera3Device::RequestThread::ExpectedDurationInfo
3259 Camera3Device::RequestThread::calculateExpectedDurationRange(
3260 const camera_metadata_t *request) {
3261 ExpectedDurationInfo expectedDurationInfo = {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08003262 InFlightRequest::kDefaultMinExpectedDuration,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003263 InFlightRequest::kDefaultMaxExpectedDuration,
3264 /*isFixedFps*/false};
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003265 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3266 find_camera_metadata_ro_entry(request,
3267 ANDROID_CONTROL_AE_MODE,
3268 &e);
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003269 if (e.count == 0) return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003270
3271 switch (e.data.u8[0]) {
3272 case ANDROID_CONTROL_AE_MODE_OFF:
3273 find_camera_metadata_ro_entry(request,
3274 ANDROID_SENSOR_EXPOSURE_TIME,
3275 &e);
3276 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003277 expectedDurationInfo.minDuration = e.data.i64[0];
3278 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003279 }
3280 find_camera_metadata_ro_entry(request,
3281 ANDROID_SENSOR_FRAME_DURATION,
3282 &e);
3283 if (e.count > 0) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003284 expectedDurationInfo.minDuration =
3285 std::max(e.data.i64[0], expectedDurationInfo.minDuration);
3286 expectedDurationInfo.maxDuration = expectedDurationInfo.minDuration;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003287 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003288 expectedDurationInfo.isFixedFps = false;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003289 break;
3290 default:
3291 find_camera_metadata_ro_entry(request,
3292 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3293 &e);
3294 if (e.count > 1) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003295 expectedDurationInfo.minDuration = 1e9 / e.data.i32[1];
3296 expectedDurationInfo.maxDuration = 1e9 / e.data.i32[0];
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003297 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003298 expectedDurationInfo.isFixedFps = (e.data.i32[1] == e.data.i32[0]);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003299 break;
3300 }
3301
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003302 return expectedDurationInfo;
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003303}
3304
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003305bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3306 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3307 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3308 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3309 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3310 return true;
3311 }
3312
3313 return false;
3314}
3315
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003316void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3317 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003318 camera_capture_request_t& halRequest = nextRequest.halRequest;
3319 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003320 Mutex::Autolock al(mLatestRequestMutex);
3321
Shuzhen Wang83bff122020-11-20 15:51:39 -08003322 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003323 mLatestRequest.acquire(cloned);
3324
3325 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003326 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3327 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3328 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003329 CameraMetadata(cloned));
3330 }
3331
3332 sp<Camera3Device> parent = mParent.promote();
3333 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003334 int32_t inputStreamId = -1;
3335 if (halRequest.input_buffer != nullptr) {
3336 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3337 }
3338
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003339 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003340 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003341 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3342 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003343 }
3344 }
3345
Shuzhen Wang83bff122020-11-20 15:51:39 -08003346 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003347 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003348 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003349 }
3350
Shuzhen Wang83bff122020-11-20 15:51:39 -08003351 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003352}
3353
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003354bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3355 ATRACE_CALL();
3356 bool updatesDetected = false;
3357
Emilian Peev4ec17882019-01-24 17:16:58 -08003358 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003359 for (auto tag : mSessionParamKeys) {
3360 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003361 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003362
3363 if (entry.count > 0) {
3364 bool isDifferent = false;
3365 if (lastEntry.count > 0) {
3366 // Have a last value, compare to see if changed
3367 if (lastEntry.type == entry.type &&
3368 lastEntry.count == entry.count) {
3369 // Same type and count, compare values
3370 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3371 size_t entryBytes = bytesPerValue * lastEntry.count;
3372 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3373 if (cmp != 0) {
3374 isDifferent = true;
3375 }
3376 } else {
3377 // Count or type has changed
3378 isDifferent = true;
3379 }
3380 } else {
3381 // No last entry, so always consider to be different
3382 isDifferent = true;
3383 }
3384
3385 if (isDifferent) {
3386 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003387 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3388 updatesDetected = true;
3389 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003390 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003391 }
3392 } else if (lastEntry.count > 0) {
3393 // Value has been removed
3394 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003395 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003396 updatesDetected = true;
3397 }
3398 }
3399
Emilian Peev4ec17882019-01-24 17:16:58 -08003400 bool reconfigureRequired;
3401 if (updatesDetected) {
3402 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3403 updatedParams);
3404 mLatestSessionParams = updatedParams;
3405 } else {
3406 reconfigureRequired = false;
3407 }
3408
3409 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003410}
3411
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003412bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003413 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003414 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003415 // Any function called from threadLoop() must not hold mInterfaceLock since
3416 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3417 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003418
3419 // Handle paused state.
3420 if (waitIfPaused()) {
3421 return true;
3422 }
3423
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003424 // Wait for the next batch of requests.
3425 waitForNextRequestBatch();
3426 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003427 return true;
3428 }
3429
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003430 // Get the latest request ID, if any
3431 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003432 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003433 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003434 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003435 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003436 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003437 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3438 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003439 }
3440
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003441 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3442 // or a single request from streaming or burst. In either case the first element
3443 // should contain the latest camera settings that we need to check for any session
3444 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003445 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003446 res = OK;
3447
3448 //Input stream buffers are already acquired at this point so an input stream
3449 //will not be able to move to idle state unless we force it.
3450 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3451 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3452 if (res != OK) {
3453 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3454 cleanUpFailedRequests(/*sendRequestError*/ false);
3455 return false;
3456 }
3457 }
3458
3459 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003460 sp<Camera3Device> parent = mParent.promote();
3461 if (parent != nullptr) {
3462 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003463 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003464 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003465
3466 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3467 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3468 if (res != OK) {
3469 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3470 cleanUpFailedRequests(/*sendRequestError*/ false);
3471 return false;
3472 }
3473 }
3474 }
3475 }
3476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003477 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003478 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003479 if (res == TIMED_OUT) {
3480 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003481 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003482 // Check if any stream is abandoned.
3483 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003484 return true;
3485 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003486 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003487 return false;
3488 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003489
Zhijun Hecc27e112013-10-03 16:12:43 -07003490 // Inform waitUntilRequestProcessed thread of a new request ID
3491 {
3492 Mutex::Autolock al(mLatestRequestMutex);
3493
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003494 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003495 mLatestRequestSignal.signal();
3496 }
3497
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003498 // Submit a batch of requests to HAL.
3499 // Use flush lock only when submitting multilple requests in a batch.
3500 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3501 // which may take a long time to finish so synchronizing flush() and
3502 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3503 // For now, only synchronize for high speed recording and we should figure something out for
3504 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003505 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003506
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003507 if (useFlushLock) {
3508 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003509 }
3510
Zhijun Hef0645c12016-08-02 00:58:11 -07003511 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003512 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003513
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003514 sp<Camera3Device> parent = mParent.promote();
3515 if (parent != nullptr) {
3516 parent->mRequestBufferSM.onSubmittingRequest();
3517 }
3518
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003519 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003520 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003521 submitRequestSuccess = sendRequestsBatch();
3522
Shuzhen Wang686f6442017-06-20 16:16:04 -07003523 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3524 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003525
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003526 if (useFlushLock) {
3527 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003528 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003529
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003530 // Unset as current request
3531 {
3532 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003533 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003534 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003535 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003536
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003537 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003538}
3539
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003540status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3541 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3542 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3543 ANDROID_SCALER_CROP_REGION_SET};
3544 if (request == nullptr) {
3545 ALOGE("%s request metadata nullptr", __FUNCTION__);
3546 return BAD_VALUE;
3547 }
3548 status_t res = OK;
3549 for (const auto &key : kFwkOnlyRegionKeys) {
3550 if (request->exists(key)) {
3551 res = request->erase(key);
3552 if (res != OK) {
3553 return res;
3554 }
3555 }
3556 }
3557 return OK;
3558}
3559
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003560status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003561 ATRACE_CALL();
3562
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003563 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003564 for (size_t i = 0; i < mNextRequests.size(); i++) {
3565 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003566 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003567 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3568 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003569
3570 // Prepare a request to HAL
3571 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3572
3573 // Insert any queued triggers (before metadata is locked)
3574 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003575 if (res < 0) {
3576 SET_ERR("RequestThread: Unable to insert triggers "
3577 "(capture request %d, HAL device: %s (%d)",
3578 halRequest->frame_number, strerror(-res), res);
3579 return INVALID_OPERATION;
3580 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003581
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003582 int triggerCount = res;
3583 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3584 mPrevTriggers = triggerCount;
3585
Emilian Peeve23f1d92021-09-20 14:56:01 -07003586 // Do not override rotate&crop for stream configurations that include
Austin Borger3560b7e2022-10-27 12:20:29 -07003587 // SurfaceViews(HW_COMPOSER) output, unless mOverrideToPortrait is set.
3588 // The display rotation there will be compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3589 bool rotateAndCropChanged = (mComposerOutput && !mOverrideToPortrait) ? false :
Emilian Peeve23f1d92021-09-20 14:56:01 -07003590 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003591 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003592
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003593 // If the request is the same as last, or we had triggers now or last time or
3594 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003595 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003596 (mPrevRequest != captureRequest || triggersMixedIn ||
3597 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003598 // Request settings are all the same within one batch, so only treat the first
3599 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003600 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003601 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003602 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003603 /**
3604 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003605 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003606 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003607 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003608 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003609 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003610 "(capture request %d, HAL device: %s (%d)",
3611 halRequest->frame_number, strerror(-res), res);
3612 return INVALID_OPERATION;
3613 }
3614
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003615 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003616 sp<Camera3Device> parent = mParent.promote();
3617 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003618 List<PhysicalCameraSettings>::iterator it;
3619 for (it = captureRequest->mSettingsList.begin();
3620 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003621 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3622 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003623 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3624 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3625 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3626 res);
3627 return INVALID_OPERATION;
3628 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003629 continue;
3630 }
3631
3632 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3633 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3634 updateCaptureRequest(&(it->metadata));
3635 if (res != OK) {
3636 SET_ERR("RequestThread: Unable to correct capture requests "
3637 "for scaler crop region and metering regions for request "
3638 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3639 res);
3640 return INVALID_OPERATION;
3641 }
3642 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003643 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3644 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3645 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3646 res);
3647 return INVALID_OPERATION;
3648 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003649 }
3650 }
3651
3652 // Correct metadata regions for distortion correction if enabled
3653 for (it = captureRequest->mSettingsList.begin();
3654 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003655 if (parent->mDistortionMappers.find(it->cameraId) ==
3656 parent->mDistortionMappers.end()) {
3657 continue;
3658 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003659
3660 if (!captureRequest->mDistortionCorrectionUpdated) {
3661 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3662 &(it->metadata));
3663 if (res != OK) {
3664 SET_ERR("RequestThread: Unable to correct capture requests "
3665 "for lens distortion for request %d: %s (%d)",
3666 halRequest->frame_number, strerror(-res), res);
3667 return INVALID_OPERATION;
3668 }
3669 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003670 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003671 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003672
3673 for (it = captureRequest->mSettingsList.begin();
3674 it != captureRequest->mSettingsList.end(); it++) {
3675 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3676 parent->mZoomRatioMappers.end()) {
3677 continue;
3678 }
3679
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003680 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003681 cameraIdsWithZoom.insert(it->cameraId);
3682 }
3683
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003684 if (!captureRequest->mZoomRatioUpdated) {
3685 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3686 &(it->metadata));
3687 if (res != OK) {
3688 SET_ERR("RequestThread: Unable to correct capture requests "
3689 "for zoom ratio for request %d: %s (%d)",
3690 halRequest->frame_number, strerror(-res), res);
3691 return INVALID_OPERATION;
3692 }
3693 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003694 }
3695 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003696 if (captureRequest->mRotateAndCropAuto &&
3697 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003698 for (it = captureRequest->mSettingsList.begin();
3699 it != captureRequest->mSettingsList.end(); it++) {
3700 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3701 if (mapper != parent->mRotateAndCropMappers.end()) {
3702 res = mapper->second.updateCaptureRequest(&(it->metadata));
3703 if (res != OK) {
3704 SET_ERR("RequestThread: Unable to correct capture requests "
3705 "for rotate-and-crop for request %d: %s (%d)",
3706 halRequest->frame_number, strerror(-res), res);
3707 return INVALID_OPERATION;
3708 }
3709 }
3710 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003711 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003712 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003713 }
3714 }
3715
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003716 /**
3717 * The request should be presorted so accesses in HAL
3718 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3719 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003720 captureRequest->mSettingsList.begin()->metadata.sort();
3721 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003722 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003723 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003724 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3725
3726 IF_ALOGV() {
3727 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3728 find_camera_metadata_ro_entry(
3729 halRequest->settings,
3730 ANDROID_CONTROL_AF_TRIGGER,
3731 &e
3732 );
3733 if (e.count > 0) {
3734 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3735 __FUNCTION__,
3736 halRequest->frame_number,
3737 e.data.u8[0]);
3738 }
3739 }
3740 } else {
3741 // leave request.settings NULL to indicate 'reuse latest given'
3742 ALOGVV("%s: Request settings are REUSED",
3743 __FUNCTION__);
3744 }
3745
Emilian Peevaebbe412018-01-15 13:53:24 +00003746 if (captureRequest->mSettingsList.size() > 1) {
3747 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3748 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003749 if (newRequest) {
3750 halRequest->physcam_settings =
3751 new const camera_metadata* [halRequest->num_physcam_settings];
3752 } else {
3753 halRequest->physcam_settings = nullptr;
3754 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003755 auto it = ++captureRequest->mSettingsList.begin();
3756 size_t i = 0;
3757 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3758 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003759 if (newRequest) {
3760 it->metadata.sort();
3761 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3762 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003763 }
3764 }
3765
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003766 uint32_t totalNumBuffers = 0;
3767
3768 // Fill in buffers
3769 if (captureRequest->mInputStream != NULL) {
3770 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003771
3772 halRequest->input_width = captureRequest->mInputBufferSize.width;
3773 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003774 totalNumBuffers += 1;
3775 } else {
3776 halRequest->input_buffer = NULL;
3777 }
3778
Emilian Peevf4816702020-04-03 15:44:51 -07003779 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003780 captureRequest->mOutputStreams.size());
3781 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003782 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003783
3784 sp<Camera3Device> parent = mParent.promote();
3785 if (parent == NULL) {
3786 // Should not happen, and nowhere to send errors to, so just log it
3787 CLOGE("RequestThread: Parent is gone");
3788 return INVALID_OPERATION;
3789 }
3790 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3791
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003792 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003793 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003794 sp<Camera3OutputStreamInterface> outputStream =
3795 captureRequest->mOutputStreams.editItemAt(j);
3796 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003797
3798 // Prepare video buffers for high speed recording on the first video request.
3799 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3800 // Only try to prepare video stream on the first video request.
3801 mPrepareVideoStream = false;
3802
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003803 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3804 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003805 while (res == NOT_ENOUGH_DATA) {
3806 res = outputStream->prepareNextBuffer();
3807 }
3808 if (res != OK) {
3809 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3810 __FUNCTION__, strerror(-res), res);
3811 outputStream->cancelPrepare();
3812 }
3813 }
3814
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003815 std::vector<size_t> uniqueSurfaceIds;
3816 res = outputStream->getUniqueSurfaceIds(
3817 captureRequest->mOutputSurfaces[streamId],
3818 &uniqueSurfaceIds);
3819 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3820 if (res != OK && res != INVALID_OPERATION) {
3821 ALOGE("%s: failed to query stream %d unique surface IDs",
3822 __FUNCTION__, streamId);
3823 return res;
3824 }
3825 if (res == OK) {
3826 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3827 }
3828
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003829 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003830 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003831 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003832 return TIMED_OUT;
3833 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003834 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003835 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003836 buffer.stream = outputStream->asHalStream();
3837 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003838 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003839 buffer.acquire_fence = -1;
3840 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003841 // Mark the output stream as unpreparable to block clients from calling
3842 // 'prepare' after this request reaches CameraHal and before the respective
3843 // buffers are requested.
3844 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003845 } else {
3846 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3847 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003848 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003849 if (res != OK) {
3850 // Can't get output buffer from gralloc queue - this could be due to
3851 // abandoned queue or other consumer misbehavior, so not a fatal
3852 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003853 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003854 " %s (%d)", strerror(-res), res);
3855
3856 return TIMED_OUT;
3857 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003858 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003859
3860 {
3861 sp<Camera3Device> parent = mParent.promote();
3862 if (parent != nullptr) {
3863 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3864 for (const auto& settings : captureRequest->mSettingsList) {
3865 if ((streamCameraId.isEmpty() &&
3866 parent->getId() == settings.cameraId.c_str()) ||
3867 streamCameraId == settings.cameraId.c_str()) {
3868 outputStream->fireBufferRequestForFrameNumber(
3869 captureRequest->mResultExtras.frameNumber,
3870 settings.metadata);
3871 }
3872 }
3873 }
3874 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003875
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003876 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003877 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3878 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3879 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3880 } else if (!physicalCameraId.isEmpty()) {
3881 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003882 }
3883 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003884 }
3885 totalNumBuffers += halRequest->num_output_buffers;
3886
3887 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003888 // If this request list is for constrained high speed recording (not
3889 // preview), and the current request is not the last one in the batch,
3890 // do not send callback to the app.
3891 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003892 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003893 hasCallback = false;
3894 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003895 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003896 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003897 const camera_metadata_t* settings = halRequest->settings;
3898 bool shouldUnlockSettings = false;
3899 if (settings == nullptr) {
3900 shouldUnlockSettings = true;
3901 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3902 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003903 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3904 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003905 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003906 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3907 isStillCapture = true;
3908 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3909 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003910
Emilian Peevaf8416e2021-02-04 17:52:43 -08003911 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003912 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003913 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3914 isZslCapture = true;
3915 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003916 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003917 auto expectedDurationInfo = calculateExpectedDurationRange(settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003918 res = parent->registerInFlight(halRequest->frame_number,
3919 totalNumBuffers, captureRequest->mResultExtras,
3920 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003921 hasCallback,
Shuzhen Wang696e4da2022-09-08 14:31:13 -07003922 expectedDurationInfo.minDuration,
3923 expectedDurationInfo.maxDuration,
3924 expectedDurationInfo.isFixedFps,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003925 requestedPhysicalCameras, isStillCapture, isZslCapture,
3926 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003927 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003928 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003929 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3930 ", burstId = %" PRId32 ".",
3931 __FUNCTION__,
3932 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3933 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003934
3935 if (shouldUnlockSettings) {
3936 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3937 }
3938
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003939 if (res != OK) {
3940 SET_ERR("RequestThread: Unable to register new in-flight request:"
3941 " %s (%d)", strerror(-res), res);
3942 return INVALID_OPERATION;
3943 }
3944 }
3945
3946 return OK;
3947}
3948
Igor Murashkin1e479c02013-09-06 16:55:14 -07003949CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003950 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003951 Mutex::Autolock al(mLatestRequestMutex);
3952
3953 ALOGV("RequestThread::%s", __FUNCTION__);
3954
3955 return mLatestRequest;
3956}
3957
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003958bool Camera3Device::RequestThread::isStreamPending(
3959 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003960 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003961 Mutex::Autolock l(mRequestLock);
3962
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003963 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003964 if (!nextRequest.submitted) {
3965 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3966 if (stream == s) return true;
3967 }
3968 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003969 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003970 }
3971
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003972 for (const auto& request : mRequestQueue) {
3973 for (const auto& s : request->mOutputStreams) {
3974 if (stream == s) return true;
3975 }
3976 if (stream == request->mInputStream) return true;
3977 }
3978
3979 for (const auto& request : mRepeatingRequests) {
3980 for (const auto& s : request->mOutputStreams) {
3981 if (stream == s) return true;
3982 }
3983 if (stream == request->mInputStream) return true;
3984 }
3985
3986 return false;
3987}
Jianing Weicb0652e2014-03-12 18:29:36 -07003988
Emilian Peev40ead602017-09-26 15:46:36 +01003989bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3990 ATRACE_CALL();
3991 Mutex::Autolock l(mRequestLock);
3992
3993 for (const auto& nextRequest : mNextRequests) {
3994 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3995 if (s.first == streamId) {
3996 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3997 if (it != s.second.end()) {
3998 return true;
3999 }
4000 }
4001 }
4002 }
4003
4004 for (const auto& request : mRequestQueue) {
4005 for (const auto& s : request->mOutputSurfaces) {
4006 if (s.first == streamId) {
4007 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4008 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004009 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004010 }
4011 }
4012 }
4013 }
4014
4015 for (const auto& request : mRepeatingRequests) {
4016 for (const auto& s : request->mOutputSurfaces) {
4017 if (s.first == streamId) {
4018 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4019 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004020 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004021 }
4022 }
4023 }
4024 }
4025
4026 return false;
4027}
4028
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004029void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4030 if (!mUseHalBufManager) {
4031 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4032 return;
4033 }
4034
4035 Mutex::Autolock pl(mPauseLock);
4036 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004037 mInterface->signalPipelineDrain(streamIds);
4038 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004039 }
4040 // If request thread is still busy, wait until paused then notify HAL
4041 mNotifyPipelineDrain = true;
4042 mStreamIdsToBeDrained = streamIds;
4043}
4044
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004045void Camera3Device::RequestThread::resetPipelineDrain() {
4046 Mutex::Autolock pl(mPauseLock);
4047 mNotifyPipelineDrain = false;
4048 mStreamIdsToBeDrained.clear();
4049}
4050
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004051void Camera3Device::RequestThread::clearPreviousRequest() {
4052 Mutex::Autolock l(mRequestLock);
4053 mPrevRequest.clear();
4054}
4055
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004056status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4057 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4058 ATRACE_CALL();
4059 Mutex::Autolock l(mTriggerMutex);
4060 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4061 return BAD_VALUE;
4062 }
4063 mRotateAndCropOverride = rotateAndCropValue;
4064 return OK;
4065}
4066
Emilian Peeve23f1d92021-09-20 14:56:01 -07004067status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
4068 ATRACE_CALL();
4069 Mutex::Autolock l(mTriggerMutex);
4070 mComposerOutput = composerSurfacePresent;
4071 return OK;
4072}
4073
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004074status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004075 ATRACE_CALL();
4076 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004077 if (muteMode != mCameraMute) {
4078 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004079 mCameraMuteChanged = true;
4080 }
4081 return OK;
4082}
4083
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004084nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004085 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004086 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004087 return mExpectedInflightDuration > kMinInflightDuration ?
4088 mExpectedInflightDuration : kMinInflightDuration;
4089}
4090
Emilian Peevaebbe412018-01-15 13:53:24 +00004091void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004092 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004093 if ((request == nullptr) || (halRequest == nullptr)) {
4094 ALOGE("%s: Invalid request!", __FUNCTION__);
4095 return;
4096 }
4097
4098 if (halRequest->num_physcam_settings > 0) {
4099 if (halRequest->physcam_id != nullptr) {
4100 delete [] halRequest->physcam_id;
4101 halRequest->physcam_id = nullptr;
4102 }
4103 if (halRequest->physcam_settings != nullptr) {
4104 auto it = ++(request->mSettingsList.begin());
4105 size_t i = 0;
4106 for (; it != request->mSettingsList.end(); it++, i++) {
4107 it->metadata.unlock(halRequest->physcam_settings[i]);
4108 }
4109 delete [] halRequest->physcam_settings;
4110 halRequest->physcam_settings = nullptr;
4111 }
4112 }
4113}
4114
Ravneet74cd3732022-03-30 05:33:03 +00004115status_t Camera3Device::setCameraServiceWatchdog(bool enabled) {
4116 Mutex::Autolock il(mInterfaceLock);
4117 Mutex::Autolock l(mLock);
4118
4119 if (mCameraServiceWatchdog != NULL) {
4120 mCameraServiceWatchdog->setEnabled(enabled);
4121 }
4122
4123 return OK;
4124}
4125
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08004126void Camera3Device::setStreamUseCaseOverrides(
4127 const std::vector<int64_t>& useCaseOverrides) {
4128 Mutex::Autolock il(mInterfaceLock);
4129 Mutex::Autolock l(mLock);
4130 mStreamUseCaseOverrides = useCaseOverrides;
4131}
4132
4133void Camera3Device::clearStreamUseCaseOverrides() {
4134 Mutex::Autolock il(mInterfaceLock);
4135 Mutex::Autolock l(mLock);
4136 mStreamUseCaseOverrides.clear();
4137}
4138
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004139void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4140 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004141 return;
4142 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004143
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004144 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004145 // Skip the ones that have been submitted successfully.
4146 if (nextRequest.submitted) {
4147 continue;
4148 }
4149
4150 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004151 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4152 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004153
4154 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004155 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004156 }
4157
Emilian Peevaebbe412018-01-15 13:53:24 +00004158 cleanupPhysicalSettings(captureRequest, halRequest);
4159
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004160 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004161 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004162 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4163 }
4164
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004165 // No output buffer can be returned when using HAL buffer manager
4166 if (!mUseHalBufManager) {
4167 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4168 //Buffers that failed processing could still have
4169 //valid acquire fence.
4170 int acquireFence = (*outputBuffers)[i].acquire_fence;
4171 if (0 <= acquireFence) {
4172 close(acquireFence);
4173 outputBuffers->editItemAt(i).acquire_fence = -1;
4174 }
Emilian Peevf4816702020-04-03 15:44:51 -07004175 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004176 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4177 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004178 /*timestampIncreasing*/true, std::vector<size_t> (),
4179 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004180 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004181 }
4182
4183 if (sendRequestError) {
4184 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004185 sp<NotificationListener> listener = mListener.promote();
4186 if (listener != NULL) {
4187 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004188 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004189 captureRequest->mResultExtras);
4190 }
4191 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004192
4193 // Remove yet-to-be submitted inflight request from inflightMap
4194 {
4195 sp<Camera3Device> parent = mParent.promote();
4196 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004197 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004198 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4199 if (idx >= 0) {
4200 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4201 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4202 parent->removeInFlightMapEntryLocked(idx);
4203 }
4204 }
4205 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004206 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004207
4208 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004209 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004210}
4211
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004212void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004213 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004214 // Optimized a bit for the simple steady-state case (single repeating
4215 // request), to avoid putting that request in the queue temporarily.
4216 Mutex::Autolock l(mRequestLock);
4217
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004218 assert(mNextRequests.empty());
4219
4220 NextRequest nextRequest;
4221 nextRequest.captureRequest = waitForNextRequestLocked();
4222 if (nextRequest.captureRequest == nullptr) {
4223 return;
4224 }
4225
Emilian Peevf4816702020-04-03 15:44:51 -07004226 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004227 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004228 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004229
4230 // Wait for additional requests
4231 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4232
4233 for (size_t i = 1; i < batchSize; i++) {
4234 NextRequest additionalRequest;
4235 additionalRequest.captureRequest = waitForNextRequestLocked();
4236 if (additionalRequest.captureRequest == nullptr) {
4237 break;
4238 }
4239
Emilian Peevf4816702020-04-03 15:44:51 -07004240 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004241 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004242 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004243 }
4244
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004245 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004246 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004247 mNextRequests.size(), batchSize);
4248 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004249 }
4250
4251 return;
4252}
4253
4254sp<Camera3Device::CaptureRequest>
4255 Camera3Device::RequestThread::waitForNextRequestLocked() {
4256 status_t res;
4257 sp<CaptureRequest> nextRequest;
4258
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004259 while (mRequestQueue.empty()) {
4260 if (!mRepeatingRequests.empty()) {
4261 // Always atomically enqueue all requests in a repeating request
4262 // list. Guarantees a complete in-sequence set of captures to
4263 // application.
4264 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004265 if (mFirstRepeating) {
4266 mFirstRepeating = false;
4267 } else {
4268 for (auto& request : requests) {
4269 // For repeating requests, override timestamp request using
4270 // the time a request is inserted into the request queue,
4271 // because the original repeating request will have an old
4272 // fixed timestamp.
4273 request->mRequestTimeNs = systemTime();
4274 }
4275 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004276 RequestList::const_iterator firstRequest =
4277 requests.begin();
4278 nextRequest = *firstRequest;
4279 mRequestQueue.insert(mRequestQueue.end(),
4280 ++firstRequest,
4281 requests.end());
4282 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004283
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004284 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004285
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004286 break;
4287 }
4288
Shuzhen Wangbb9b93d2022-04-07 13:22:48 -07004289 if (!mRequestClearing) {
4290 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4291 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004292
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004293 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4294 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004295 Mutex::Autolock pl(mPauseLock);
4296 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004297 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004299 if (mNotifyPipelineDrain) {
4300 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4301 mNotifyPipelineDrain = false;
4302 mStreamIdsToBeDrained.clear();
4303 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004304 // Let the tracker know
4305 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4306 if (statusTracker != 0) {
4307 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4308 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004309 sp<Camera3Device> parent = mParent.promote();
4310 if (parent != nullptr) {
4311 parent->mRequestBufferSM.onRequestThreadPaused();
4312 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004313 }
Shuzhen Wangb8696c02022-05-20 13:31:02 -07004314 mRequestClearing = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004315 // Stop waiting for now and let thread management happen
4316 return NULL;
4317 }
4318 }
4319
4320 if (nextRequest == NULL) {
4321 // Don't have a repeating request already in hand, so queue
4322 // must have an entry now.
4323 RequestList::iterator firstRequest =
4324 mRequestQueue.begin();
4325 nextRequest = *firstRequest;
4326 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004327 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4328 sp<NotificationListener> listener = mListener.promote();
4329 if (listener != NULL) {
4330 listener->notifyRequestQueueEmpty();
4331 }
4332 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 }
4334
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004335 // In case we've been unpaused by setPaused clearing mDoPause, need to
4336 // update internal pause state (capture/setRepeatingRequest unpause
4337 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004339 if (mPaused) {
4340 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4341 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4342 if (statusTracker != 0) {
4343 statusTracker->markComponentActive(mStatusId);
4344 }
4345 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004346 mPaused = false;
4347
4348 // Check if we've reconfigured since last time, and reset the preview
4349 // request if so. Can't use 'NULL request == repeat' across configure calls.
4350 if (mReconfigured) {
4351 mPrevRequest.clear();
4352 mReconfigured = false;
4353 }
4354
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004355 if (nextRequest != NULL) {
4356 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004357 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4358 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004359
4360 // Since RequestThread::clear() removes buffers from the input stream,
4361 // get the right buffer here before unlocking mRequestLock
4362 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004363 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4364 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004365 if (res != OK) {
4366 // Can't get input buffer from gralloc queue - this could be due to
4367 // disconnected queue or other producer misbehavior, so not a fatal
4368 // error
4369 ALOGE("%s: Can't get input buffer, skipping request:"
4370 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004371
4372 sp<NotificationListener> listener = mListener.promote();
4373 if (listener != NULL) {
4374 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004375 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004376 nextRequest->mResultExtras);
4377 }
4378 return NULL;
4379 }
4380 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004381 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004382
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004383 return nextRequest;
4384}
4385
4386bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004387 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004388 status_t res;
4389 Mutex::Autolock l(mPauseLock);
4390 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004391 if (mPaused == false) {
4392 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004393 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004394 if (mNotifyPipelineDrain) {
4395 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4396 mNotifyPipelineDrain = false;
4397 mStreamIdsToBeDrained.clear();
4398 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004399 // Let the tracker know
4400 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4401 if (statusTracker != 0) {
4402 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4403 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004404 sp<Camera3Device> parent = mParent.promote();
4405 if (parent != nullptr) {
4406 parent->mRequestBufferSM.onRequestThreadPaused();
4407 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004408 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004409
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004410 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004411 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004412 return true;
4413 }
4414 }
4415 // We don't set mPaused to false here, because waitForNextRequest needs
4416 // to further manage the paused state in case of starvation.
4417 return false;
4418}
4419
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004420void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004421 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004422 // With work to do, mark thread as unpaused.
4423 // If paused by request (setPaused), don't resume, to avoid
4424 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004425 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004426 Mutex::Autolock p(mPauseLock);
4427 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004428 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4429 if (mPaused) {
4430 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4431 if (statusTracker != 0) {
4432 statusTracker->markComponentActive(mStatusId);
4433 }
4434 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004435 mPaused = false;
4436 }
4437}
4438
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004439void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4440 sp<Camera3Device> parent = mParent.promote();
4441 if (parent != NULL) {
4442 va_list args;
4443 va_start(args, fmt);
4444
4445 parent->setErrorStateV(fmt, args);
4446
4447 va_end(args);
4448 }
4449}
4450
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004451status_t Camera3Device::RequestThread::insertTriggers(
4452 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004453 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004454 Mutex::Autolock al(mTriggerMutex);
4455
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004456 sp<Camera3Device> parent = mParent.promote();
4457 if (parent == NULL) {
4458 CLOGE("RequestThread: Parent is gone");
4459 return DEAD_OBJECT;
4460 }
4461
Emilian Peevaebbe412018-01-15 13:53:24 +00004462 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004463 size_t count = mTriggerMap.size();
4464
4465 for (size_t i = 0; i < count; ++i) {
4466 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004467 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004468
4469 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4470 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4471 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004472 if (isAeTrigger) {
4473 request->mResultExtras.precaptureTriggerId = triggerId;
4474 mCurrentPreCaptureTriggerId = triggerId;
4475 } else {
4476 request->mResultExtras.afTriggerId = triggerId;
4477 mCurrentAfTriggerId = triggerId;
4478 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004479 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004480 }
4481
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004482 camera_metadata_entry entry = metadata.find(tag);
4483
4484 if (entry.count > 0) {
4485 /**
4486 * Already has an entry for this trigger in the request.
4487 * Rewrite it with our requested trigger value.
4488 */
4489 RequestTrigger oldTrigger = trigger;
4490
4491 oldTrigger.entryValue = entry.data.u8[0];
4492
4493 mTriggerReplacedMap.add(tag, oldTrigger);
4494 } else {
4495 /**
4496 * More typical, no trigger entry, so we just add it
4497 */
4498 mTriggerRemovedMap.add(tag, trigger);
4499 }
4500
4501 status_t res;
4502
4503 switch (trigger.getTagType()) {
4504 case TYPE_BYTE: {
4505 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4506 res = metadata.update(tag,
4507 &entryValue,
4508 /*count*/1);
4509 break;
4510 }
4511 case TYPE_INT32:
4512 res = metadata.update(tag,
4513 &trigger.entryValue,
4514 /*count*/1);
4515 break;
4516 default:
4517 ALOGE("%s: Type not supported: 0x%x",
4518 __FUNCTION__,
4519 trigger.getTagType());
4520 return INVALID_OPERATION;
4521 }
4522
4523 if (res != OK) {
4524 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4525 ", value %d", __FUNCTION__, trigger.getTagName(),
4526 trigger.entryValue);
4527 return res;
4528 }
4529
4530 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4531 trigger.getTagName(),
4532 trigger.entryValue);
4533 }
4534
4535 mTriggerMap.clear();
4536
4537 return count;
4538}
4539
4540status_t Camera3Device::RequestThread::removeTriggers(
4541 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004542 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004543 Mutex::Autolock al(mTriggerMutex);
4544
Emilian Peevaebbe412018-01-15 13:53:24 +00004545 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004546
4547 /**
4548 * Replace all old entries with their old values.
4549 */
4550 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4551 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4552
4553 status_t res;
4554
4555 uint32_t tag = trigger.metadataTag;
4556 switch (trigger.getTagType()) {
4557 case TYPE_BYTE: {
4558 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4559 res = metadata.update(tag,
4560 &entryValue,
4561 /*count*/1);
4562 break;
4563 }
4564 case TYPE_INT32:
4565 res = metadata.update(tag,
4566 &trigger.entryValue,
4567 /*count*/1);
4568 break;
4569 default:
4570 ALOGE("%s: Type not supported: 0x%x",
4571 __FUNCTION__,
4572 trigger.getTagType());
4573 return INVALID_OPERATION;
4574 }
4575
4576 if (res != OK) {
4577 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4578 ", trigger value %d", __FUNCTION__,
4579 trigger.getTagName(), trigger.entryValue);
4580 return res;
4581 }
4582 }
4583 mTriggerReplacedMap.clear();
4584
4585 /**
4586 * Remove all new entries.
4587 */
4588 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4589 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4590 status_t res = metadata.erase(trigger.metadataTag);
4591
4592 if (res != OK) {
4593 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4594 ", trigger value %d", __FUNCTION__,
4595 trigger.getTagName(), trigger.entryValue);
4596 return res;
4597 }
4598 }
4599 mTriggerRemovedMap.clear();
4600
4601 return OK;
4602}
4603
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004604status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004605 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004606 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004607 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004608 status_t res;
4609
Emilian Peevaebbe412018-01-15 13:53:24 +00004610 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004611
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004612 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004613 // exists
4614 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4615 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4616 if (afTrigger.count > 0 &&
4617 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4618 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004619 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004620 if (res != OK) return res;
4621 }
4622
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004623 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004624 // if none already exists
4625 camera_metadata_entry pcTrigger =
4626 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4627 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4628 if (pcTrigger.count > 0 &&
4629 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4630 pcId.count == 0) {
4631 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004632 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004633 if (res != OK) return res;
4634 }
4635
4636 return OK;
4637}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004638
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004639bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4640 const sp<CaptureRequest> &request) {
4641 ATRACE_CALL();
4642
Austin Borger3560b7e2022-10-27 12:20:29 -07004643 if (mOverrideToPortrait) {
4644 Mutex::Autolock l(mTriggerMutex);
4645 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4646 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4647 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4648 &rotateAndCrop_u8, 1);
4649 return true;
4650 }
4651
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004652 if (request->mRotateAndCropAuto) {
4653 Mutex::Autolock l(mTriggerMutex);
4654 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4655
4656 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4657 if (rotateAndCropEntry.count > 0) {
4658 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4659 return false;
4660 } else {
4661 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4662 return true;
4663 }
4664 } else {
4665 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4666 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4667 &rotateAndCrop_u8, 1);
4668 return true;
4669 }
4670 }
4671 return false;
4672}
4673
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004674bool Camera3Device::RequestThread::overrideTestPattern(
4675 const sp<CaptureRequest> &request) {
4676 ATRACE_CALL();
4677
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004678 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004679
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004680 Mutex::Autolock l(mTriggerMutex);
4681
4682 bool changed = false;
4683
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004684 // For a multi-camera, the physical cameras support the same set of
4685 // test pattern modes as the logical camera.
4686 for (auto& settings : request->mSettingsList) {
4687 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004688
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004689 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4690 int32_t testPatternData[4] = {
4691 settings.mOriginalTestPatternData[0],
4692 settings.mOriginalTestPatternData[1],
4693 settings.mOriginalTestPatternData[2],
4694 settings.mOriginalTestPatternData[3]
4695 };
4696 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4697 testPatternMode = mCameraMute;
4698 testPatternData[0] = 0;
4699 testPatternData[1] = 0;
4700 testPatternData[2] = 0;
4701 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004702 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004703
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004704 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4705 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4706 if (testPatternEntry.count > 0) {
4707 if (testPatternEntry.data.i32[0] != testPatternMode) {
4708 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004709 changed = true;
4710 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004711 } else if (supportTestPatternModeKey) {
4712 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4713 &testPatternMode, 1);
4714 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004715 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004716
4717 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4718 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4719 if (testPatternColor.count >= 4) {
4720 for (size_t i = 0; i < 4; i++) {
4721 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4722 testPatternColor.data.i32[i] = testPatternData[i];
4723 changed = true;
4724 }
4725 }
4726 } else if (supportTestPatternDataKey) {
4727 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4728 testPatternData, 4);
4729 changed = true;
4730 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004731 }
4732
4733 return changed;
4734}
4735
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004736status_t Camera3Device::RequestThread::setHalInterface(
4737 sp<HalInterface> newHalInterface) {
4738 if (newHalInterface.get() == nullptr) {
4739 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4740 return DEAD_OBJECT;
4741 }
4742
4743 mInterface = newHalInterface;
4744
4745 return OK;
4746}
4747
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004748/**
4749 * PreparerThread inner class methods
4750 */
4751
4752Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004753 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004754 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004755}
4756
4757Camera3Device::PreparerThread::~PreparerThread() {
4758 Thread::requestExitAndWait();
4759 if (mCurrentStream != nullptr) {
4760 mCurrentStream->cancelPrepare();
4761 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4762 mCurrentStream.clear();
4763 }
4764 clear();
4765}
4766
Ruben Brunkc78ac262015-08-13 17:58:46 -07004767status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004768 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004769 status_t res;
4770
4771 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004772 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004773
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004774 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004775 if (res == OK) {
4776 // No preparation needed, fire listener right off
4777 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004778 if (listener != NULL) {
4779 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004780 }
4781 return OK;
4782 } else if (res != NOT_ENOUGH_DATA) {
4783 return res;
4784 }
4785
4786 // Need to prepare, start up thread if necessary
4787 if (!mActive) {
4788 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4789 // isn't running
4790 Thread::requestExitAndWait();
4791 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4792 if (res != OK) {
4793 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004794 if (listener != NULL) {
4795 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004796 }
4797 return res;
4798 }
4799 mCancelNow = false;
4800 mActive = true;
4801 ALOGV("%s: Preparer stream started", __FUNCTION__);
4802 }
4803
4804 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004805 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004806 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4807
4808 return OK;
4809}
4810
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004811void Camera3Device::PreparerThread::pause() {
4812 ATRACE_CALL();
4813
4814 Mutex::Autolock l(mLock);
4815
4816 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4817 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4818 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4819 int currentMaxCount = mCurrentMaxCount;
4820 mPendingStreams.clear();
4821 mCancelNow = true;
4822 while (mActive) {
4823 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4824 if (res == TIMED_OUT) {
4825 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4826 return;
4827 } else if (res != OK) {
4828 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4829 return;
4830 }
4831 }
4832
4833 //Check whether the prepare thread was able to complete the current
4834 //stream. In case work is still pending emplace it along with the rest
4835 //of the streams in the pending list.
4836 if (currentStream != nullptr) {
4837 if (!mCurrentPrepareComplete) {
4838 pendingStreams.emplace(currentMaxCount, currentStream);
4839 }
4840 }
4841
4842 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4843 for (const auto& it : mPendingStreams) {
4844 it.second->cancelPrepare();
4845 }
4846}
4847
4848status_t Camera3Device::PreparerThread::resume() {
4849 ATRACE_CALL();
4850 status_t res;
4851
4852 Mutex::Autolock l(mLock);
4853 sp<NotificationListener> listener = mListener.promote();
4854
4855 if (mActive) {
4856 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4857 return NO_INIT;
4858 }
4859
4860 auto it = mPendingStreams.begin();
4861 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004862 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004863 if (res == OK) {
4864 if (listener != NULL) {
4865 listener->notifyPrepared(it->second->getId());
4866 }
4867 it = mPendingStreams.erase(it);
4868 } else if (res != NOT_ENOUGH_DATA) {
4869 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4870 res, strerror(-res));
4871 it = mPendingStreams.erase(it);
4872 } else {
4873 it++;
4874 }
4875 }
4876
4877 if (mPendingStreams.empty()) {
4878 return OK;
4879 }
4880
4881 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4882 if (res != OK) {
4883 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4884 __FUNCTION__, res, strerror(-res));
4885 return res;
4886 }
4887 mCancelNow = false;
4888 mActive = true;
4889 ALOGV("%s: Preparer stream started", __FUNCTION__);
4890
4891 return OK;
4892}
4893
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004894status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004895 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004896 Mutex::Autolock l(mLock);
4897
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004898 for (const auto& it : mPendingStreams) {
4899 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004900 }
4901 mPendingStreams.clear();
4902 mCancelNow = true;
4903
4904 return OK;
4905}
4906
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004907void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004908 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004909 Mutex::Autolock l(mLock);
4910 mListener = listener;
4911}
4912
4913bool Camera3Device::PreparerThread::threadLoop() {
4914 status_t res;
4915 {
4916 Mutex::Autolock l(mLock);
4917 if (mCurrentStream == nullptr) {
4918 // End thread if done with work
4919 if (mPendingStreams.empty()) {
4920 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4921 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4922 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4923 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004924 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004925 return false;
4926 }
4927
4928 // Get next stream to prepare
4929 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004930 mCurrentStream = it->second;
4931 mCurrentMaxCount = it->first;
4932 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004933 mPendingStreams.erase(it);
4934 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4935 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4936 } else if (mCancelNow) {
4937 mCurrentStream->cancelPrepare();
4938 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4939 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4940 mCurrentStream.clear();
4941 mCancelNow = false;
4942 return true;
4943 }
4944 }
4945
4946 res = mCurrentStream->prepareNextBuffer();
4947 if (res == NOT_ENOUGH_DATA) return true;
4948 if (res != OK) {
4949 // Something bad happened; try to recover by cancelling prepare and
4950 // signalling listener anyway
4951 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4952 mCurrentStream->getId(), res, strerror(-res));
4953 mCurrentStream->cancelPrepare();
4954 }
4955
4956 // This stream has finished, notify listener
4957 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004958 sp<NotificationListener> listener = mListener.promote();
4959 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004960 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4961 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004962 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004963 }
4964
4965 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4966 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004967 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004968
4969 return true;
4970}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004971
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004972status_t Camera3Device::RequestBufferStateMachine::initialize(
4973 sp<camera3::StatusTracker> statusTracker) {
4974 if (statusTracker == nullptr) {
4975 ALOGE("%s: statusTracker is null", __FUNCTION__);
4976 return BAD_VALUE;
4977 }
4978
4979 std::lock_guard<std::mutex> lock(mLock);
4980 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004981 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004982 return OK;
4983}
4984
4985bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4986 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004987 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004988 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004989 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004990 return true;
4991 }
4992 return false;
4993}
4994
4995void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4996 std::lock_guard<std::mutex> lock(mLock);
4997 if (!mRequestBufferOngoing) {
4998 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4999 return;
5000 }
5001 mRequestBufferOngoing = false;
5002 if (mStatus == RB_STATUS_PENDING_STOP) {
5003 checkSwitchToStopLocked();
5004 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005005 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005006}
5007
5008void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5009 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005010 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005011 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005012 return;
5013}
5014
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005015void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005016 std::lock_guard<std::mutex> lock(mLock);
5017 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005018 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5019 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005020 mInflightMapEmpty = false;
5021 if (mStatus == RB_STATUS_STOPPED) {
5022 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005023 }
5024 return;
5025}
5026
5027void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5028 std::lock_guard<std::mutex> lock(mLock);
5029 mRequestThreadPaused = true;
5030 if (mStatus == RB_STATUS_PENDING_STOP) {
5031 checkSwitchToStopLocked();
5032 }
5033 return;
5034}
5035
5036void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5037 std::lock_guard<std::mutex> lock(mLock);
5038 mInflightMapEmpty = true;
5039 if (mStatus == RB_STATUS_PENDING_STOP) {
5040 checkSwitchToStopLocked();
5041 }
5042 return;
5043}
5044
5045void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5046 std::lock_guard<std::mutex> lock(mLock);
5047 if (!checkSwitchToStopLocked()) {
5048 mStatus = RB_STATUS_PENDING_STOP;
5049 }
5050 return;
5051}
5052
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005053bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5054 std::lock_guard<std::mutex> lock(mLock);
5055 if (mRequestBufferOngoing) {
5056 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5057 __FUNCTION__);
5058 return false;
5059 }
5060 mSwitchedToOffline = true;
5061 mInflightMapEmpty = true;
5062 mRequestThreadPaused = true;
5063 mStatus = RB_STATUS_STOPPED;
5064 return true;
5065}
5066
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005067void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5068 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5069 if (statusTracker != nullptr) {
5070 if (active) {
5071 statusTracker->markComponentActive(mRequestBufferStatusId);
5072 } else {
5073 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5074 }
5075 }
5076}
5077
5078bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5079 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5080 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005081 return true;
5082 }
5083 return false;
5084}
5085
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005086bool Camera3Device::startRequestBuffer() {
5087 return mRequestBufferSM.startRequestBuffer();
5088}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005089
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005090void Camera3Device::endRequestBuffer() {
5091 mRequestBufferSM.endRequestBuffer();
5092}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005093
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005094nsecs_t Camera3Device::getWaitDuration() {
5095 return kBaseGetBufferWait + getExpectedInFlightDuration();
5096}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005097
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005098void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5099 mInterface->getInflightBufferKeys(out);
5100}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005101
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005102void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5103 mInterface->getInflightRequestBufferKeys(out);
5104}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005105
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005106std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5107 std::vector<sp<Camera3StreamInterface>> ret;
5108 bool hasInputStream = mInputStream != nullptr;
5109 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5110 if (hasInputStream) {
5111 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005112 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005113 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5114 ret.push_back(mOutputStreams[i]);
5115 }
5116 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5117 ret.push_back(mDeletedStreams[i]);
5118 }
5119 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005120}
5121
Emilian Peevcc0b7952020-01-07 13:54:47 -08005122void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5123 ATRACE_CALL();
5124
5125 if (offlineStreamIds == nullptr) {
5126 return;
5127 }
5128
5129 Mutex::Autolock il(mInterfaceLock);
5130
5131 auto streamIds = mOutputStreams.getStreamIds();
5132 bool hasInputStream = mInputStream != nullptr;
5133 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5134 offlineStreamIds->push_back(mInputStream->getId());
5135 }
5136
5137 for (const auto & streamId : streamIds) {
5138 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5139 // Streams that use the camera buffer manager are currently not supported in
5140 // offline mode
5141 if (stream->getOfflineProcessingSupport() &&
5142 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5143 offlineStreamIds->push_back(streamId);
5144 }
5145 }
5146}
5147
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005148status_t Camera3Device::setRotateAndCropAutoBehavior(
5149 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5150 ATRACE_CALL();
5151 Mutex::Autolock il(mInterfaceLock);
5152 Mutex::Autolock l(mLock);
5153 if (mRequestThread == nullptr) {
5154 return INVALID_OPERATION;
5155 }
5156 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5157}
5158
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005159bool Camera3Device::supportsCameraMute() {
5160 Mutex::Autolock il(mInterfaceLock);
5161 Mutex::Autolock l(mLock);
5162
5163 return mSupportCameraMute;
5164}
5165
5166status_t Camera3Device::setCameraMute(bool enabled) {
5167 ATRACE_CALL();
5168 Mutex::Autolock il(mInterfaceLock);
5169 Mutex::Autolock l(mLock);
5170
5171 if (mRequestThread == nullptr || !mSupportCameraMute) {
5172 return INVALID_OPERATION;
5173 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005174 int32_t muteMode =
5175 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5176 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5177 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5178 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005179}
5180
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005181status_t Camera3Device::injectCamera(const String8& injectedCamId,
5182 sp<CameraProviderManager> manager) {
5183 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5184 ATRACE_CALL();
5185 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005186 // When the camera device is active, injectCamera() and stopInjection() will call
5187 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5188 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5189 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5190 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5191 // waitUntilStateThenRelock().
5192 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005193
5194 status_t res = NO_ERROR;
5195 if (mInjectionMethods->isInjecting()) {
5196 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5197 return OK;
5198 } else {
5199 res = mInjectionMethods->stopInjection();
5200 if (res != OK) {
5201 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5202 __FUNCTION__, res);
5203 return res;
5204 }
5205 }
5206 }
5207
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005208 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005209 if (res != OK) {
5210 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5211 __FUNCTION__, res);
5212 return res;
5213 }
5214
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005215 // When the second display of android is cast to the remote device, and the opened camera is
5216 // also cast to the second display, in this case, because the camera has configured the streams
5217 // at this time, we can directly call injectCamera() to replace the internal camera with
5218 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005219 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5220 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5221
5222 camera3::camera_stream_configuration injectionConfig;
5223 std::vector<uint32_t> injectionBufferSizes;
5224 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5225 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5226 || injectionBufferSizes.size() <= 0) {
5227 ALOGE("Failed to inject camera due to abandoned configuration! "
5228 "mOperatingMode: %d injectionConfig.num_streams: %d "
5229 "injectionBufferSizes.size(): %zu", mOperatingMode,
5230 injectionConfig.num_streams, injectionBufferSizes.size());
5231 return DEAD_OBJECT;
5232 }
5233
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005234 res = mInjectionMethods->injectCamera(
5235 injectionConfig, injectionBufferSizes);
5236 if (res != OK) {
5237 ALOGE("Can't finish inject camera process!");
5238 return res;
5239 }
5240 }
5241
5242 return OK;
5243}
5244
5245status_t Camera3Device::stopInjection() {
5246 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5247 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005248 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005249 return mInjectionMethods->stopInjection();
5250}
5251
Shuzhen Wangabe5ea12022-12-15 22:38:07 -08005252void Camera3Device::overrideStreamUseCaseLocked() {
5253 if (mStreamUseCaseOverrides.size() == 0) {
5254 return;
5255 }
5256
5257 // Start from an array of indexes in mStreamUseCaseOverrides, and sort them
5258 // based first on size, and second on formats of [JPEG, RAW, YUV, PRIV].
5259 std::vector<int> outputStreamsIndices(mOutputStreams.size());
5260 for (size_t i = 0; i < outputStreamsIndices.size(); i++) {
5261 outputStreamsIndices[i] = i;
5262 }
5263
5264 std::sort(outputStreamsIndices.begin(), outputStreamsIndices.end(),
5265 [&](int a, int b) -> bool {
5266
5267 auto formatScore = [](int format) {
5268 switch (format) {
5269 case HAL_PIXEL_FORMAT_BLOB:
5270 return 4;
5271 case HAL_PIXEL_FORMAT_RAW16:
5272 case HAL_PIXEL_FORMAT_RAW10:
5273 case HAL_PIXEL_FORMAT_RAW12:
5274 return 3;
5275 case HAL_PIXEL_FORMAT_YCBCR_420_888:
5276 return 2;
5277 case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
5278 return 1;
5279 default:
5280 return 0;
5281 }
5282 };
5283
5284 int sizeA = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5285 int sizeB = mOutputStreams[a]->getWidth() * mOutputStreams[a]->getHeight();
5286 int formatAScore = formatScore(mOutputStreams[a]->getFormat());
5287 int formatBScore = formatScore(mOutputStreams[b]->getFormat());
5288 if (sizeA > sizeB ||
5289 (sizeA == sizeB && formatAScore >= formatBScore)) {
5290 return true;
5291 } else {
5292 return false;
5293 }
5294 });
5295
5296 size_t overlapSize = std::min(mStreamUseCaseOverrides.size(), mOutputStreams.size());
5297 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5298 mOutputStreams[outputStreamsIndices[i]]->setStreamUseCase(
5299 mStreamUseCaseOverrides[std::min(i, overlapSize-1)]);
5300 }
5301}
5302
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005303}; // namespace android