blob: e4338b9c3fa92697cccce81bab315d1965e5cc09 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Cliff Wuc2ad9c82021-04-21 00:58:58 +080052#include <android/hardware/camera/device/3.7/ICameraInjectionSession.h>
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080053#include <android/hardware/camera2/ICameraDeviceUser.h>
54
Igor Murashkinff3e31d2013-10-23 16:40:06 -070055#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070056#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070057#include "device3/Camera3Device.h"
58#include "device3/Camera3OutputStream.h"
59#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040060#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070061#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080064#include "utils/SessionConfigurationUtils.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070065#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070066#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067
Jayant Chowdhary0bd38522021-11-05 17:49:27 -070068#include "../common/hidl/HidlProviderInfo.h"
69
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080070#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080071#include <tuple>
72
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080073using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074using namespace android::hardware::camera;
75using namespace android::hardware::camera::device::V3_2;
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080076using android::hardware::camera::metadata::V3_6::CameraMetadataEnumAndroidSensorPixelMode;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080077
78namespace android {
79
Emilian Peev5104fe92021-10-21 14:27:09 -070080Camera3Device::Camera3Device(const String8 &id, bool overrideForPerfClass, bool legacyClient):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080081 mId(id),
Emilian Peev5104fe92021-10-21 14:27:09 -070082 mLegacyClient(legacyClient),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080083 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070084 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070085 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070086 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070087 mUsePartialResult(false),
88 mNumPartialResults(1),
Shuzhen Wange4208922022-02-01 16:52:48 -080089 mDeviceTimeBaseIsRealtime(false),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080090 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070091 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070092 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070093 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070094 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070095 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070096 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000097 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010098 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070099 mLastTemplateId(-1),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700100 mNeedFixupMonochromeTags(false),
101 mOverrideForPerfClass(overrideForPerfClass)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102{
103 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800105}
106
107Camera3Device::~Camera3Device()
108{
109 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700111 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800112}
113
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800115 return mId;
116}
117
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800118status_t Camera3Device::initializeCommonLocked() {
119
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700120 /** Start up status tracker thread */
121 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700123 if (res != OK) {
124 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
125 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800126 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700127 mStatusTracker.clear();
128 return res;
129 }
130
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700131 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700132 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700133
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700134 if (mUseHalBufManager) {
135 res = mRequestBufferSM.initialize(mStatusTracker);
136 if (res != OK) {
137 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
138 strerror(-res), res);
139 mInterface->close();
140 mStatusTracker.clear();
141 return res;
142 }
143 }
144
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800145 /** Create buffer manager */
146 mBufferManager = new Camera3BufferManager();
147
148 Vector<int32_t> sessionParamKeys;
149 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
150 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
151 if (sessionKeysEntry.count > 0) {
152 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
153 }
154
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700155 camera_metadata_entry_t availableTestPatternModes = mDeviceInfo.find(
156 ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES);
157 for (size_t i = 0; i < availableTestPatternModes.count; i++) {
158 if (availableTestPatternModes.data.i32[i] ==
159 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
160 mSupportCameraMute = true;
161 mSupportTestPatternSolidColor = true;
162 break;
163 } else if (availableTestPatternModes.data.i32[i] ==
164 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
165 mSupportCameraMute = true;
166 mSupportTestPatternSolidColor = false;
167 }
168 }
169
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700170 /** Start up request queue thread */
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800171 mRequestThread = createNewRequestThread(
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -0700172 this, mStatusTracker, mInterface, sessionParamKeys,
173 mUseHalBufManager, mSupportCameraMute);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800174 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800175 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700176 SET_ERR_L("Unable to start request queue thread: %s (%d)",
177 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800178 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800179 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800180 return res;
181 }
182
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700183 mPreparerThread = new PreparerThread();
184
Ruben Brunk183f0562015-08-12 12:55:02 -0700185 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800186 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400187 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700188 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700189 mPauseStateNotify = false;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800190 mIsInputStreamMultiResolution = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800191
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800192 // Measure the clock domain offset between camera and video/hw_composer
Shuzhen Wange4208922022-02-01 16:52:48 -0800193 mTimestampOffset = getMonoToBoottimeOffset();
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800194 camera_metadata_entry timestampSource =
195 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
196 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
197 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800198 mDeviceTimeBaseIsRealtime = true;
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800199 }
200
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700201 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100202 camera_metadata_entry partialResultsCount =
203 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
204 if (partialResultsCount.count > 0) {
205 mNumPartialResults = partialResultsCount.data.i32[0];
206 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700207 }
208
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800209 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
210 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700211 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700212 if (res != OK) {
213 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
214 return res;
215 }
216 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800217
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800218 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800219 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800220
Jayant Chowdhary9255ce02021-07-15 11:18:17 -0700221 if (SessionConfigurationUtils::isUltraHighResolutionSensor(mDeviceInfo)) {
222 mUHRCropAndMeteringRegionMappers[mId.c_str()] =
223 UHRCropAndMeteringRegionMapper(mDeviceInfo, usePrecorrectArray);
224 }
225
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800226 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
227 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
228 }
229
Jayant Chowdhary22441f32021-12-26 18:35:41 -0800230 // Hidl/AidlCamera3DeviceInjectionMethods
231 mInjectionMethods = createCamera3DeviceInjectionMethods(this);
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800232
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800233 return OK;
234}
235
236status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700237 return disconnectImpl();
238}
239
240status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800241 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700242 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800243
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700244 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700245 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700246 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800247 Mutex::Autolock il(mInterfaceLock);
248 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
249 {
250 Mutex::Autolock l(mLock);
251 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700252
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800253 if (mStatus == STATUS_ACTIVE ||
254 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
255 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800257 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700258 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800259 } else {
260 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
261 if (res != OK) {
262 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
263 maxExpectedDuration);
264 // Continue to close device even in case of error
265 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700266 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700267 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800268
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800269 if (mStatus == STATUS_ERROR) {
270 CLOGE("Shutting down in an error state");
271 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800273 if (mStatusTracker != NULL) {
274 mStatusTracker->requestExit();
275 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700276
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800277 if (mRequestThread != NULL) {
278 mRequestThread->requestExit();
279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700280
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800281 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
282 for (size_t i = 0; i < mOutputStreams.size(); i++) {
283 streams.push_back(mOutputStreams[i]);
284 }
285 if (mInputStream != nullptr) {
286 streams.push_back(mInputStream);
287 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700288 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700289 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800290 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
291 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700292 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
293 // HAL may be in a bad state, so waiting for request thread
294 // (which may be stuck in the HAL processCaptureRequest call)
295 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800296 // give up mInterfaceLock here and then lock it again. Could this lead
297 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 mRequestThread->join();
299 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700300 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800301 Mutex::Autolock il(mInterfaceLock);
302 if (mStatusTracker != NULL) {
303 mStatusTracker->join();
304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305
Cliff Wuc2ad9c82021-04-21 00:58:58 +0800306 if (mInjectionMethods->isInjecting()) {
307 mInjectionMethods->stopInjection();
308 }
309
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800310 HalInterface* interface;
311 {
312 Mutex::Autolock l(mLock);
313 mRequestThread.clear();
314 Mutex::Autolock stLock(mTrackerLock);
315 mStatusTracker.clear();
316 interface = mInterface.get();
317 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700318
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800319 // Call close without internal mutex held, as the HAL close may need to
320 // wait on assorted callbacks,etc, to complete before it can return.
321 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700322
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800323 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800324
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800325 {
326 Mutex::Autolock l(mLock);
327 mInterface->clear();
328 mOutputStreams.clear();
329 mInputStream.clear();
330 mDeletedStreams.clear();
331 mBufferManager.clear();
332 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
333 }
334
335 for (auto& weakStream : streams) {
336 sp<Camera3StreamInterface> stream = weakStream.promote();
337 if (stream != nullptr) {
338 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
339 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
340 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700341 }
342 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700343 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700344 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800345}
346
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700347// For dumping/debugging only -
348// try to acquire a lock a few times, eventually give up to proceed with
349// debug/dump operations
350bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
351 bool gotLock = false;
352 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
353 if (lock.tryLock() == NO_ERROR) {
354 gotLock = true;
355 break;
356 } else {
357 usleep(kDumpSleepDuration);
358 }
359 }
360 return gotLock;
361}
362
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800363nsecs_t Camera3Device::getMonoToBoottimeOffset() {
364 // try three times to get the clock offset, choose the one
365 // with the minimum gap in measurements.
366 const int tries = 3;
367 nsecs_t bestGap, measured;
368 for (int i = 0; i < tries; ++i) {
369 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
370 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
371 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
372 const nsecs_t gap = tmono2 - tmono;
373 if (i == 0 || gap < bestGap) {
374 bestGap = gap;
375 measured = tbase - ((tmono + tmono2) >> 1);
376 }
377 }
378 return measured;
379}
380
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800381ssize_t Camera3Device::getJpegBufferSize(const CameraMetadata &info, uint32_t width,
382 uint32_t height) const {
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700383 // Get max jpeg size (area-wise) for default sensor pixel mode
384 camera3::Size maxDefaultJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800385 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700386 /*isUltraHighResolutionSensor*/false);
387 // Get max jpeg size (area-wise) for max resolution sensor pixel mode / 0 if
388 // not ultra high res sensor
389 camera3::Size uhrMaxJpegResolution =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800390 SessionConfigurationUtils::getMaxJpegResolution(info,
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700391 /*isUltraHighResolution*/true);
392 if (maxDefaultJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800393 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
394 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700395 return BAD_VALUE;
396 }
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700397 bool useMaxSensorPixelModeThreshold = false;
398 if (uhrMaxJpegResolution.width != 0 &&
399 width * height > maxDefaultJpegResolution.width * maxDefaultJpegResolution.height) {
400 // Use the ultra high res max jpeg size and max jpeg buffer size
401 useMaxSensorPixelModeThreshold = true;
402 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700403
Zhijun Hef7da0962014-04-24 13:27:56 -0700404 // Get max jpeg buffer size
405 ssize_t maxJpegBufferSize = 0;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800406 camera_metadata_ro_entry jpegBufMaxSize = info.find(ANDROID_JPEG_MAX_SIZE);
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700407 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800408 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
409 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700410 return BAD_VALUE;
411 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700412 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700413
414 camera3::Size chosenMaxJpegResolution = maxDefaultJpegResolution;
415 if (useMaxSensorPixelModeThreshold) {
416 maxJpegBufferSize =
417 SessionConfigurationUtils::getUHRMaxJpegBufferSize(uhrMaxJpegResolution,
418 maxDefaultJpegResolution, maxJpegBufferSize);
419 chosenMaxJpegResolution = uhrMaxJpegResolution;
420 }
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800421 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700422
423 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700424 float scaleFactor = ((float) (width * height)) /
Jayant Chowdharycd3d36b2021-07-10 10:53:53 -0700425 (chosenMaxJpegResolution.width * chosenMaxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800426 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
427 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700428 if (jpegBufferSize > maxJpegBufferSize) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800429 ALOGI("%s: jpeg buffer size calculated is > maxJpeg bufferSize(%zd), clamping",
430 __FUNCTION__, maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700431 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700432 }
Zhijun Hef7da0962014-04-24 13:27:56 -0700433 return jpegBufferSize;
434}
435
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800436ssize_t Camera3Device::getPointCloudBufferSize(const CameraMetadata &info) const {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700437 const int FLOATS_PER_POINT=4;
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800438 camera_metadata_ro_entry maxPointCount = info.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700439 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800440 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
441 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700442 return BAD_VALUE;
443 }
444 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
445 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
446 return maxBytesForPointCloud;
447}
448
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800449ssize_t Camera3Device::getRawOpaqueBufferSize(const CameraMetadata &info, int32_t width,
450 int32_t height, bool maxResolution) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800451 const int PER_CONFIGURATION_SIZE = 3;
452 const int WIDTH_OFFSET = 0;
453 const int HEIGHT_OFFSET = 1;
454 const int SIZE_OFFSET = 2;
455 camera_metadata_ro_entry rawOpaqueSizes =
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -0800456 info.find(
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800457 camera3::SessionConfigurationUtils::getAppropriateModeTag(
458 ANDROID_SENSOR_OPAQUE_RAW_SIZE,
459 maxResolution));
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800460 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800461 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800462 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
463 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800464 return BAD_VALUE;
465 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700466
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800467 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
468 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
469 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
470 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
471 }
472 }
473
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800474 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
475 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800476 return BAD_VALUE;
477}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700478
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800479status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
480 ATRACE_CALL();
481 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700482
483 // Try to lock, but continue in case of failure (to avoid blocking in
484 // deadlocks)
485 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
486 bool gotLock = tryLockSpinRightRound(mLock);
487
488 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800489 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
490 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700491 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800492 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
493 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700494
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800495 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700496
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800497 String16 templatesOption("-t");
498 int n = args.size();
499 for (int i = 0; i < n; i++) {
500 if (args[i] == templatesOption) {
501 dumpTemplates = true;
502 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000503 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700504 if (i + 1 < n) {
505 String8 monitorTags = String8(args[i + 1]);
506 if (monitorTags == "off") {
507 mTagMonitor.disableMonitoring();
508 } else {
509 mTagMonitor.parseTagsToMonitor(monitorTags);
510 }
511 } else {
512 mTagMonitor.disableMonitoring();
513 }
514 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800515 }
516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800517 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800519 const char *status =
520 mStatus == STATUS_ERROR ? "ERROR" :
521 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700522 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
523 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800524 mStatus == STATUS_ACTIVE ? "ACTIVE" :
525 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700526
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800527 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700528 if (mStatus == STATUS_ERROR) {
529 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
530 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800531 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800532 const char *mode =
533 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
534 mOperatingMode == static_cast<int>(
535 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
536 "CUSTOM";
537 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800538
539 if (mInputStream != NULL) {
540 write(fd, lines.string(), lines.size());
541 mInputStream->dump(fd, args);
542 } else {
543 lines.appendFormat(" No input stream.\n");
544 write(fd, lines.string(), lines.size());
545 }
546 for (size_t i = 0; i < mOutputStreams.size(); i++) {
547 mOutputStreams[i]->dump(fd,args);
548 }
549
Zhijun He431503c2016-03-07 17:30:16 -0800550 if (mBufferManager != NULL) {
551 lines = String8(" Camera3 Buffer Manager:\n");
552 write(fd, lines.string(), lines.size());
553 mBufferManager->dump(fd, args);
554 }
Zhijun He125684a2015-12-26 15:07:30 -0800555
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700556 lines = String8(" In-flight requests:\n");
Emilian Peeva6138c52021-06-24 12:52:38 -0700557 if (mInFlightLock.try_lock()) {
558 if (mInFlightMap.size() == 0) {
559 lines.append(" None\n");
560 } else {
561 for (size_t i = 0; i < mInFlightMap.size(); i++) {
562 InFlightRequest r = mInFlightMap.valueAt(i);
563 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
564 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
565 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
566 r.numBuffersLeft);
567 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700568 }
Emilian Peeva6138c52021-06-24 12:52:38 -0700569 mInFlightLock.unlock();
570 } else {
571 lines.append(" Failed to acquire In-flight lock!\n");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700572 }
573 write(fd, lines.string(), lines.size());
574
Shuzhen Wang686f6442017-06-20 16:16:04 -0700575 if (mRequestThread != NULL) {
576 mRequestThread->dumpCaptureRequestLatency(fd,
577 " ProcessCaptureRequest latency histogram:");
578 }
579
Igor Murashkin1e479c02013-09-06 16:55:14 -0700580 {
581 lines = String8(" Last request sent:\n");
582 write(fd, lines.string(), lines.size());
583
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700584 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700585 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
586 }
587
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800588 if (dumpTemplates) {
Emilian Peevf4816702020-04-03 15:44:51 -0700589 const char *templateNames[CAMERA_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800590 "TEMPLATE_PREVIEW",
591 "TEMPLATE_STILL_CAPTURE",
592 "TEMPLATE_VIDEO_RECORD",
593 "TEMPLATE_VIDEO_SNAPSHOT",
594 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800595 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800596 };
597
Emilian Peevf4816702020-04-03 15:44:51 -0700598 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800599 camera_metadata_t *templateRequest = nullptr;
600 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700601 (camera_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800602 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800603 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800604 lines.append(" Not supported\n");
605 write(fd, lines.string(), lines.size());
606 } else {
607 write(fd, lines.string(), lines.size());
608 dump_indented_camera_metadata(templateRequest,
609 fd, /*verbosity*/2, /*indentation*/8);
610 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800611 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 }
613 }
614
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700615 mTagMonitor.dumpMonitoredMetadata(fd);
616
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800618 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800619 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800621 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800622
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700623 if (gotLock) mLock.unlock();
624 if (gotInterfaceLock) mInterfaceLock.unlock();
625
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800626 return OK;
627}
628
Avichal Rakesh7e53cad2021-10-05 13:46:30 -0700629status_t Camera3Device::startWatchingTags(const String8 &tags) {
630 mTagMonitor.parseTagsToMonitor(tags);
631 return OK;
632}
633
634status_t Camera3Device::stopWatchingTags() {
635 mTagMonitor.disableMonitoring();
636 return OK;
637}
638
639status_t Camera3Device::dumpWatchedEventsToVector(std::vector<std::string> &out) {
640 mTagMonitor.getLatestMonitoredTagEvents(out);
641 return OK;
642}
643
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800644const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800645 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800646 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
647 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700648 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800649 mStatus == STATUS_ERROR ?
650 "when in error state" : "before init");
651 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700652 if (physicalId.isEmpty()) {
653 return mDeviceInfo;
654 } else {
655 std::string id(physicalId.c_str());
656 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
657 return mPhysicalDeviceInfoMap.at(id);
658 } else {
659 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
660 return mDeviceInfo;
661 }
662 }
663}
664
665const CameraMetadata& Camera3Device::info() const {
666 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800667 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800668}
669
Jianing Wei90e59c92014-03-12 18:29:36 -0700670status_t Camera3Device::checkStatusOkToCaptureLocked() {
671 switch (mStatus) {
672 case STATUS_ERROR:
673 CLOGE("Device has encountered a serious error");
674 return INVALID_OPERATION;
675 case STATUS_UNINITIALIZED:
676 CLOGE("Device not initialized");
677 return INVALID_OPERATION;
678 case STATUS_UNCONFIGURED:
679 case STATUS_CONFIGURED:
680 case STATUS_ACTIVE:
681 // OK
682 break;
683 default:
684 SET_ERR_L("Unexpected status: %d", mStatus);
685 return INVALID_OPERATION;
686 }
687 return OK;
688}
689
690status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000691 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700692 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700693 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700694 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700695 if (requestList == NULL) {
696 CLOGE("requestList cannot be NULL.");
697 return BAD_VALUE;
698 }
699
Jianing Weicb0652e2014-03-12 18:29:36 -0700700 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000701 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700702 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
703 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
704 ++metadataIt, ++surfaceMapIt) {
705 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700706 if (newRequest == 0) {
707 CLOGE("Can't create capture request");
708 return BAD_VALUE;
709 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700710
Shuzhen Wang9d066012016-09-30 11:30:20 -0700711 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700712 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700713
Jianing Weicb0652e2014-03-12 18:29:36 -0700714 // Setup burst Id and request Id
715 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800716 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
717 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700718 CLOGE("RequestID does not exist in metadata");
719 return BAD_VALUE;
720 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800721 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700722
Jianing Wei90e59c92014-03-12 18:29:36 -0700723 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700724
725 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700726 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700727 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
728 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
729 return BAD_VALUE;
730 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700731
732 // Setup batch size if this is a high speed video recording request.
733 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
734 auto firstRequest = requestList->begin();
735 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
736 if (outputStream->isVideoStream()) {
737 (*firstRequest)->mBatchSize = requestList->size();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800738 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700739 break;
740 }
741 }
742 }
743
Jianing Wei90e59c92014-03-12 18:29:36 -0700744 return OK;
745}
746
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800747status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800748 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800749
Emilian Peevaebbe412018-01-15 13:53:24 +0000750 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700751 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000752 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700753
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800754 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700755}
756
Emilian Peevaebbe412018-01-15 13:53:24 +0000757void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700758 std::list<const SurfaceMap>& surfaceMaps,
759 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000760 PhysicalCameraSettingsList requestList;
761 requestList.push_back({std::string(getId().string()), request});
762 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700763
764 SurfaceMap surfaceMap;
765 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
766 // With no surface list passed in, stream and surface will have 1-to-1
767 // mapping. So the surface index is 0 for each stream in the surfaceMap.
768 for (size_t i = 0; i < streams.count; i++) {
769 surfaceMap[streams.data.i32[i]].push_back(0);
770 }
771 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772}
773
Jianing Wei90e59c92014-03-12 18:29:36 -0700774status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000775 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700776 const std::list<const SurfaceMap> &surfaceMaps,
777 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700778 /*out*/
779 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700780 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700781 nsecs_t requestTimeNs = systemTime();
782
Jianing Wei90e59c92014-03-12 18:29:36 -0700783 Mutex::Autolock il(mInterfaceLock);
784 Mutex::Autolock l(mLock);
785
786 status_t res = checkStatusOkToCaptureLocked();
787 if (res != OK) {
788 // error logged by previous call
789 return res;
790 }
791
792 RequestList requestList;
793
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700795 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700796 if (res != OK) {
797 // error logged by previous call
798 return res;
799 }
800
801 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700802 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700804 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700805 }
806
807 if (res == OK) {
808 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
809 if (res != OK) {
810 SET_ERR_L("Can't transition to active in %f seconds!",
811 kActiveTimeout/1e9);
812 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800813 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700814 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700815 } else {
816 CLOGE("Cannot queue request. Impossible.");
817 return BAD_VALUE;
818 }
819
820 return res;
821}
822
Emilian Peevaebbe412018-01-15 13:53:24 +0000823status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700824 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -0700825 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700826 ATRACE_CALL();
827
Emilian Peevaebbe412018-01-15 13:53:24 +0000828 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700829}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800830
Jianing Weicb0652e2014-03-12 18:29:36 -0700831status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
832 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800833 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800834
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700836 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000837 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700838
Emilian Peevaebbe412018-01-15 13:53:24 +0000839 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700840 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800841}
842
Emilian Peevaebbe412018-01-15 13:53:24 +0000843status_t Camera3Device::setStreamingRequestList(
844 const List<const PhysicalCameraSettingsList> &requestsList,
845 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700846 ATRACE_CALL();
847
Emilian Peevaebbe412018-01-15 13:53:24 +0000848 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700849}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800850
851sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000852 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800853 status_t res;
854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700855 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -0800856 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
857 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -0700859 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700860 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800861 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700862 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800863 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -0700864 } else if (mStatus == STATUS_UNCONFIGURED) {
865 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700866 CLOGE("No streams configured");
867 return NULL;
868 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800869 }
870
Shuzhen Wang0129d522016-10-30 22:43:41 -0700871 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800872 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800873}
874
Jianing Weicb0652e2014-03-12 18:29:36 -0700875status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800876 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700877 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800878 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800879
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800880 switch (mStatus) {
881 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700882 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800883 return INVALID_OPERATION;
884 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700885 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800886 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700887 case STATUS_UNCONFIGURED:
888 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800889 case STATUS_ACTIVE:
890 // OK
891 break;
892 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700893 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800894 return INVALID_OPERATION;
895 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800896 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -0700897
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700898 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800899}
900
901status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
902 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700903 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904
Igor Murashkin4d2f2e82013-04-01 17:29:07 -0700905 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800906}
907
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700908status_t Camera3Device::createInputStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800909 uint32_t width, uint32_t height, int format, bool isMultiResolution, int *id) {
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700910 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700911 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700912 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700913 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800914 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
915 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700916
917 status_t res;
918 bool wasActive = false;
919
920 switch (mStatus) {
921 case STATUS_ERROR:
922 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
923 return INVALID_OPERATION;
924 case STATUS_UNINITIALIZED:
925 ALOGE("%s: Device not initialized", __FUNCTION__);
926 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700927 case STATUS_UNCONFIGURED:
928 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700929 // OK
930 break;
931 case STATUS_ACTIVE:
932 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700933 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700934 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700935 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700936 return res;
937 }
938 wasActive = true;
939 break;
940 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700941 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700942 return INVALID_OPERATION;
943 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700944 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700945
946 if (mInputStream != 0) {
947 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
948 return INVALID_OPERATION;
949 }
950
951 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
952 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700953 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700954
955 mInputStream = newStream;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800956 mIsInputStreamMultiResolution = isMultiResolution;
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700957
958 *id = mNextStreamId++;
959
960 // Continue captures if active at start
961 if (wasActive) {
962 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +0100963 // Reuse current operating mode and session parameters for new stream config
964 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700965 if (res != OK) {
966 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
967 __FUNCTION__, mNextStreamId, strerror(-res), res);
968 return res;
969 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700970 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700971 }
972
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800973 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -0700974 return OK;
975}
976
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700977status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700978 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700979 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800980 const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800981 const std::unordered_set<int32_t> &sensorPixelModesUsed,
982 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800983 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase, int timestampBase,
984 int mirrorMode) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700985 ATRACE_CALL();
986
987 if (consumer == nullptr) {
988 ALOGE("%s: consumer must not be null", __FUNCTION__);
989 return BAD_VALUE;
990 }
991
992 std::vector<sp<Surface>> consumers;
993 consumers.push_back(consumer);
994
995 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800996 format, dataSpace, rotation, id, physicalCameraId, sensorPixelModesUsed, surfaceIds,
Shuzhen Wangc8ab4522021-12-14 20:12:42 -0800997 streamSetId, isShared, isMultiResolution, consumerUsage, dynamicRangeProfile,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800998 streamUseCase, timestampBase, mirrorMode);
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800999}
1000
1001static bool isRawFormat(int format) {
1002 switch (format) {
1003 case HAL_PIXEL_FORMAT_RAW16:
1004 case HAL_PIXEL_FORMAT_RAW12:
1005 case HAL_PIXEL_FORMAT_RAW10:
1006 case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1007 return true;
1008 default:
1009 return false;
1010 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001011}
1012
1013status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1014 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001015 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001016 const String8& physicalCameraId, const std::unordered_set<int32_t> &sensorPixelModesUsed,
Shuzhen Wang83bff122020-11-20 15:51:39 -08001017 std::vector<int> *surfaceIds, int streamSetId, bool isShared, bool isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001018 uint64_t consumerUsage, int dynamicRangeProfile, int streamUseCase, int timestampBase,
1019 int mirrorMode) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001020 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001021
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001022 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001023 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001024 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001025 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wange4208922022-02-01 16:52:48 -08001026 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s, isMultiResolution %d"
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001027 " dynamicRangeProfile %d, streamUseCase %d, timestampBase %d, mirrorMode %d",
Shuzhen Wang83bff122020-11-20 15:51:39 -08001028 mId.string(), mNextStreamId, width, height, format, dataSpace, rotation,
Shuzhen Wange4208922022-02-01 16:52:48 -08001029 consumerUsage, isShared, physicalCameraId.string(), isMultiResolution,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001030 dynamicRangeProfile, streamUseCase, timestampBase, mirrorMode);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001031
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001032 status_t res;
1033 bool wasActive = false;
1034
1035 switch (mStatus) {
1036 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001037 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001038 return INVALID_OPERATION;
1039 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001040 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001041 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001042 case STATUS_UNCONFIGURED:
1043 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001044 // OK
1045 break;
1046 case STATUS_ACTIVE:
1047 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001048 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001049 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001050 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001051 return res;
1052 }
1053 wasActive = true;
1054 break;
1055 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001056 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001057 return INVALID_OPERATION;
1058 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001059 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001060
1061 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001062
Shuzhen Wang0129d522016-10-30 22:43:41 -07001063 if (consumers.size() == 0 && !hasDeferredConsumer) {
1064 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1065 return BAD_VALUE;
1066 }
Zhijun He5d677d12016-05-29 16:52:39 -07001067
Shuzhen Wang0129d522016-10-30 22:43:41 -07001068 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001069 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1070 return BAD_VALUE;
1071 }
1072
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001073 if (isRawFormat(format) && sensorPixelModesUsed.size() > 1) {
1074 // We can't use one stream with a raw format in both sensor pixel modes since its going to
1075 // be found in only one sensor pixel mode.
1076 ALOGE("%s: RAW opaque stream cannot be used with > 1 sensor pixel modes", __FUNCTION__);
1077 return BAD_VALUE;
1078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001079 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001080 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001081 if (dataSpace == HAL_DATASPACE_DEPTH) {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001082 blobBufferSize = getPointCloudBufferSize(infoPhysical(physicalCameraId));
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001083 if (blobBufferSize <= 0) {
1084 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1085 return BAD_VALUE;
1086 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001087 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1088 blobBufferSize = width * height;
1089 } else {
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001090 blobBufferSize = getJpegBufferSize(infoPhysical(physicalCameraId), width, height);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001091 if (blobBufferSize <= 0) {
1092 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1093 return BAD_VALUE;
1094 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001095 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001096 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001097 width, height, blobBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001098 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001099 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001100 timestampBase, mirrorMode);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001101 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001102 bool maxResolution =
1103 sensorPixelModesUsed.find(ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) !=
1104 sensorPixelModesUsed.end();
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08001105 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(infoPhysical(physicalCameraId), width,
1106 height, maxResolution);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001107 if (rawOpaqueBufferSize <= 0) {
1108 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1109 return BAD_VALUE;
1110 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001111 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001112 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001113 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001114 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001115 timestampBase, mirrorMode);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001116 } else if (isShared) {
1117 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1118 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001119 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001120 mUseHalBufManager, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001121 timestampBase, mirrorMode);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001122 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001123 newStream = new Camera3OutputStream(mNextStreamId,
1124 width, height, format, consumerUsage, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001125 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001126 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001127 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001128 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001129 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001130 width, height, format, dataSpace, rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -08001131 mTimestampOffset, physicalCameraId, sensorPixelModesUsed, streamSetId,
Shuzhen Wange4208922022-02-01 16:52:48 -08001132 isMultiResolution, dynamicRangeProfile, streamUseCase, mDeviceTimeBaseIsRealtime,
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001133 timestampBase, mirrorMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001134 }
Emilian Peev40ead602017-09-26 15:46:36 +01001135
1136 size_t consumerCount = consumers.size();
1137 for (size_t i = 0; i < consumerCount; i++) {
1138 int id = newStream->getSurfaceId(consumers[i]);
1139 if (id < 0) {
1140 SET_ERR_L("Invalid surface id");
1141 return BAD_VALUE;
1142 }
1143 if (surfaceIds != nullptr) {
1144 surfaceIds->push_back(id);
1145 }
1146 }
1147
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001148 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001149
Emilian Peev08dd2452017-04-06 16:55:14 +01001150 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001151
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001152 newStream->setImageDumpMask(mImageDumpMask);
1153
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001154 res = mOutputStreams.add(mNextStreamId, newStream);
1155 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001156 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001157 return res;
1158 }
1159
Shuzhen Wang316781a2020-08-18 18:11:01 -07001160 mSessionStatsBuilder.addStream(mNextStreamId);
1161
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001162 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001163 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001164
1165 // Continue captures if active at start
1166 if (wasActive) {
1167 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001168 // Reuse current operating mode and session parameters for new stream config
1169 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001170 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001171 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1172 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001173 return res;
1174 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001175 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001176 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001177 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001178 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001179}
1180
Emilian Peev710c1422017-08-30 11:19:38 +01001181status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001182 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001183 if (nullptr == streamInfo) {
1184 return BAD_VALUE;
1185 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001186 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001187 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001188
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189 switch (mStatus) {
1190 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001191 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 return INVALID_OPERATION;
1193 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001194 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001195 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001196 case STATUS_UNCONFIGURED:
1197 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198 case STATUS_ACTIVE:
1199 // OK
1200 break;
1201 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001202 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return INVALID_OPERATION;
1204 }
1205
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001206 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1207 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001208 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001209 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 }
1211
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001212 streamInfo->width = stream->getWidth();
1213 streamInfo->height = stream->getHeight();
1214 streamInfo->format = stream->getFormat();
1215 streamInfo->dataSpace = stream->getDataSpace();
1216 streamInfo->formatOverridden = stream->isFormatOverridden();
1217 streamInfo->originalFormat = stream->getOriginalFormat();
1218 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1219 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Emilian Peev2295df72021-11-12 18:14:10 -08001220 streamInfo->dynamicRangeProfile = stream->getDynamicRangeProfile();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001222}
1223
1224status_t Camera3Device::setStreamTransform(int id,
1225 int transform) {
1226 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001229
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 switch (mStatus) {
1231 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
1234 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001235 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 case STATUS_UNCONFIGURED:
1238 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 case STATUS_ACTIVE:
1240 // OK
1241 break;
1242 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001243 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 return INVALID_OPERATION;
1245 }
1246
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001247 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1248 if (stream == nullptr) {
1249 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 return BAD_VALUE;
1251 }
Shuzhen Wang610d7b82022-02-08 14:37:22 -08001252 return stream->setTransform(transform, false /*mayChangeMirror*/);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
1255status_t Camera3Device::deleteStream(int id) {
1256 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001257 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 Mutex::Autolock l(mLock);
1259 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001260
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001262
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001263 // CameraDevice semantics require device to already be idle before
1264 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001265 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001266 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001267 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001268 }
1269
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001270 if (mStatus == STATUS_ERROR) {
1271 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1272 __FUNCTION__, mId.string());
1273 return -EBUSY;
1274 }
1275
Igor Murashkin2fba5842013-04-22 14:03:54 -07001276 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001277 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001278 if (mInputStream != NULL && id == mInputStream->getId()) {
1279 deletedStream = mInputStream;
1280 mInputStream.clear();
1281 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001282 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001283 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001284 return BAD_VALUE;
1285 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001286 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001287 }
1288
1289 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001290 if (stream != nullptr) {
1291 deletedStream = stream;
1292 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001293 }
1294
1295 // Free up the stream endpoint so that it can be used by some other stream
1296 res = deletedStream->disconnect();
1297 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001298 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001299 // fall through since we want to still list the stream as deleted.
1300 }
1301 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001302 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001303
1304 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001305}
1306
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001307status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001308 ATRACE_CALL();
1309 ALOGV("%s: E", __FUNCTION__);
1310
1311 Mutex::Autolock il(mInterfaceLock);
1312 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001313
Emilian Peev811d2952018-05-25 11:08:40 +01001314 // In case the client doesn't include any session parameter, try a
1315 // speculative configuration using the values from the last cached
1316 // default request.
1317 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001318 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001319 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1320 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1321 mLastTemplateId);
1322 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1323 operatingMode);
1324 }
1325
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001326 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1327}
1328
1329status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1330 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001331 //Filter out any incoming session parameters
1332 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001333 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1334 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001335 CameraMetadata filteredParams(availableSessionKeys.count);
1336 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1337 filteredParams.getAndLock());
1338 set_camera_metadata_vendor_id(meta, mVendorTagId);
1339 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001340 if (availableSessionKeys.count > 0) {
1341 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1342 camera_metadata_ro_entry entry = params.find(
1343 availableSessionKeys.data.i32[i]);
1344 if (entry.count > 0) {
1345 filteredParams.update(entry);
1346 }
1347 }
1348 }
1349
1350 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001351}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001352
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001353status_t Camera3Device::getInputBufferProducer(
1354 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001355 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001356 Mutex::Autolock il(mInterfaceLock);
1357 Mutex::Autolock l(mLock);
1358
1359 if (producer == NULL) {
1360 return BAD_VALUE;
1361 } else if (mInputStream == NULL) {
1362 return INVALID_OPERATION;
1363 }
1364
1365 return mInputStream->getInputBufferProducer(producer);
1366}
1367
Emilian Peevf4816702020-04-03 15:44:51 -07001368status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001369 CameraMetadata *request) {
1370 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001371 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001372
Emilian Peevf4816702020-04-03 15:44:51 -07001373 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001374 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001375 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001376 return BAD_VALUE;
1377 }
1378
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001379 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001380
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001381 {
1382 Mutex::Autolock l(mLock);
1383 switch (mStatus) {
1384 case STATUS_ERROR:
1385 CLOGE("Device has encountered a serious error");
1386 return INVALID_OPERATION;
1387 case STATUS_UNINITIALIZED:
1388 CLOGE("Device is not initialized!");
1389 return INVALID_OPERATION;
1390 case STATUS_UNCONFIGURED:
1391 case STATUS_CONFIGURED:
1392 case STATUS_ACTIVE:
1393 // OK
1394 break;
1395 default:
1396 SET_ERR_L("Unexpected status: %d", mStatus);
1397 return INVALID_OPERATION;
1398 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001399
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001400 if (!mRequestTemplateCache[templateId].isEmpty()) {
1401 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001402 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001403 return OK;
1404 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001405 }
1406
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001407 camera_metadata_t *rawRequest;
1408 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001409 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001410
1411 {
1412 Mutex::Autolock l(mLock);
1413 if (res == BAD_VALUE) {
1414 ALOGI("%s: template %d is not supported on this camera device",
1415 __FUNCTION__, templateId);
1416 return res;
1417 } else if (res != OK) {
1418 CLOGE("Unable to construct request template %d: %s (%d)",
1419 templateId, strerror(-res), res);
1420 return res;
1421 }
1422
1423 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1424 mRequestTemplateCache[templateId].acquire(rawRequest);
1425
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001426 // Override the template request with zoomRatioMapper
1427 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1428 &mRequestTemplateCache[templateId]);
1429 if (res != OK) {
1430 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1431 templateId, strerror(-res), res);
1432 return res;
1433 }
1434
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001435 // Fill in JPEG_QUALITY if not available
1436 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1437 static const uint8_t kDefaultJpegQuality = 95;
1438 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1439 &kDefaultJpegQuality, 1);
1440 }
1441
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001442 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001443 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001444 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001445 return OK;
1446}
1447
1448status_t Camera3Device::waitUntilDrained() {
1449 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001450 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001451 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001453
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001454 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001455}
1456
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001457status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 switch (mStatus) {
1459 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001460 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 ALOGV("%s: Already idle", __FUNCTION__);
1462 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001463 case STATUS_CONFIGURED:
1464 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 case STATUS_ERROR:
1466 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001467 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 break;
1469 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001470 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 return INVALID_OPERATION;
1472 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001473 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1474 maxExpectedDuration);
1475 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001476 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001477 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001478 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1479 res);
1480 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 return res;
1482}
1483
Ruben Brunk183f0562015-08-12 12:55:02 -07001484void Camera3Device::internalUpdateStatusLocked(Status status) {
1485 mStatus = status;
1486 mRecentStatusUpdates.add(mStatus);
1487 mStatusChanged.broadcast();
1488}
1489
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001490// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001491status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001492 if (mRequestThread.get() != nullptr) {
1493 mRequestThread->setPaused(true);
1494 } else {
1495 return NO_INIT;
1496 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001498 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1499 maxExpectedDuration);
1500 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 if (res != OK) {
1502 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001503 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 }
1505
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001506 return res;
1507}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001509// Resume after internalPauseAndWaitLocked
1510status_t Camera3Device::internalResumeLocked() {
1511 status_t res;
1512
1513 mRequestThread->setPaused(false);
1514
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001515 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1516 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001517 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1518 if (res != OK) {
1519 SET_ERR_L("Can't transition to active in %f seconds!",
1520 kActiveTimeout/1e9);
1521 }
1522 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001524}
1525
Ruben Brunk183f0562015-08-12 12:55:02 -07001526status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001527 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001528
1529 size_t startIndex = 0;
1530 if (mStatusWaiters == 0) {
1531 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1532 // this status list
1533 mRecentStatusUpdates.clear();
1534 } else {
1535 // If other threads are waiting on updates to this status list, set the position of the
1536 // first element that this list will check rather than clearing the list.
1537 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001538 }
1539
Ruben Brunk183f0562015-08-12 12:55:02 -07001540 mStatusWaiters++;
1541
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001542 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001543 if (!active && mUseHalBufManager) {
1544 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001545 if (mStatus == STATUS_ACTIVE) {
1546 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001547 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001548 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001549 mRequestBufferSM.onWaitUntilIdle();
1550 }
1551
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 bool stateSeen = false;
1553 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001554 if (active == (mStatus == STATUS_ACTIVE)) {
1555 // Desired state is current
1556 break;
1557 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558
1559 res = mStatusChanged.waitRelative(mLock, timeout);
1560 if (res != OK) break;
1561
Ruben Brunk183f0562015-08-12 12:55:02 -07001562 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1563 // transitions.
1564 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1565 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1566 __FUNCTION__);
1567
1568 // Encountered desired state since we began waiting
1569 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1571 stateSeen = true;
1572 break;
1573 }
1574 }
1575 } while (!stateSeen);
1576
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001577 if (signalPipelineDrain) {
1578 mRequestThread->resetPipelineDrain();
1579 }
1580
Ruben Brunk183f0562015-08-12 12:55:02 -07001581 mStatusWaiters--;
1582
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 return res;
1584}
1585
1586
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001587status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001589 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001591 if (listener != NULL && mListener != NULL) {
1592 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1593 }
1594 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001595 mRequestThread->setNotificationListener(listener);
1596 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001597
1598 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599}
1600
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001601bool Camera3Device::willNotify3A() {
1602 return false;
1603}
1604
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001605status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001606 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001607 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001608
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001609 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001610 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1611 if (st == std::cv_status::timeout) {
1612 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001613 }
1614 }
1615 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001616}
1617
Jianing Weicb0652e2014-03-12 18:29:36 -07001618status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001620 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001621
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001622 if (mResultQueue.empty()) {
1623 return NOT_ENOUGH_DATA;
1624 }
1625
Jianing Weicb0652e2014-03-12 18:29:36 -07001626 if (frame == NULL) {
1627 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1628 return BAD_VALUE;
1629 }
1630
1631 CaptureResult &result = *(mResultQueue.begin());
1632 frame->mResultExtras = result.mResultExtras;
1633 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001634 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001635 mResultQueue.erase(mResultQueue.begin());
1636
1637 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001638}
1639
1640status_t Camera3Device::triggerAutofocus(uint32_t id) {
1641 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001643
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001644 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1645 // Mix-in this trigger into the next request and only the next request.
1646 RequestTrigger trigger[] = {
1647 {
1648 ANDROID_CONTROL_AF_TRIGGER,
1649 ANDROID_CONTROL_AF_TRIGGER_START
1650 },
1651 {
1652 ANDROID_CONTROL_AF_TRIGGER_ID,
1653 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001654 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001655 };
1656
1657 return mRequestThread->queueTrigger(trigger,
1658 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659}
1660
1661status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1662 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001663 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001664
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001665 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1666 // Mix-in this trigger into the next request and only the next request.
1667 RequestTrigger trigger[] = {
1668 {
1669 ANDROID_CONTROL_AF_TRIGGER,
1670 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1671 },
1672 {
1673 ANDROID_CONTROL_AF_TRIGGER_ID,
1674 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001675 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001676 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001678 return mRequestThread->queueTrigger(trigger,
1679 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680}
1681
1682status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1683 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001685
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001686 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1687 // Mix-in this trigger into the next request and only the next request.
1688 RequestTrigger trigger[] = {
1689 {
1690 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1691 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1692 },
1693 {
1694 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1695 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001696 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001697 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001699 return mRequestThread->queueTrigger(trigger,
1700 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001701}
1702
Jianing Weicb0652e2014-03-12 18:29:36 -07001703status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001704 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001705 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001706 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001707
Zhijun He7ef20392014-04-21 16:04:17 -07001708 {
1709 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001710
1711 // b/116514106 "disconnect()" can get called twice for the same device. The
1712 // camera device will not be initialized during the second run.
1713 if (mStatus == STATUS_UNINITIALIZED) {
1714 return OK;
1715 }
1716
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001717 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001718
1719 // Stop session and stream counter
1720 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07001721 }
1722
Emilian Peev08dd2452017-04-06 16:55:14 +01001723 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001724}
1725
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001726status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07001727 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
1728}
1729
1730status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001731 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001732 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001733 Mutex::Autolock il(mInterfaceLock);
1734 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001735
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001736 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1737 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001738 CLOGE("Stream %d does not exist", streamId);
1739 return BAD_VALUE;
1740 }
1741
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001742 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001743 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001744 return BAD_VALUE;
1745 }
1746
1747 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07001748 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001749 return BAD_VALUE;
1750 }
1751
Ruben Brunkc78ac262015-08-13 17:58:46 -07001752 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001753}
1754
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001755status_t Camera3Device::tearDown(int streamId) {
1756 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001757 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001758 Mutex::Autolock il(mInterfaceLock);
1759 Mutex::Autolock l(mLock);
1760
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001761 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1762 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001763 CLOGE("Stream %d does not exist", streamId);
1764 return BAD_VALUE;
1765 }
1766
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07001767 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
1768 CLOGE("Stream %d is a target of a in-progress request", streamId);
1769 return BAD_VALUE;
1770 }
1771
1772 return stream->tearDown();
1773}
1774
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001775status_t Camera3Device::addBufferListenerForStream(int streamId,
1776 wp<Camera3StreamBufferListener> listener) {
1777 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001778 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001779 Mutex::Autolock il(mInterfaceLock);
1780 Mutex::Autolock l(mLock);
1781
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001782 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
1783 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001784 CLOGE("Stream %d does not exist", streamId);
1785 return BAD_VALUE;
1786 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07001787 stream->addBufferListener(listener);
1788
1789 return OK;
1790}
1791
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001792/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001793 * Methods called by subclasses
1794 */
1795
1796void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001797 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001798 std::vector<int> streamIds;
1799 std::vector<hardware::CameraStreamStats> streamStats;
1800
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001801 {
1802 // Need mLock to safely update state and synchronize to current
1803 // state of methods in flight.
1804 Mutex::Autolock l(mLock);
1805 // We can get various system-idle notices from the status tracker
1806 // while starting up. Only care about them if we've actually sent
1807 // in some requests recently.
1808 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1809 return;
1810 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001811 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
1812 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07001813 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814
1815 // Skip notifying listener if we're doing some user-transparent
1816 // state changes
1817 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001818
1819 // Populate stream statistics in case of Idle
1820 if (idle) {
1821 for (size_t i = 0; i < mOutputStreams.size(); i++) {
1822 auto stream = mOutputStreams[i];
1823 if (stream.get() == nullptr) continue;
1824 streamIds.push_back(stream->getId());
1825 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
1826 int64_t usage = 0LL;
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001827 int streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001828 if (camera3Stream != nullptr) {
1829 usage = camera3Stream->getUsage();
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001830 streamUseCase = camera3Stream->getStreamUseCase();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001831 }
1832 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
1833 stream->getFormat(), stream->getDataSpace(), usage,
1834 stream->getMaxHalBuffers(),
Emilian Peev2295df72021-11-12 18:14:10 -08001835 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers(),
Shuzhen Wangc8ab4522021-12-14 20:12:42 -08001836 stream->getDynamicRangeProfile(), streamUseCase);
Shuzhen Wang316781a2020-08-18 18:11:01 -07001837 }
1838 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001839 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001840
1841 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001842 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001843 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001844 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001846 status_t res = OK;
1847 if (listener != nullptr) {
1848 if (idle) {
1849 // Get session stats from the builder, and notify the listener.
1850 int64_t requestCount, resultErrorCount;
1851 bool deviceError;
1852 std::map<int, StreamStats> streamStatsMap;
1853 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
1854 &deviceError, &streamStatsMap);
1855 for (size_t i = 0; i < streamIds.size(); i++) {
1856 int streamId = streamIds[i];
1857 auto stats = streamStatsMap.find(streamId);
1858 if (stats != streamStatsMap.end()) {
1859 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
1860 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
1861 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
1862 streamStats[i].mHistogramType =
1863 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
1864 streamStats[i].mHistogramBins.assign(
1865 stats->second.mCaptureLatencyBins.begin(),
1866 stats->second.mCaptureLatencyBins.end());
1867 streamStats[i].mHistogramCounts.assign(
1868 stats->second.mCaptureLatencyHistogram.begin(),
1869 stats->second.mCaptureLatencyHistogram.end());
1870 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001871 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001872 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
1873 } else {
1874 res = listener->notifyActive();
Shuzhen Wang316781a2020-08-18 18:11:01 -07001875 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07001876 }
1877 if (res != OK) {
1878 SET_ERR("Camera access permission lost mid-operation: %s (%d)",
1879 strerror(-res), res);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001880 }
1881}
1882
Shuzhen Wang758c2152017-01-10 18:26:18 -08001883status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01001884 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07001885 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001886 ALOGV("%s: Camera %s: set consumer surface for stream %d",
1887 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01001888
1889 if (surfaceIds == nullptr) {
1890 return BAD_VALUE;
1891 }
1892
Zhijun He5d677d12016-05-29 16:52:39 -07001893 Mutex::Autolock il(mInterfaceLock);
1894 Mutex::Autolock l(mLock);
1895
Shuzhen Wang758c2152017-01-10 18:26:18 -08001896 if (consumers.size() == 0) {
1897 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07001898 return BAD_VALUE;
1899 }
1900
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001901 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1902 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07001903 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001904 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07001905 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001906
1907 // isConsumerConfigurationDeferred will be off after setConsumers
1908 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08001909 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07001910 if (res != OK) {
1911 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
1912 return res;
1913 }
1914
Emilian Peev40ead602017-09-26 15:46:36 +01001915 for (auto &consumer : consumers) {
1916 int id = stream->getSurfaceId(consumer);
1917 if (id < 0) {
1918 CLOGE("Invalid surface id!");
1919 return BAD_VALUE;
1920 }
1921 surfaceIds->push_back(id);
1922 }
1923
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07001924 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001925 if (!stream->isConfiguring()) {
1926 CLOGE("Stream %d was already fully configured.", streamId);
1927 return INVALID_OPERATION;
1928 }
Zhijun He5d677d12016-05-29 16:52:39 -07001929
Shuzhen Wang0129d522016-10-30 22:43:41 -07001930 res = stream->finishConfiguration();
1931 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07001932 // If finishConfiguration fails due to abandoned surface, do not set
1933 // device to error state.
1934 bool isSurfaceAbandoned =
1935 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
1936 if (!isSurfaceAbandoned) {
1937 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1938 stream->getId(), strerror(-res), res);
1939 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001940 return res;
1941 }
Zhijun He5d677d12016-05-29 16:52:39 -07001942 }
1943
1944 return OK;
1945}
1946
Emilian Peev40ead602017-09-26 15:46:36 +01001947status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
1948 const std::vector<OutputStreamInfo> &outputInfo,
1949 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
1950 Mutex::Autolock il(mInterfaceLock);
1951 Mutex::Autolock l(mLock);
1952
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001953 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1954 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01001955 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001956 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01001957 }
1958
1959 for (const auto &it : removedSurfaceIds) {
1960 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
1961 CLOGE("Shared surface still part of a pending request!");
1962 return -EBUSY;
1963 }
1964 }
1965
Emilian Peev40ead602017-09-26 15:46:36 +01001966 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
1967 if (res != OK) {
1968 CLOGE("Stream %d failed to update stream (error %d %s) ",
1969 streamId, res, strerror(-res));
1970 if (res == UNKNOWN_ERROR) {
1971 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
1972 __FUNCTION__);
1973 }
1974 return res;
1975 }
1976
1977 return res;
1978}
1979
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001980status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
1981 Mutex::Autolock il(mInterfaceLock);
1982 Mutex::Autolock l(mLock);
1983
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001984 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
1985 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001986 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
1987 return BAD_VALUE;
1988 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001989
1990 if (dropping) {
1991 mSessionStatsBuilder.stopCounter(streamId);
1992 } else {
1993 mSessionStatsBuilder.startCounter(streamId);
1994 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001995 return stream->dropBuffers(dropping);
1996}
1997
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001998/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001999 * Camera3Device private methods
2000 */
2001
2002sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002003 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002004 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002005
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002006 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002007 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002008
2009 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002010 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002011 if (inputStreams.count > 0) {
2012 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002013 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002014 CLOGE("Request references unknown input stream %d",
2015 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002016 return NULL;
2017 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002018
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002020 SET_ERR_L("%s: input stream %d is not configured!",
2021 __FUNCTION__, mInputStream->getId());
2022 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002023 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002024 // Check if stream prepare is blocking requests.
2025 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002026 CLOGE("Request references an input stream that's being prepared!");
2027 return NULL;
2028 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002029
2030 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002031 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002032 }
2033
2034 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002035 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002036 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002037 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002038 return NULL;
2039 }
2040
2041 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002042 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2043 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002044 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002045 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046 return NULL;
2047 }
Zhijun He5d677d12016-05-29 16:52:39 -07002048 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002049 auto iter = surfaceMap.find(streams.data.i32[i]);
2050 if (iter != surfaceMap.end()) {
2051 const std::vector<size_t>& surfaces = iter->second;
2052 for (const auto& surface : surfaces) {
2053 if (stream->isConsumerConfigurationDeferred(surface)) {
2054 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2055 "due to deferred consumer", stream->getId(), surface);
2056 return NULL;
2057 }
2058 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002059 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002060 }
2061
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002062 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002063 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2064 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002066 // Check if stream prepare is blocking requests.
2067 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002068 CLOGE("Request references an output stream that's being prepared!");
2069 return NULL;
2070 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071
2072 newRequest->mOutputStreams.push(stream);
2073 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002074 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002075 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002077 auto rotateAndCropEntry =
2078 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2079 if (rotateAndCropEntry.count > 0 &&
2080 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2081 newRequest->mRotateAndCropAuto = true;
2082 } else {
2083 newRequest->mRotateAndCropAuto = false;
2084 }
2085
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002086 auto zoomRatioEntry =
2087 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2088 if (zoomRatioEntry.count > 0 &&
2089 zoomRatioEntry.data.f[0] == 1.0f) {
2090 newRequest->mZoomRatioIs1x = true;
2091 } else {
2092 newRequest->mZoomRatioIs1x = false;
2093 }
2094
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002095 if (mSupportCameraMute) {
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002096 for (auto& settings : newRequest->mSettingsList) {
2097 auto testPatternModeEntry =
2098 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2099 settings.mOriginalTestPatternMode = testPatternModeEntry.count > 0 ?
2100 testPatternModeEntry.data.i32[0] :
2101 ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002102
Shuzhen Wang911c6a32021-10-27 13:36:03 -07002103 auto testPatternDataEntry =
2104 settings.metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2105 if (testPatternDataEntry.count >= 4) {
2106 memcpy(settings.mOriginalTestPatternData, testPatternDataEntry.data.i32,
2107 sizeof(PhysicalCameraSettings::mOriginalTestPatternData));
2108 } else {
2109 settings.mOriginalTestPatternData[0] = 0;
2110 settings.mOriginalTestPatternData[1] = 0;
2111 settings.mOriginalTestPatternData[2] = 0;
2112 settings.mOriginalTestPatternData[3] = 0;
2113 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002114 }
2115 }
2116
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002118}
2119
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002120void Camera3Device::cancelStreamsConfigurationLocked() {
2121 int res = OK;
2122 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2123 res = mInputStream->cancelConfiguration();
2124 if (res != OK) {
2125 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2126 mInputStream->getId(), strerror(-res), res);
2127 }
2128 }
2129
2130 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002131 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002132 if (outputStream->isConfiguring()) {
2133 res = outputStream->cancelConfiguration();
2134 if (res != OK) {
2135 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2136 outputStream->getId(), strerror(-res), res);
2137 }
2138 }
2139 }
2140
2141 // Return state to that at start of call, so that future configures
2142 // properly clean things up
2143 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2144 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002145
2146 res = mPreparerThread->resume();
2147 if (res != OK) {
2148 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2149 }
2150}
2151
Emilian Peev0d0191e2020-04-21 17:01:18 -07002152bool Camera3Device::checkAbandonedStreamsLocked() {
2153 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2154 return true;
2155 }
2156
2157 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2158 auto stream = mOutputStreams[i];
2159 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2160 return true;
2161 }
2162 }
2163
2164 return false;
2165}
2166
Emilian Peev3bead5f2020-05-28 17:29:08 -07002167bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002168 ATRACE_CALL();
2169 bool ret = false;
2170
Shuzhen Wang316781a2020-08-18 18:11:01 -07002171 nsecs_t startTime = systemTime();
2172
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002173 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002174 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2175
2176 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002177 if (checkAbandonedStreamsLocked()) {
2178 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2179 __FUNCTION__);
2180 return true;
2181 }
2182
Emilian Peev3bead5f2020-05-28 17:29:08 -07002183 status_t rc = NO_ERROR;
2184 bool markClientActive = false;
2185 if (mStatus == STATUS_ACTIVE) {
2186 markClientActive = true;
2187 mPauseStateNotify = true;
2188 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2189
2190 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2191 }
2192
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002193 if (rc == NO_ERROR) {
2194 mNeedConfig = true;
2195 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2196 if (rc == NO_ERROR) {
2197 ret = true;
2198 mPauseStateNotify = false;
2199 //Moving to active state while holding 'mLock' is important.
2200 //There could be pending calls to 'create-/deleteStream' which
2201 //will trigger another stream configuration while the already
2202 //present streams end up with outstanding buffers that will
2203 //not get drained.
2204 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002205 } else if (rc == DEAD_OBJECT) {
2206 // DEAD_OBJECT can be returned if either the consumer surface is
2207 // abandoned, or the HAL has died.
2208 // - If the HAL has died, configureStreamsLocked call will set
2209 // device to error state,
2210 // - If surface is abandoned, we should not set device to error
2211 // state.
2212 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002213 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002214 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002215 }
2216 } else {
2217 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2218 }
2219
Shuzhen Wang316781a2020-08-18 18:11:01 -07002220 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2221 ns2ms(systemTime() - startTime));
2222
Emilian Peev3bead5f2020-05-28 17:29:08 -07002223 if (markClientActive) {
2224 mStatusTracker->markComponentActive(clientStatusId);
2225 }
2226
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002227 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002228}
2229
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002230status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002231 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002232 ATRACE_CALL();
2233 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002234
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002235 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002236 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002237 return INVALID_OPERATION;
2238 }
2239
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002240 if (operatingMode < 0) {
2241 CLOGE("Invalid operating mode: %d", operatingMode);
2242 return BAD_VALUE;
2243 }
2244
2245 bool isConstrainedHighSpeed =
2246 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2247 operatingMode;
2248
2249 if (mOperatingMode != operatingMode) {
2250 mNeedConfig = true;
2251 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2252 mOperatingMode = operatingMode;
2253 }
2254
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002255 // In case called from configureStreams, abort queued input buffers not belonging to
2256 // any pending requests.
2257 if (mInputStream != NULL && notifyRequestThread) {
2258 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002259 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08002260 camera3::Size inputBufferSize;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002261 status_t res = mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08002262 &inputBufferSize, /*respectHalLimit*/ false);
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002263 if (res != OK) {
2264 // Exhausted acquiring all input buffers.
2265 break;
2266 }
2267
Emilian Peevf4816702020-04-03 15:44:51 -07002268 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002269 res = mInputStream->returnInputBuffer(inputBuffer);
2270 if (res != OK) {
2271 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2272 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2273 }
2274 }
2275 }
2276
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002277 if (!mNeedConfig) {
2278 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2279 return OK;
2280 }
2281
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002282 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002283 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002284 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2285 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002286 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002287 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002288 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002289 }
2290
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002292 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002294 mPreparerThread->pause();
2295
Emilian Peevf4816702020-04-03 15:44:51 -07002296 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002297 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Shuzhen Wang83bff122020-11-20 15:51:39 -08002299 config.input_is_multi_resolution = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300
Emilian Peevf4816702020-04-03 15:44:51 -07002301 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002303 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305
2306 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002307 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 inputStream = mInputStream->startConfiguration();
2309 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002310 CLOGE("Can't start input stream configuration");
2311 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 return INVALID_OPERATION;
2313 }
2314 streams.add(inputStream);
Shuzhen Wang83bff122020-11-20 15:51:39 -08002315
2316 config.input_is_multi_resolution = mIsInputStreamMultiResolution;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317 }
2318
Shuzhen Wang99080502021-03-07 21:08:20 -08002319 mGroupIdPhysicalCameraMap.clear();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002320 bool composerSurfacePresent = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002321 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002322
2323 // Don't configure bidi streams twice, nor add them twice to the list
2324 if (mOutputStreams[i].get() ==
2325 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2326
2327 config.num_streams--;
2328 continue;
2329 }
2330
Emilian Peevf4816702020-04-03 15:44:51 -07002331 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002332 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002334 CLOGE("Can't start output stream configuration");
2335 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002336 return INVALID_OPERATION;
2337 }
2338 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002339
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002340 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002341 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2342 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002343 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2344 bufferSizes[k] = static_cast<uint32_t>(
Jayant Chowdhary6a6d3a82021-11-17 16:54:34 -08002345 getJpegBufferSize(infoPhysical(String8(outputStream->physical_camera_id)),
2346 outputStream->width, outputStream->height));
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002347 } else if (outputStream->data_space ==
2348 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2349 bufferSizes[k] = outputStream->width * outputStream->height;
2350 } else {
2351 ALOGW("%s: Blob dataSpace %d not supported",
2352 __FUNCTION__, outputStream->data_space);
2353 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002354 }
Shuzhen Wang99080502021-03-07 21:08:20 -08002355
2356 if (mOutputStreams[i]->isMultiResolution()) {
2357 int32_t streamGroupId = mOutputStreams[i]->getHalStreamGroupId();
2358 const String8& physicalCameraId = mOutputStreams[i]->getPhysicalCameraId();
2359 mGroupIdPhysicalCameraMap[streamGroupId].insert(physicalCameraId);
2360 }
Emilian Peeve23f1d92021-09-20 14:56:01 -07002361
2362 if (outputStream->usage & GraphicBuffer::USAGE_HW_COMPOSER) {
2363 composerSurfacePresent = true;
2364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002365 }
2366
2367 config.streams = streams.editArray();
2368
2369 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002370 // max_buffers, usage, and priv fields, as well as data_space and format
2371 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002372
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002373 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002374 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002375 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002376
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002377 if (res == BAD_VALUE) {
2378 // HAL rejected this set of streams as unsupported, clean up config
2379 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002380 CLOGE("Set of requested inputs/outputs not supported by HAL");
2381 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002382 return BAD_VALUE;
2383 } else if (res != OK) {
2384 // Some other kind of error from configure_streams - this is not
2385 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002386 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2387 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 return res;
2389 }
2390
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002391 // Finish all stream configuration immediately.
2392 // TODO: Try to relax this later back to lazy completion, which should be
2393 // faster
2394
Igor Murashkin073f8572013-05-02 14:59:28 -07002395 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002396 bool streamReConfigured = false;
2397 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002398 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002399 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002400 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002401 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002402 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2403 return DEAD_OBJECT;
2404 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002405 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002406 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002407 if (streamReConfigured) {
2408 mInterface->onStreamReConfigured(mInputStream->getId());
2409 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002410 }
2411
2412 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002413 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002414 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002415 bool streamReConfigured = false;
2416 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002417 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002418 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002419 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002420 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002421 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2422 return DEAD_OBJECT;
2423 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002424 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002425 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002426 if (streamReConfigured) {
2427 mInterface->onStreamReConfigured(outputStream->getId());
2428 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002429 }
2430 }
2431
Emilian Peeve23f1d92021-09-20 14:56:01 -07002432 mRequestThread->setComposerSurface(composerSurfacePresent);
2433
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434 // Request thread needs to know to avoid using repeat-last-settings protocol
2435 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002436 if (notifyRequestThread) {
Shuzhen Wang99080502021-03-07 21:08:20 -08002437 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration,
2438 sessionParams, mGroupIdPhysicalCameraMap);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002439 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440
Zhijun He90f7c372016-08-16 16:19:43 -07002441 char value[PROPERTY_VALUE_MAX];
2442 property_get("camera.fifo.disable", value, "0");
2443 int32_t disableFifo = atoi(value);
2444 if (disableFifo != 1) {
2445 // Boost priority of request thread to SCHED_FIFO.
2446 pid_t requestThreadTid = mRequestThread->getTid();
2447 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002448 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002449 if (res != OK) {
2450 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2451 strerror(-res), res);
2452 } else {
2453 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2454 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002455 }
2456
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002457 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002458 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2459 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2460 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2461 sessionParams.unlock(newSessionParams);
2462 mSessionParams.unlock(currentSessionParams);
2463 if (updateSessionParams) {
2464 mSessionParams = sessionParams;
2465 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002467 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002468
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002469 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002470 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002472 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002473
Zhijun He0a210512014-07-24 13:45:15 -07002474 // tear down the deleted streams after configure streams.
2475 mDeletedStreams.clear();
2476
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002477 auto rc = mPreparerThread->resume();
2478 if (rc != OK) {
2479 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2480 return rc;
2481 }
2482
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002483 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002484 mRequestBufferSM.onStreamsConfigured();
2485 }
2486
Cliff Wu3b268182021-07-06 15:44:43 +08002487 // First call injectCamera() and then run configureStreamsLocked() case:
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002488 // Since the streams configuration of the injection camera is based on the internal camera, we
Cliff Wu3b268182021-07-06 15:44:43 +08002489 // must wait until the internal camera configure streams before running the injection job to
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002490 // configure the injection streams.
2491 if (mInjectionMethods->isInjecting()) {
Cliff Wu3b268182021-07-06 15:44:43 +08002492 ALOGD("%s: Injection camera %s: Start to configure streams.",
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002493 __FUNCTION__, mInjectionMethods->getInjectedCamId().string());
2494 res = mInjectionMethods->injectCamera(config, bufferSizes);
2495 if (res != OK) {
2496 ALOGE("Can't finish inject camera process!");
2497 return res;
2498 }
Cliff Wu3b268182021-07-06 15:44:43 +08002499 } else {
2500 // First run configureStreamsLocked() and then call injectCamera() case:
2501 // If the stream configuration has been completed and camera deive is active, but the
2502 // injection camera has not been injected yet, we need to store the stream configuration of
2503 // the internal camera (because the stream configuration of the injection camera is based
2504 // on the internal camera). When injecting occurs later, this configuration can be used by
2505 // the injection camera.
2506 ALOGV("%s: The stream configuration is complete and the camera device is active, but the"
2507 " injection camera has not been injected yet.", __FUNCTION__);
2508 mInjectionMethods->storeInjectionConfig(config, bufferSizes);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08002509 }
2510
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002512}
2513
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002514status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002515 ATRACE_CALL();
2516 status_t res;
2517
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002518 if (mFakeStreamId != NO_STREAM) {
2519 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002520 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002521 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002522 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002523 return INVALID_OPERATION;
2524 }
2525
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002526 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002527
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002528 sp<Camera3OutputStreamInterface> fakeStream =
2529 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002530
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002531 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002532 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002533 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002534 return res;
2535 }
2536
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002537 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002538 mNextStreamId++;
2539
2540 return OK;
2541}
2542
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002543status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002544 ATRACE_CALL();
2545 status_t res;
2546
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002547 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548 if (mOutputStreams.size() == 1) return OK;
2549
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002551
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002552 // Ok, have a fake stream and there's at least one other output stream,
2553 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002554
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002556 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002557 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002558 return INVALID_OPERATION;
2559 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002560 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002561
2562 // Free up the stream endpoint so that it can be used by some other stream
2563 res = deletedStream->disconnect();
2564 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002565 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002566 // fall through since we want to still list the stream as deleted.
2567 }
2568 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002569 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002570
2571 return res;
2572}
2573
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002574void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002575 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002576 Mutex::Autolock l(mLock);
2577 va_list args;
2578 va_start(args, fmt);
2579
2580 setErrorStateLockedV(fmt, args);
2581
2582 va_end(args);
2583}
2584
2585void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002586 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002587 Mutex::Autolock l(mLock);
2588 setErrorStateLockedV(fmt, args);
2589}
2590
2591void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2592 va_list args;
2593 va_start(args, fmt);
2594
2595 setErrorStateLockedV(fmt, args);
2596
2597 va_end(args);
2598}
2599
2600void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002601 // Print out all error messages to log
2602 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002603 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002604
2605 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002606 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002607
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002608 mErrorCause = errorCause;
2609
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002610 if (mRequestThread != nullptr) {
2611 mRequestThread->setPaused(true);
2612 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002613 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002614
2615 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002616 sp<NotificationListener> listener = mListener.promote();
2617 if (listener != NULL) {
2618 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002619 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002620 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002621 }
2622
2623 // Save stack trace. View by dumping it later.
2624 CameraTraces::saveTrace();
2625 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002626}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002627
2628/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002629 * In-flight request management
2630 */
2631
Jianing Weicb0652e2014-03-12 18:29:36 -07002632status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002633 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002634 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang99080502021-03-07 21:08:20 -08002635 const std::set<std::set<String8>>& physicalCameraIds,
2636 bool isStillCapture, bool isZslCapture, bool rotateAndCropAuto,
2637 const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002638 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002639 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002640 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002641
2642 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002643 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002644 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002645 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002646 if (res < 0) return res;
2647
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002648 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002649 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2650 // avoid a deadlock during reprocess requests.
2651 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002652 if (mStatusTracker != nullptr) {
2653 mStatusTracker->markComponentActive(mInFlightStatusId);
2654 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002655 }
2656
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002657 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002658 return OK;
2659}
2660
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002661void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002662 // Indicate idle inFlightMap to the status tracker
2663 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002664 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002665 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2666 // avoid a deadlock during reprocess requests.
2667 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002668 if (mStatusTracker != nullptr) {
2669 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2670 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002671 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002672 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002673}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002674
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002675void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002676 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002677 // something has likely gone wrong. This might still be legit only if application send in
2678 // a long burst of long exposure requests.
2679 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2680 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2681 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2682 mInFlightMap.size(), mExpectedInflightDuration);
2683 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2684 kInFlightWarnLimitHighSpeed) {
2685 CLOGW("In-flight list too large for high speed configuration: %zu,"
2686 "total inflight duration %" PRIu64,
2687 mInFlightMap.size(), mExpectedInflightDuration);
2688 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002689 }
2690}
2691
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002692void Camera3Device::onInflightMapFlushedLocked() {
2693 mExpectedInflightDuration = 0;
2694}
2695
2696void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002697 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002698 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2699 mInFlightMap.removeItemsAt(idx, 1);
2700
2701 onInflightEntryRemovedLocked(duration);
2702}
2703
2704
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002705void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002706 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002707 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002708 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002709 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002710 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002711 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002712
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002713 FlushInflightReqStates states {
2714 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002715 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002716
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002717 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002718}
2719
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002720CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002721 ALOGV("%s", __FUNCTION__);
2722
Igor Murashkin1e479c02013-09-06 16:55:14 -07002723 CameraMetadata retVal;
2724
2725 if (mRequestThread != NULL) {
2726 retVal = mRequestThread->getLatestRequest();
2727 }
2728
Igor Murashkin1e479c02013-09-06 16:55:14 -07002729 return retVal;
2730}
2731
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002732void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002733 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07002734 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002735 const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers,
2736 int32_t inputStreamId) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002737
2738 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07002739 physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002740}
2741
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002742/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002743 * HalInterface inner class methods
2744 */
2745
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002746void Camera3Device::HalInterface::cleanupNativeHandles(
2747 std::vector<native_handle_t*> *handles, bool closeFd) {
2748 if (handles == nullptr) {
2749 return;
2750 }
2751 if (closeFd) {
2752 for (auto& handle : *handles) {
2753 native_handle_close(handle);
2754 }
2755 }
2756 for (auto& handle : *handles) {
2757 native_handle_delete(handle);
2758 }
2759 handles->clear();
2760 return;
2761}
2762
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002763void Camera3Device::HalInterface::getInflightBufferKeys(
2764 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002765 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002766 return;
2767}
2768
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002769void Camera3Device::HalInterface::getInflightRequestBufferKeys(
2770 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002771 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002772 return;
2773}
2774
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002775bool Camera3Device::HalInterface::verifyBufferIds(
2776 int32_t streamId, std::vector<uint64_t>& bufIds) {
2777 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002778}
2779
2780status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08002781 int32_t frameNumber, int32_t streamId,
2782 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002783 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07002784}
2785
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002786status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002787 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002788 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002789}
2790
2791// Find and pop a buffer_handle_t based on bufferId
2792status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08002793 uint64_t bufferId,
2794 /*out*/ buffer_handle_t** buffer,
2795 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002796 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002797}
2798
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002799std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
2800 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002801 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08002802}
2803
Shuzhen Wangcd5b1822021-09-07 11:52:48 -07002804uint64_t Camera3Device::HalInterface::removeOneBufferCache(int streamId,
2805 const native_handle_t* handle) {
2806 return mBufferRecords.removeOneBufferCache(streamId, handle);
2807}
2808
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002809void Camera3Device::HalInterface::onBufferFreed(
2810 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002811 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
2812 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2813 if (bufferId != BUFFER_ID_NO_BUFFER) {
2814 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002815 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07002816}
2817
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002818void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002819 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
2820 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
2821 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002822 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
2823 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002824}
2825
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002826/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 * RequestThread inner class methods
2828 */
2829
2830Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002831 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002832 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002833 bool useHalBufManager,
2834 bool supportCameraMute) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002835 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002836 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002837 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002838 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07002839 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002840 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07002841 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002842 mReconfigured(false),
2843 mDoPause(false),
2844 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002845 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002846 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07002847 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07002848 mCurrentAfTriggerId(0),
2849 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002850 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Emilian Peeve23f1d92021-09-20 14:56:01 -07002851 mComposerOutput(false),
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07002852 mCameraMute(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF),
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002853 mCameraMuteChanged(false),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002854 mRepeatingLastFrameNumber(
2855 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07002856 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002857 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002858 mRequestLatency(kRequestLatencyBinSize),
2859 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002860 mLatestSessionParams(sessionParamKeys.size()),
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07002861 mUseHalBufManager(useHalBufManager),
2862 mSupportCameraMute(supportCameraMute){
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07002863 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002864}
2865
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002866Camera3Device::RequestThread::~RequestThread() {}
2867
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002868void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002869 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002870 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002871 Mutex::Autolock l(mRequestLock);
2872 mListener = listener;
2873}
2874
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002875void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
Shuzhen Wang99080502021-03-07 21:08:20 -08002876 const CameraMetadata& sessionParams,
2877 const std::map<int32_t, std::set<String8>>& groupIdPhysicalCameraMap) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002878 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002879 Mutex::Autolock l(mRequestLock);
2880 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002881 mLatestSessionParams = sessionParams;
Shuzhen Wang99080502021-03-07 21:08:20 -08002882 mGroupIdPhysicalCameraMap = groupIdPhysicalCameraMap;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07002883 // Prepare video stream for high speed recording.
2884 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01002885 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886}
2887
Jianing Wei90e59c92014-03-12 18:29:36 -07002888status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002889 List<sp<CaptureRequest> > &requests,
2890 /*out*/
2891 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002892 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07002893 Mutex::Autolock l(mRequestLock);
2894 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2895 ++it) {
2896 mRequestQueue.push_back(*it);
2897 }
2898
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002899 if (lastFrameNumber != NULL) {
2900 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2901 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2902 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2903 *lastFrameNumber);
2904 }
Jianing Weicb0652e2014-03-12 18:29:36 -07002905
Jianing Wei90e59c92014-03-12 18:29:36 -07002906 unpauseForNewRequests();
2907
2908 return OK;
2909}
2910
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002911
2912status_t Camera3Device::RequestThread::queueTrigger(
2913 RequestTrigger trigger[],
2914 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002915 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002916 Mutex::Autolock l(mTriggerMutex);
2917 status_t ret;
2918
2919 for (size_t i = 0; i < count; ++i) {
2920 ret = queueTriggerLocked(trigger[i]);
2921
2922 if (ret != OK) {
2923 return ret;
2924 }
2925 }
2926
2927 return OK;
2928}
2929
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002930const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2931 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002932 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002933 if (d != nullptr) return d->mId;
2934 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002935}
2936
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002937status_t Camera3Device::RequestThread::queueTriggerLocked(
2938 RequestTrigger trigger) {
2939
2940 uint32_t tag = trigger.metadataTag;
2941 ssize_t index = mTriggerMap.indexOfKey(tag);
2942
2943 switch (trigger.getTagType()) {
2944 case TYPE_BYTE:
2945 // fall-through
2946 case TYPE_INT32:
2947 break;
2948 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002949 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2950 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002951 return INVALID_OPERATION;
2952 }
2953
2954 /**
2955 * Collect only the latest trigger, since we only have 1 field
2956 * in the request settings per trigger tag, and can't send more than 1
2957 * trigger per request.
2958 */
2959 if (index != NAME_NOT_FOUND) {
2960 mTriggerMap.editValueAt(index) = trigger;
2961 } else {
2962 mTriggerMap.add(tag, trigger);
2963 }
2964
2965 return OK;
2966}
2967
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002968status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002969 const RequestList &requests,
2970 /*out*/
2971 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002972 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002973 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002974 if (lastFrameNumber != NULL) {
2975 *lastFrameNumber = mRepeatingLastFrameNumber;
2976 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002978 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002979 mRepeatingRequests.insert(mRepeatingRequests.begin(),
2980 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07002981
2982 unpauseForNewRequests();
2983
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002984 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002985 return OK;
2986}
2987
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07002988bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07002989 if (mRepeatingRequests.empty()) {
2990 return false;
2991 }
2992 int32_t requestId = requestIn->mResultExtras.requestId;
2993 const RequestList &repeatRequests = mRepeatingRequests;
2994 // All repeating requests are guaranteed to have same id so only check first quest
2995 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2996 return (firstRequest->mResultExtras.requestId == requestId);
2997}
2998
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07002999status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003000 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003001 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003002 return clearRepeatingRequestsLocked(lastFrameNumber);
3003
3004}
3005
3006status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Emilian Peev2295df72021-11-12 18:14:10 -08003007 std::vector<int32_t> streamIds;
3008 for (const auto& request : mRepeatingRequests) {
3009 for (const auto& stream : request->mOutputStreams) {
3010 streamIds.push_back(stream->getId());
3011 }
3012 }
3013
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003014 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003015 if (lastFrameNumber != NULL) {
3016 *lastFrameNumber = mRepeatingLastFrameNumber;
3017 }
Emilian Peev2295df72021-11-12 18:14:10 -08003018
3019 mInterface->repeatingRequestEnd(mRepeatingLastFrameNumber, streamIds);
3020
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003021 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003022 return OK;
3023}
3024
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003025status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003026 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003027 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003028 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003029 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003030
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003031 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003032
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003033 // Send errors for all requests pending in the request queue, including
3034 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003035 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003036 if (listener != NULL) {
3037 for (RequestList::iterator it = mRequestQueue.begin();
3038 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003039 // Abort the input buffers for reprocess requests.
3040 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07003041 camera_stream_buffer_t inputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003042 camera3::Size inputBufferSize;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003043 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003044 &inputBufferSize, /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003045 if (res != OK) {
3046 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3047 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3048 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07003049 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003050 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3051 if (res != OK) {
3052 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3053 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3054 }
3055 }
3056 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003057 // Set the frame number this request would have had, if it
3058 // had been submitted; this frame number will not be reused.
3059 // The requestId and burstId fields were set when the request was
3060 // submitted originally (in convertMetadataListToRequestListLocked)
3061 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003062 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003063 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003064 }
3065 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003066 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003067
3068 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003069 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003070 if (lastFrameNumber != NULL) {
3071 *lastFrameNumber = mRepeatingLastFrameNumber;
3072 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003073 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003074 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003075 return OK;
3076}
3077
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003078status_t Camera3Device::RequestThread::flush() {
3079 ATRACE_CALL();
3080 Mutex::Autolock l(mFlushLock);
3081
Emilian Peev08dd2452017-04-06 16:55:14 +01003082 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003083}
3084
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003085void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003086 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003087 Mutex::Autolock l(mPauseLock);
3088 mDoPause = paused;
3089 mDoPauseSignal.signal();
3090}
3091
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003092status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3093 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003094 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003095 Mutex::Autolock l(mLatestRequestMutex);
3096 status_t res;
3097 while (mLatestRequestId != requestId) {
3098 nsecs_t startTime = systemTime();
3099
3100 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3101 if (res != OK) return res;
3102
3103 timeout -= (systemTime() - startTime);
3104 }
3105
3106 return OK;
3107}
3108
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003109void Camera3Device::RequestThread::requestExit() {
3110 // Call parent to set up shutdown
3111 Thread::requestExit();
3112 // The exit from any possible waits
3113 mDoPauseSignal.signal();
3114 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003115
3116 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3117 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003118}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003119
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003120void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003121 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003122 bool surfaceAbandoned = false;
3123 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003124 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003125 {
3126 Mutex::Autolock l(mRequestLock);
3127 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3128 // repeating requests.
3129 for (const auto& request : mRepeatingRequests) {
3130 for (const auto& s : request->mOutputStreams) {
3131 if (s->isAbandoned()) {
3132 surfaceAbandoned = true;
3133 clearRepeatingRequestsLocked(&lastFrameNumber);
3134 break;
3135 }
3136 }
3137 if (surfaceAbandoned) {
3138 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003139 }
3140 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003141 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003142 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003143
3144 if (listener != NULL && surfaceAbandoned) {
3145 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003146 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003147}
3148
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003149bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003150 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003151 status_t res;
3152 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07003153 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003154 uint32_t numRequestProcessed = 0;
3155 for (size_t i = 0; i < batchSize; i++) {
3156 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07003157 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003158 }
3159
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003160 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
3161
3162 bool triggerRemoveFailed = false;
3163 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
3164 for (size_t i = 0; i < numRequestProcessed; i++) {
3165 NextRequest& nextRequest = mNextRequests.editItemAt(i);
3166 nextRequest.submitted = true;
3167
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003168 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00003169
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003170 if (!triggerRemoveFailed) {
3171 // Remove any previously queued triggers (after unlock)
3172 status_t removeTriggerRes = removeTriggers(mPrevRequest);
3173 if (removeTriggerRes != OK) {
3174 triggerRemoveFailed = true;
3175 triggerFailedRequest = nextRequest;
3176 }
3177 }
3178 }
3179
3180 if (triggerRemoveFailed) {
3181 SET_ERR("RequestThread: Unable to remove triggers "
3182 "(capture request %d, HAL device: %s (%d)",
3183 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
3184 cleanUpFailedRequests(/*sendRequestError*/ false);
3185 return false;
3186 }
3187
3188 if (res != OK) {
3189 // Should only get a failure here for malformed requests or device-level
3190 // errors, so consider all errors fatal. Bad metadata failures should
3191 // come through notify.
3192 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
3193 mNextRequests[numRequestProcessed].halRequest.frame_number,
3194 strerror(-res), res);
3195 cleanUpFailedRequests(/*sendRequestError*/ false);
3196 return false;
3197 }
3198 return true;
3199}
3200
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003201nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
3202 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
3203 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3204 find_camera_metadata_ro_entry(request,
3205 ANDROID_CONTROL_AE_MODE,
3206 &e);
3207 if (e.count == 0) return maxExpectedDuration;
3208
3209 switch (e.data.u8[0]) {
3210 case ANDROID_CONTROL_AE_MODE_OFF:
3211 find_camera_metadata_ro_entry(request,
3212 ANDROID_SENSOR_EXPOSURE_TIME,
3213 &e);
3214 if (e.count > 0) {
3215 maxExpectedDuration = e.data.i64[0];
3216 }
3217 find_camera_metadata_ro_entry(request,
3218 ANDROID_SENSOR_FRAME_DURATION,
3219 &e);
3220 if (e.count > 0) {
3221 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
3222 }
3223 break;
3224 default:
3225 find_camera_metadata_ro_entry(request,
3226 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
3227 &e);
3228 if (e.count > 1) {
3229 maxExpectedDuration = 1e9 / e.data.u8[0];
3230 }
3231 break;
3232 }
3233
3234 return maxExpectedDuration;
3235}
3236
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003237bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
3238 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
3239 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
3240 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
3241 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
3242 return true;
3243 }
3244
3245 return false;
3246}
3247
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003248void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
3249 // Update the latest request sent to HAL
Shuzhen Wang83bff122020-11-20 15:51:39 -08003250 camera_capture_request_t& halRequest = nextRequest.halRequest;
3251 if (halRequest.settings != NULL) { // Don't update if they were unchanged
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003252 Mutex::Autolock al(mLatestRequestMutex);
3253
Shuzhen Wang83bff122020-11-20 15:51:39 -08003254 camera_metadata_t* cloned = clone_camera_metadata(halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003255 mLatestRequest.acquire(cloned);
3256
3257 mLatestPhysicalRequest.clear();
Shuzhen Wang83bff122020-11-20 15:51:39 -08003258 for (uint32_t i = 0; i < halRequest.num_physcam_settings; i++) {
3259 cloned = clone_camera_metadata(halRequest.physcam_settings[i]);
3260 mLatestPhysicalRequest.emplace(halRequest.physcam_id[i],
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003261 CameraMetadata(cloned));
3262 }
3263
3264 sp<Camera3Device> parent = mParent.promote();
3265 if (parent != NULL) {
Jayant Chowdharycd277cd2021-08-11 15:48:40 -07003266 int32_t inputStreamId = -1;
3267 if (halRequest.input_buffer != nullptr) {
3268 inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId();
3269 }
3270
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003271 parent->monitorMetadata(TagMonitor::REQUEST,
Shuzhen Wang83bff122020-11-20 15:51:39 -08003272 halRequest.frame_number,
Jayant Chowdharyc30b4c32021-08-18 11:43:16 -07003273 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers,
3274 halRequest.num_output_buffers, inputStreamId);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003275 }
3276 }
3277
Shuzhen Wang83bff122020-11-20 15:51:39 -08003278 if (halRequest.settings != NULL) {
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003279 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
Shuzhen Wang83bff122020-11-20 15:51:39 -08003280 halRequest.settings);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003281 }
3282
Shuzhen Wang83bff122020-11-20 15:51:39 -08003283 cleanupPhysicalSettings(nextRequest.captureRequest, &halRequest);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003284}
3285
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003286bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
3287 ATRACE_CALL();
3288 bool updatesDetected = false;
3289
Emilian Peev4ec17882019-01-24 17:16:58 -08003290 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003291 for (auto tag : mSessionParamKeys) {
3292 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003293 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003294
3295 if (entry.count > 0) {
3296 bool isDifferent = false;
3297 if (lastEntry.count > 0) {
3298 // Have a last value, compare to see if changed
3299 if (lastEntry.type == entry.type &&
3300 lastEntry.count == entry.count) {
3301 // Same type and count, compare values
3302 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
3303 size_t entryBytes = bytesPerValue * lastEntry.count;
3304 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
3305 if (cmp != 0) {
3306 isDifferent = true;
3307 }
3308 } else {
3309 // Count or type has changed
3310 isDifferent = true;
3311 }
3312 } else {
3313 // No last entry, so always consider to be different
3314 isDifferent = true;
3315 }
3316
3317 if (isDifferent) {
3318 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003319 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
3320 updatesDetected = true;
3321 }
Emilian Peev4ec17882019-01-24 17:16:58 -08003322 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003323 }
3324 } else if (lastEntry.count > 0) {
3325 // Value has been removed
3326 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08003327 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003328 updatesDetected = true;
3329 }
3330 }
3331
Emilian Peev4ec17882019-01-24 17:16:58 -08003332 bool reconfigureRequired;
3333 if (updatesDetected) {
3334 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
3335 updatedParams);
3336 mLatestSessionParams = updatedParams;
3337 } else {
3338 reconfigureRequired = false;
3339 }
3340
3341 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003342}
3343
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003344bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003345 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003346 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08003347 // Any function called from threadLoop() must not hold mInterfaceLock since
3348 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
3349 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003350
3351 // Handle paused state.
3352 if (waitIfPaused()) {
3353 return true;
3354 }
3355
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003356 // Wait for the next batch of requests.
3357 waitForNextRequestBatch();
3358 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003359 return true;
3360 }
3361
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003362 // Get the latest request ID, if any
3363 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003364 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00003365 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003366 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003367 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003368 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003369 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
3370 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003371 }
3372
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003373 // 'mNextRequests' will at this point contain either a set of HFR batched requests
3374 // or a single request from streaming or burst. In either case the first element
3375 // should contain the latest camera settings that we need to check for any session
3376 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00003377 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003378 res = OK;
3379
3380 //Input stream buffers are already acquired at this point so an input stream
3381 //will not be able to move to idle state unless we force it.
3382 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3383 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
3384 if (res != OK) {
3385 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
3386 cleanUpFailedRequests(/*sendRequestError*/ false);
3387 return false;
3388 }
3389 }
3390
3391 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07003392 sp<Camera3Device> parent = mParent.promote();
3393 if (parent != nullptr) {
3394 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003395 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07003396 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003397
3398 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
3399 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
3400 if (res != OK) {
3401 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
3402 cleanUpFailedRequests(/*sendRequestError*/ false);
3403 return false;
3404 }
3405 }
3406 }
3407 }
3408
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003409 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003410 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003411 if (res == TIMED_OUT) {
3412 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003413 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003414 // Check if any stream is abandoned.
3415 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003416 return true;
3417 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003418 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003419 return false;
3420 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003421
Zhijun Hecc27e112013-10-03 16:12:43 -07003422 // Inform waitUntilRequestProcessed thread of a new request ID
3423 {
3424 Mutex::Autolock al(mLatestRequestMutex);
3425
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003426 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07003427 mLatestRequestSignal.signal();
3428 }
3429
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003430 // Submit a batch of requests to HAL.
3431 // Use flush lock only when submitting multilple requests in a batch.
3432 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
3433 // which may take a long time to finish so synchronizing flush() and
3434 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
3435 // For now, only synchronize for high speed recording and we should figure something out for
3436 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003437 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003438
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003439 if (useFlushLock) {
3440 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003441 }
3442
Zhijun Hef0645c12016-08-02 00:58:11 -07003443 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003444 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07003445
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08003446 sp<Camera3Device> parent = mParent.promote();
3447 if (parent != nullptr) {
3448 parent->mRequestBufferSM.onSubmittingRequest();
3449 }
3450
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003451 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07003452 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07003453 submitRequestSuccess = sendRequestsBatch();
3454
Shuzhen Wang686f6442017-06-20 16:16:04 -07003455 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
3456 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07003457
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003458 if (useFlushLock) {
3459 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003460 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003461
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003462 // Unset as current request
3463 {
3464 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003465 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003466 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003467 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003468
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003469 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003470}
3471
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003472status_t Camera3Device::removeFwkOnlyRegionKeys(CameraMetadata *request) {
3473 static const std::array<uint32_t, 4> kFwkOnlyRegionKeys = {ANDROID_CONTROL_AF_REGIONS_SET,
3474 ANDROID_CONTROL_AE_REGIONS_SET, ANDROID_CONTROL_AWB_REGIONS_SET,
3475 ANDROID_SCALER_CROP_REGION_SET};
3476 if (request == nullptr) {
3477 ALOGE("%s request metadata nullptr", __FUNCTION__);
3478 return BAD_VALUE;
3479 }
3480 status_t res = OK;
3481 for (const auto &key : kFwkOnlyRegionKeys) {
3482 if (request->exists(key)) {
3483 res = request->erase(key);
3484 if (res != OK) {
3485 return res;
3486 }
3487 }
3488 }
3489 return OK;
3490}
3491
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003492status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003493 ATRACE_CALL();
3494
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003495 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003496 for (size_t i = 0; i < mNextRequests.size(); i++) {
3497 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003498 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07003499 camera_capture_request_t* halRequest = &nextRequest.halRequest;
3500 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003501
3502 // Prepare a request to HAL
3503 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
3504
3505 // Insert any queued triggers (before metadata is locked)
3506 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003507 if (res < 0) {
3508 SET_ERR("RequestThread: Unable to insert triggers "
3509 "(capture request %d, HAL device: %s (%d)",
3510 halRequest->frame_number, strerror(-res), res);
3511 return INVALID_OPERATION;
3512 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003513
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003514 int triggerCount = res;
3515 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
3516 mPrevTriggers = triggerCount;
3517
Emilian Peeve23f1d92021-09-20 14:56:01 -07003518 // Do not override rotate&crop for stream configurations that include
3519 // SurfaceViews(HW_COMPOSER) output. The display rotation there will be
3520 // compensated by NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY
3521 bool rotateAndCropChanged = mComposerOutput ? false :
3522 overrideAutoRotateAndCrop(captureRequest);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003523 bool testPatternChanged = overrideTestPattern(captureRequest);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003524
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003525 // If the request is the same as last, or we had triggers now or last time or
3526 // changing overrides this time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003527 bool newRequest =
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08003528 (mPrevRequest != captureRequest || triggersMixedIn ||
3529 rotateAndCropChanged || testPatternChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003530 // Request settings are all the same within one batch, so only treat the first
3531 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07003532 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00003533 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003534 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003535 /**
3536 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003537 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003538 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003539 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003540 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04003541 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003542 "(capture request %d, HAL device: %s (%d)",
3543 halRequest->frame_number, strerror(-res), res);
3544 return INVALID_OPERATION;
3545 }
3546
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003547 {
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003548 sp<Camera3Device> parent = mParent.promote();
3549 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003550 List<PhysicalCameraSettings>::iterator it;
3551 for (it = captureRequest->mSettingsList.begin();
3552 it != captureRequest->mSettingsList.end(); it++) {
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003553 if (parent->mUHRCropAndMeteringRegionMappers.find(it->cameraId) ==
3554 parent->mUHRCropAndMeteringRegionMappers.end()) {
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003555 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3556 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3557 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3558 res);
3559 return INVALID_OPERATION;
3560 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003561 continue;
3562 }
3563
3564 if (!captureRequest->mUHRCropAndMeteringRegionsUpdated) {
3565 res = parent->mUHRCropAndMeteringRegionMappers[it->cameraId].
3566 updateCaptureRequest(&(it->metadata));
3567 if (res != OK) {
3568 SET_ERR("RequestThread: Unable to correct capture requests "
3569 "for scaler crop region and metering regions for request "
3570 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3571 res);
3572 return INVALID_OPERATION;
3573 }
3574 captureRequest->mUHRCropAndMeteringRegionsUpdated = true;
Jayant Chowdhary65c9bf02021-09-03 16:44:16 +00003575 if (removeFwkOnlyRegionKeys(&(it->metadata)) != OK) {
3576 SET_ERR("RequestThread: Unable to remove fwk-only keys from request"
3577 "%d: %s (%d)", halRequest->frame_number, strerror(-res),
3578 res);
3579 return INVALID_OPERATION;
3580 }
Jayant Chowdhary9255ce02021-07-15 11:18:17 -07003581 }
3582 }
3583
3584 // Correct metadata regions for distortion correction if enabled
3585 for (it = captureRequest->mSettingsList.begin();
3586 it != captureRequest->mSettingsList.end(); it++) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003587 if (parent->mDistortionMappers.find(it->cameraId) ==
3588 parent->mDistortionMappers.end()) {
3589 continue;
3590 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003591
3592 if (!captureRequest->mDistortionCorrectionUpdated) {
3593 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
3594 &(it->metadata));
3595 if (res != OK) {
3596 SET_ERR("RequestThread: Unable to correct capture requests "
3597 "for lens distortion for request %d: %s (%d)",
3598 halRequest->frame_number, strerror(-res), res);
3599 return INVALID_OPERATION;
3600 }
3601 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003602 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003603 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003604
3605 for (it = captureRequest->mSettingsList.begin();
3606 it != captureRequest->mSettingsList.end(); it++) {
3607 if (parent->mZoomRatioMappers.find(it->cameraId) ==
3608 parent->mZoomRatioMappers.end()) {
3609 continue;
3610 }
3611
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003612 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003613 cameraIdsWithZoom.insert(it->cameraId);
3614 }
3615
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003616 if (!captureRequest->mZoomRatioUpdated) {
3617 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
3618 &(it->metadata));
3619 if (res != OK) {
3620 SET_ERR("RequestThread: Unable to correct capture requests "
3621 "for zoom ratio for request %d: %s (%d)",
3622 halRequest->frame_number, strerror(-res), res);
3623 return INVALID_OPERATION;
3624 }
3625 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003626 }
3627 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003628 if (captureRequest->mRotateAndCropAuto &&
3629 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003630 for (it = captureRequest->mSettingsList.begin();
3631 it != captureRequest->mSettingsList.end(); it++) {
3632 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
3633 if (mapper != parent->mRotateAndCropMappers.end()) {
3634 res = mapper->second.updateCaptureRequest(&(it->metadata));
3635 if (res != OK) {
3636 SET_ERR("RequestThread: Unable to correct capture requests "
3637 "for rotate-and-crop for request %d: %s (%d)",
3638 halRequest->frame_number, strerror(-res), res);
3639 return INVALID_OPERATION;
3640 }
3641 }
3642 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07003643 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003644 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003645 }
3646 }
3647
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003648 /**
3649 * The request should be presorted so accesses in HAL
3650 * are O(logn). Sidenote, sorting a sorted metadata is nop.
3651 */
Emilian Peevaebbe412018-01-15 13:53:24 +00003652 captureRequest->mSettingsList.begin()->metadata.sort();
3653 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003654 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003655 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003656 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
3657
3658 IF_ALOGV() {
3659 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
3660 find_camera_metadata_ro_entry(
3661 halRequest->settings,
3662 ANDROID_CONTROL_AF_TRIGGER,
3663 &e
3664 );
3665 if (e.count > 0) {
3666 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
3667 __FUNCTION__,
3668 halRequest->frame_number,
3669 e.data.u8[0]);
3670 }
3671 }
3672 } else {
3673 // leave request.settings NULL to indicate 'reuse latest given'
3674 ALOGVV("%s: Request settings are REUSED",
3675 __FUNCTION__);
3676 }
3677
Emilian Peevaebbe412018-01-15 13:53:24 +00003678 if (captureRequest->mSettingsList.size() > 1) {
3679 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
3680 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00003681 if (newRequest) {
3682 halRequest->physcam_settings =
3683 new const camera_metadata* [halRequest->num_physcam_settings];
3684 } else {
3685 halRequest->physcam_settings = nullptr;
3686 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003687 auto it = ++captureRequest->mSettingsList.begin();
3688 size_t i = 0;
3689 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
3690 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00003691 if (newRequest) {
3692 it->metadata.sort();
3693 halRequest->physcam_settings[i] = it->metadata.getAndLock();
3694 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003695 }
3696 }
3697
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003698 uint32_t totalNumBuffers = 0;
3699
3700 // Fill in buffers
3701 if (captureRequest->mInputStream != NULL) {
3702 halRequest->input_buffer = &captureRequest->mInputBuffer;
Shuzhen Wang83bff122020-11-20 15:51:39 -08003703
3704 halRequest->input_width = captureRequest->mInputBufferSize.width;
3705 halRequest->input_height = captureRequest->mInputBufferSize.height;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003706 totalNumBuffers += 1;
3707 } else {
3708 halRequest->input_buffer = NULL;
3709 }
3710
Emilian Peevf4816702020-04-03 15:44:51 -07003711 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003712 captureRequest->mOutputStreams.size());
3713 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang99080502021-03-07 21:08:20 -08003714 std::set<std::set<String8>> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07003715
3716 sp<Camera3Device> parent = mParent.promote();
3717 if (parent == NULL) {
3718 // Should not happen, and nowhere to send errors to, so just log it
3719 CLOGE("RequestThread: Parent is gone");
3720 return INVALID_OPERATION;
3721 }
3722 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
3723
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003724 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08003725 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003726 sp<Camera3OutputStreamInterface> outputStream =
3727 captureRequest->mOutputStreams.editItemAt(j);
3728 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003729
3730 // Prepare video buffers for high speed recording on the first video request.
3731 if (mPrepareVideoStream && outputStream->isVideoStream()) {
3732 // Only try to prepare video stream on the first video request.
3733 mPrepareVideoStream = false;
3734
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07003735 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
3736 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003737 while (res == NOT_ENOUGH_DATA) {
3738 res = outputStream->prepareNextBuffer();
3739 }
3740 if (res != OK) {
3741 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
3742 __FUNCTION__, strerror(-res), res);
3743 outputStream->cancelPrepare();
3744 }
3745 }
3746
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003747 std::vector<size_t> uniqueSurfaceIds;
3748 res = outputStream->getUniqueSurfaceIds(
3749 captureRequest->mOutputSurfaces[streamId],
3750 &uniqueSurfaceIds);
3751 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
3752 if (res != OK && res != INVALID_OPERATION) {
3753 ALOGE("%s: failed to query stream %d unique surface IDs",
3754 __FUNCTION__, streamId);
3755 return res;
3756 }
3757 if (res == OK) {
3758 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
3759 }
3760
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003761 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003762 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003763 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08003764 return TIMED_OUT;
3765 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003766 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07003767 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003768 buffer.stream = outputStream->asHalStream();
3769 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07003770 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003771 buffer.acquire_fence = -1;
3772 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08003773 // Mark the output stream as unpreparable to block clients from calling
3774 // 'prepare' after this request reaches CameraHal and before the respective
3775 // buffers are requested.
3776 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003777 } else {
3778 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
3779 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003780 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003781 if (res != OK) {
3782 // Can't get output buffer from gralloc queue - this could be due to
3783 // abandoned queue or other consumer misbehavior, so not a fatal
3784 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003785 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003786 " %s (%d)", strerror(-res), res);
3787
3788 return TIMED_OUT;
3789 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003790 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08003791
3792 {
3793 sp<Camera3Device> parent = mParent.promote();
3794 if (parent != nullptr) {
3795 const String8& streamCameraId = outputStream->getPhysicalCameraId();
3796 for (const auto& settings : captureRequest->mSettingsList) {
3797 if ((streamCameraId.isEmpty() &&
3798 parent->getId() == settings.cameraId.c_str()) ||
3799 streamCameraId == settings.cameraId.c_str()) {
3800 outputStream->fireBufferRequestForFrameNumber(
3801 captureRequest->mResultExtras.frameNumber,
3802 settings.metadata);
3803 }
3804 }
3805 }
3806 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07003807
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003808 String8 physicalCameraId = outputStream->getPhysicalCameraId();
Shuzhen Wang99080502021-03-07 21:08:20 -08003809 int32_t streamGroupId = outputStream->getHalStreamGroupId();
3810 if (streamGroupId != -1 && mGroupIdPhysicalCameraMap.count(streamGroupId) == 1) {
3811 requestedPhysicalCameras.insert(mGroupIdPhysicalCameraMap[streamGroupId]);
3812 } else if (!physicalCameraId.isEmpty()) {
3813 requestedPhysicalCameras.insert(std::set<String8>({physicalCameraId}));
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003814 }
3815 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003816 }
3817 totalNumBuffers += halRequest->num_output_buffers;
3818
3819 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08003820 // If this request list is for constrained high speed recording (not
3821 // preview), and the current request is not the last one in the batch,
3822 // do not send callback to the app.
3823 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07003824 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08003825 hasCallback = false;
3826 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003827 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003828 bool isZslCapture = false;
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003829 const camera_metadata_t* settings = halRequest->settings;
3830 bool shouldUnlockSettings = false;
3831 if (settings == nullptr) {
3832 shouldUnlockSettings = true;
3833 settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
3834 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003835 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
3836 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003837 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
Emilian Peev9dd21f42018-08-03 13:39:29 +01003838 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
3839 isStillCapture = true;
3840 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
3841 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003842
Emilian Peevaf8416e2021-02-04 17:52:43 -08003843 e = camera_metadata_ro_entry_t();
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003844 find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003845 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
3846 isZslCapture = true;
3847 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01003848 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003849 res = parent->registerInFlight(halRequest->frame_number,
3850 totalNumBuffers, captureRequest->mResultExtras,
3851 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003852 hasCallback,
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003853 calculateMaxExpectedDuration(settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003854 requestedPhysicalCameras, isStillCapture, isZslCapture,
3855 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003856 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07003857 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003858 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
3859 ", burstId = %" PRId32 ".",
3860 __FUNCTION__,
3861 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
3862 captureRequest->mResultExtras.burstId);
Yin-Chia Yehf7057ca2020-11-16 14:11:40 -08003863
3864 if (shouldUnlockSettings) {
3865 captureRequest->mSettingsList.begin()->metadata.unlock(settings);
3866 }
3867
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003868 if (res != OK) {
3869 SET_ERR("RequestThread: Unable to register new in-flight request:"
3870 " %s (%d)", strerror(-res), res);
3871 return INVALID_OPERATION;
3872 }
3873 }
3874
3875 return OK;
3876}
3877
Igor Murashkin1e479c02013-09-06 16:55:14 -07003878CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003879 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07003880 Mutex::Autolock al(mLatestRequestMutex);
3881
3882 ALOGV("RequestThread::%s", __FUNCTION__);
3883
3884 return mLatestRequest;
3885}
3886
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003887bool Camera3Device::RequestThread::isStreamPending(
3888 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003889 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003890 Mutex::Autolock l(mRequestLock);
3891
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003892 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07003893 if (!nextRequest.submitted) {
3894 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
3895 if (stream == s) return true;
3896 }
3897 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003898 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07003899 }
3900
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003901 for (const auto& request : mRequestQueue) {
3902 for (const auto& s : request->mOutputStreams) {
3903 if (stream == s) return true;
3904 }
3905 if (stream == request->mInputStream) return true;
3906 }
3907
3908 for (const auto& request : mRepeatingRequests) {
3909 for (const auto& s : request->mOutputStreams) {
3910 if (stream == s) return true;
3911 }
3912 if (stream == request->mInputStream) return true;
3913 }
3914
3915 return false;
3916}
Jianing Weicb0652e2014-03-12 18:29:36 -07003917
Emilian Peev40ead602017-09-26 15:46:36 +01003918bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
3919 ATRACE_CALL();
3920 Mutex::Autolock l(mRequestLock);
3921
3922 for (const auto& nextRequest : mNextRequests) {
3923 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
3924 if (s.first == streamId) {
3925 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3926 if (it != s.second.end()) {
3927 return true;
3928 }
3929 }
3930 }
3931 }
3932
3933 for (const auto& request : mRequestQueue) {
3934 for (const auto& s : request->mOutputSurfaces) {
3935 if (s.first == streamId) {
3936 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3937 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003938 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003939 }
3940 }
3941 }
3942 }
3943
3944 for (const auto& request : mRepeatingRequests) {
3945 for (const auto& s : request->mOutputSurfaces) {
3946 if (s.first == streamId) {
3947 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
3948 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003949 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01003950 }
3951 }
3952 }
3953 }
3954
3955 return false;
3956}
3957
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003958void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
3959 if (!mUseHalBufManager) {
3960 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
3961 return;
3962 }
3963
3964 Mutex::Autolock pl(mPauseLock);
3965 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003966 mInterface->signalPipelineDrain(streamIds);
3967 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003968 }
3969 // If request thread is still busy, wait until paused then notify HAL
3970 mNotifyPipelineDrain = true;
3971 mStreamIdsToBeDrained = streamIds;
3972}
3973
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07003974void Camera3Device::RequestThread::resetPipelineDrain() {
3975 Mutex::Autolock pl(mPauseLock);
3976 mNotifyPipelineDrain = false;
3977 mStreamIdsToBeDrained.clear();
3978}
3979
Emilian Peevc0fe54c2020-03-11 14:05:07 -07003980void Camera3Device::RequestThread::clearPreviousRequest() {
3981 Mutex::Autolock l(mRequestLock);
3982 mPrevRequest.clear();
3983}
3984
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003985status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
3986 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
3987 ATRACE_CALL();
3988 Mutex::Autolock l(mTriggerMutex);
3989 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
3990 return BAD_VALUE;
3991 }
3992 mRotateAndCropOverride = rotateAndCropValue;
3993 return OK;
3994}
3995
Emilian Peeve23f1d92021-09-20 14:56:01 -07003996status_t Camera3Device::RequestThread::setComposerSurface(bool composerSurfacePresent) {
3997 ATRACE_CALL();
3998 Mutex::Autolock l(mTriggerMutex);
3999 mComposerOutput = composerSurfacePresent;
4000 return OK;
4001}
4002
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004003status_t Camera3Device::RequestThread::setCameraMute(int32_t muteMode) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004004 ATRACE_CALL();
4005 Mutex::Autolock l(mTriggerMutex);
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07004006 if (muteMode != mCameraMute) {
4007 mCameraMute = muteMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004008 mCameraMuteChanged = true;
4009 }
4010 return OK;
4011}
4012
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004013nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004014 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004015 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004016 return mExpectedInflightDuration > kMinInflightDuration ?
4017 mExpectedInflightDuration : kMinInflightDuration;
4018}
4019
Emilian Peevaebbe412018-01-15 13:53:24 +00004020void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004021 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004022 if ((request == nullptr) || (halRequest == nullptr)) {
4023 ALOGE("%s: Invalid request!", __FUNCTION__);
4024 return;
4025 }
4026
4027 if (halRequest->num_physcam_settings > 0) {
4028 if (halRequest->physcam_id != nullptr) {
4029 delete [] halRequest->physcam_id;
4030 halRequest->physcam_id = nullptr;
4031 }
4032 if (halRequest->physcam_settings != nullptr) {
4033 auto it = ++(request->mSettingsList.begin());
4034 size_t i = 0;
4035 for (; it != request->mSettingsList.end(); it++, i++) {
4036 it->metadata.unlock(halRequest->physcam_settings[i]);
4037 }
4038 delete [] halRequest->physcam_settings;
4039 halRequest->physcam_settings = nullptr;
4040 }
4041 }
4042}
4043
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004044void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4045 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004046 return;
4047 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004048
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004049 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004050 // Skip the ones that have been submitted successfully.
4051 if (nextRequest.submitted) {
4052 continue;
4053 }
4054
4055 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004056 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4057 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004058
4059 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004060 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004061 }
4062
Emilian Peevaebbe412018-01-15 13:53:24 +00004063 cleanupPhysicalSettings(captureRequest, halRequest);
4064
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004065 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004066 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004067 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4068 }
4069
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004070 // No output buffer can be returned when using HAL buffer manager
4071 if (!mUseHalBufManager) {
4072 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4073 //Buffers that failed processing could still have
4074 //valid acquire fence.
4075 int acquireFence = (*outputBuffers)[i].acquire_fence;
4076 if (0 <= acquireFence) {
4077 close(acquireFence);
4078 outputBuffers->editItemAt(i).acquire_fence = -1;
4079 }
Emilian Peevf4816702020-04-03 15:44:51 -07004080 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang90708ea2021-11-04 11:40:49 -07004081 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i],
4082 /*timestamp*/0, /*readoutTimestamp*/0,
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004083 /*timestampIncreasing*/true, std::vector<size_t> (),
4084 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004085 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004086 }
4087
4088 if (sendRequestError) {
4089 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004090 sp<NotificationListener> listener = mListener.promote();
4091 if (listener != NULL) {
4092 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004093 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004094 captureRequest->mResultExtras);
4095 }
4096 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004097
4098 // Remove yet-to-be submitted inflight request from inflightMap
4099 {
4100 sp<Camera3Device> parent = mParent.promote();
4101 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004102 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004103 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4104 if (idx >= 0) {
4105 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4106 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4107 parent->removeInFlightMapEntryLocked(idx);
4108 }
4109 }
4110 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004111 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004112
4113 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004114 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004115}
4116
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004117void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004118 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004119 // Optimized a bit for the simple steady-state case (single repeating
4120 // request), to avoid putting that request in the queue temporarily.
4121 Mutex::Autolock l(mRequestLock);
4122
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004123 assert(mNextRequests.empty());
4124
4125 NextRequest nextRequest;
4126 nextRequest.captureRequest = waitForNextRequestLocked();
4127 if (nextRequest.captureRequest == nullptr) {
4128 return;
4129 }
4130
Emilian Peevf4816702020-04-03 15:44:51 -07004131 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004132 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004133 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004134
4135 // Wait for additional requests
4136 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4137
4138 for (size_t i = 1; i < batchSize; i++) {
4139 NextRequest additionalRequest;
4140 additionalRequest.captureRequest = waitForNextRequestLocked();
4141 if (additionalRequest.captureRequest == nullptr) {
4142 break;
4143 }
4144
Emilian Peevf4816702020-04-03 15:44:51 -07004145 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004146 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004147 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004148 }
4149
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004150 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004151 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004152 mNextRequests.size(), batchSize);
4153 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004154 }
4155
4156 return;
4157}
4158
4159sp<Camera3Device::CaptureRequest>
4160 Camera3Device::RequestThread::waitForNextRequestLocked() {
4161 status_t res;
4162 sp<CaptureRequest> nextRequest;
4163
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004164 while (mRequestQueue.empty()) {
4165 if (!mRepeatingRequests.empty()) {
4166 // Always atomically enqueue all requests in a repeating request
4167 // list. Guarantees a complete in-sequence set of captures to
4168 // application.
4169 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07004170 if (mFirstRepeating) {
4171 mFirstRepeating = false;
4172 } else {
4173 for (auto& request : requests) {
4174 // For repeating requests, override timestamp request using
4175 // the time a request is inserted into the request queue,
4176 // because the original repeating request will have an old
4177 // fixed timestamp.
4178 request->mRequestTimeNs = systemTime();
4179 }
4180 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004181 RequestList::const_iterator firstRequest =
4182 requests.begin();
4183 nextRequest = *firstRequest;
4184 mRequestQueue.insert(mRequestQueue.end(),
4185 ++firstRequest,
4186 requests.end());
4187 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004188
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004189 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004190
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004191 break;
4192 }
4193
4194 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004196 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4197 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004198 Mutex::Autolock pl(mPauseLock);
4199 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004200 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004201 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004202 if (mNotifyPipelineDrain) {
4203 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4204 mNotifyPipelineDrain = false;
4205 mStreamIdsToBeDrained.clear();
4206 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004207 // Let the tracker know
4208 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4209 if (statusTracker != 0) {
4210 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4211 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004212 sp<Camera3Device> parent = mParent.promote();
4213 if (parent != nullptr) {
4214 parent->mRequestBufferSM.onRequestThreadPaused();
4215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004216 }
4217 // Stop waiting for now and let thread management happen
4218 return NULL;
4219 }
4220 }
4221
4222 if (nextRequest == NULL) {
4223 // Don't have a repeating request already in hand, so queue
4224 // must have an entry now.
4225 RequestList::iterator firstRequest =
4226 mRequestQueue.begin();
4227 nextRequest = *firstRequest;
4228 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07004229 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
4230 sp<NotificationListener> listener = mListener.promote();
4231 if (listener != NULL) {
4232 listener->notifyRequestQueueEmpty();
4233 }
4234 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004235 }
4236
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004237 // In case we've been unpaused by setPaused clearing mDoPause, need to
4238 // update internal pause state (capture/setRepeatingRequest unpause
4239 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004240 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004241 if (mPaused) {
4242 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
4243 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4244 if (statusTracker != 0) {
4245 statusTracker->markComponentActive(mStatusId);
4246 }
4247 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248 mPaused = false;
4249
4250 // Check if we've reconfigured since last time, and reset the preview
4251 // request if so. Can't use 'NULL request == repeat' across configure calls.
4252 if (mReconfigured) {
4253 mPrevRequest.clear();
4254 mReconfigured = false;
4255 }
4256
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004257 if (nextRequest != NULL) {
4258 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004259 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
4260 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004261
4262 // Since RequestThread::clear() removes buffers from the input stream,
4263 // get the right buffer here before unlocking mRequestLock
4264 if (nextRequest->mInputStream != NULL) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08004265 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer,
4266 &nextRequest->mInputBufferSize);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004267 if (res != OK) {
4268 // Can't get input buffer from gralloc queue - this could be due to
4269 // disconnected queue or other producer misbehavior, so not a fatal
4270 // error
4271 ALOGE("%s: Can't get input buffer, skipping request:"
4272 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004273
4274 sp<NotificationListener> listener = mListener.promote();
4275 if (listener != NULL) {
4276 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004277 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004278 nextRequest->mResultExtras);
4279 }
4280 return NULL;
4281 }
4282 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004283 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07004284
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004285 return nextRequest;
4286}
4287
4288bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004289 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004290 status_t res;
4291 Mutex::Autolock l(mPauseLock);
4292 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004293 if (mPaused == false) {
4294 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004295 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004296 if (mNotifyPipelineDrain) {
4297 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4298 mNotifyPipelineDrain = false;
4299 mStreamIdsToBeDrained.clear();
4300 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004301 // Let the tracker know
4302 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4303 if (statusTracker != 0) {
4304 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4305 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004306 sp<Camera3Device> parent = mParent.promote();
4307 if (parent != nullptr) {
4308 parent->mRequestBufferSM.onRequestThreadPaused();
4309 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004310 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004311
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004313 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004314 return true;
4315 }
4316 }
4317 // We don't set mPaused to false here, because waitForNextRequest needs
4318 // to further manage the paused state in case of starvation.
4319 return false;
4320}
4321
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004322void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004323 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004324 // With work to do, mark thread as unpaused.
4325 // If paused by request (setPaused), don't resume, to avoid
4326 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004327 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004328 Mutex::Autolock p(mPauseLock);
4329 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004330 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
4331 if (mPaused) {
4332 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4333 if (statusTracker != 0) {
4334 statusTracker->markComponentActive(mStatusId);
4335 }
4336 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004337 mPaused = false;
4338 }
4339}
4340
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07004341void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
4342 sp<Camera3Device> parent = mParent.promote();
4343 if (parent != NULL) {
4344 va_list args;
4345 va_start(args, fmt);
4346
4347 parent->setErrorStateV(fmt, args);
4348
4349 va_end(args);
4350 }
4351}
4352
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004353status_t Camera3Device::RequestThread::insertTriggers(
4354 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004355 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004356 Mutex::Autolock al(mTriggerMutex);
4357
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004358 sp<Camera3Device> parent = mParent.promote();
4359 if (parent == NULL) {
4360 CLOGE("RequestThread: Parent is gone");
4361 return DEAD_OBJECT;
4362 }
4363
Emilian Peevaebbe412018-01-15 13:53:24 +00004364 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004365 size_t count = mTriggerMap.size();
4366
4367 for (size_t i = 0; i < count; ++i) {
4368 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004369 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004370
4371 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
4372 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
4373 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004374 if (isAeTrigger) {
4375 request->mResultExtras.precaptureTriggerId = triggerId;
4376 mCurrentPreCaptureTriggerId = triggerId;
4377 } else {
4378 request->mResultExtras.afTriggerId = triggerId;
4379 mCurrentAfTriggerId = triggerId;
4380 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01004381 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07004382 }
4383
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004384 camera_metadata_entry entry = metadata.find(tag);
4385
4386 if (entry.count > 0) {
4387 /**
4388 * Already has an entry for this trigger in the request.
4389 * Rewrite it with our requested trigger value.
4390 */
4391 RequestTrigger oldTrigger = trigger;
4392
4393 oldTrigger.entryValue = entry.data.u8[0];
4394
4395 mTriggerReplacedMap.add(tag, oldTrigger);
4396 } else {
4397 /**
4398 * More typical, no trigger entry, so we just add it
4399 */
4400 mTriggerRemovedMap.add(tag, trigger);
4401 }
4402
4403 status_t res;
4404
4405 switch (trigger.getTagType()) {
4406 case TYPE_BYTE: {
4407 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4408 res = metadata.update(tag,
4409 &entryValue,
4410 /*count*/1);
4411 break;
4412 }
4413 case TYPE_INT32:
4414 res = metadata.update(tag,
4415 &trigger.entryValue,
4416 /*count*/1);
4417 break;
4418 default:
4419 ALOGE("%s: Type not supported: 0x%x",
4420 __FUNCTION__,
4421 trigger.getTagType());
4422 return INVALID_OPERATION;
4423 }
4424
4425 if (res != OK) {
4426 ALOGE("%s: Failed to update request metadata with trigger tag %s"
4427 ", value %d", __FUNCTION__, trigger.getTagName(),
4428 trigger.entryValue);
4429 return res;
4430 }
4431
4432 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
4433 trigger.getTagName(),
4434 trigger.entryValue);
4435 }
4436
4437 mTriggerMap.clear();
4438
4439 return count;
4440}
4441
4442status_t Camera3Device::RequestThread::removeTriggers(
4443 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004444 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004445 Mutex::Autolock al(mTriggerMutex);
4446
Emilian Peevaebbe412018-01-15 13:53:24 +00004447 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004448
4449 /**
4450 * Replace all old entries with their old values.
4451 */
4452 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
4453 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
4454
4455 status_t res;
4456
4457 uint32_t tag = trigger.metadataTag;
4458 switch (trigger.getTagType()) {
4459 case TYPE_BYTE: {
4460 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
4461 res = metadata.update(tag,
4462 &entryValue,
4463 /*count*/1);
4464 break;
4465 }
4466 case TYPE_INT32:
4467 res = metadata.update(tag,
4468 &trigger.entryValue,
4469 /*count*/1);
4470 break;
4471 default:
4472 ALOGE("%s: Type not supported: 0x%x",
4473 __FUNCTION__,
4474 trigger.getTagType());
4475 return INVALID_OPERATION;
4476 }
4477
4478 if (res != OK) {
4479 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
4480 ", trigger value %d", __FUNCTION__,
4481 trigger.getTagName(), trigger.entryValue);
4482 return res;
4483 }
4484 }
4485 mTriggerReplacedMap.clear();
4486
4487 /**
4488 * Remove all new entries.
4489 */
4490 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
4491 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
4492 status_t res = metadata.erase(trigger.metadataTag);
4493
4494 if (res != OK) {
4495 ALOGE("%s: Failed to erase metadata with trigger tag %s"
4496 ", trigger value %d", __FUNCTION__,
4497 trigger.getTagName(), trigger.entryValue);
4498 return res;
4499 }
4500 }
4501 mTriggerRemovedMap.clear();
4502
4503 return OK;
4504}
4505
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004506status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004507 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004508 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004509 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004510 status_t res;
4511
Emilian Peevaebbe412018-01-15 13:53:24 +00004512 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004513
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004514 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004515 // exists
4516 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
4517 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
4518 if (afTrigger.count > 0 &&
4519 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
4520 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004521 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004522 if (res != OK) return res;
4523 }
4524
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004525 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004526 // if none already exists
4527 camera_metadata_entry pcTrigger =
4528 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
4529 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
4530 if (pcTrigger.count > 0 &&
4531 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
4532 pcId.count == 0) {
4533 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004534 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07004535 if (res != OK) return res;
4536 }
4537
4538 return OK;
4539}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004540
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004541bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
4542 const sp<CaptureRequest> &request) {
4543 ATRACE_CALL();
4544
4545 if (request->mRotateAndCropAuto) {
4546 Mutex::Autolock l(mTriggerMutex);
4547 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
4548
4549 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
4550 if (rotateAndCropEntry.count > 0) {
4551 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
4552 return false;
4553 } else {
4554 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
4555 return true;
4556 }
4557 } else {
4558 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
4559 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
4560 &rotateAndCrop_u8, 1);
4561 return true;
4562 }
4563 }
4564 return false;
4565}
4566
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004567bool Camera3Device::RequestThread::overrideTestPattern(
4568 const sp<CaptureRequest> &request) {
4569 ATRACE_CALL();
4570
Eino-Ville Talvala1646c3c2021-07-29 13:48:40 -07004571 if (!mSupportCameraMute) return false;
Eino-Ville Talvalac2459842021-07-22 16:36:36 -07004572
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004573 Mutex::Autolock l(mTriggerMutex);
4574
4575 bool changed = false;
4576
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004577 // For a multi-camera, the physical cameras support the same set of
4578 // test pattern modes as the logical camera.
4579 for (auto& settings : request->mSettingsList) {
4580 CameraMetadata &metadata = settings.metadata;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004581
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004582 int32_t testPatternMode = settings.mOriginalTestPatternMode;
4583 int32_t testPatternData[4] = {
4584 settings.mOriginalTestPatternData[0],
4585 settings.mOriginalTestPatternData[1],
4586 settings.mOriginalTestPatternData[2],
4587 settings.mOriginalTestPatternData[3]
4588 };
4589 if (mCameraMute != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) {
4590 testPatternMode = mCameraMute;
4591 testPatternData[0] = 0;
4592 testPatternData[1] = 0;
4593 testPatternData[2] = 0;
4594 testPatternData[3] = 0;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004595 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004596
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004597 auto testPatternEntry = metadata.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
4598 bool supportTestPatternModeKey = settings.mHasTestPatternModeTag;
4599 if (testPatternEntry.count > 0) {
4600 if (testPatternEntry.data.i32[0] != testPatternMode) {
4601 testPatternEntry.data.i32[0] = testPatternMode;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004602 changed = true;
4603 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004604 } else if (supportTestPatternModeKey) {
4605 metadata.update(ANDROID_SENSOR_TEST_PATTERN_MODE,
4606 &testPatternMode, 1);
4607 changed = true;
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004608 }
Shuzhen Wang911c6a32021-10-27 13:36:03 -07004609
4610 auto testPatternColor = metadata.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
4611 bool supportTestPatternDataKey = settings.mHasTestPatternDataTag;
4612 if (testPatternColor.count >= 4) {
4613 for (size_t i = 0; i < 4; i++) {
4614 if (testPatternColor.data.i32[i] != testPatternData[i]) {
4615 testPatternColor.data.i32[i] = testPatternData[i];
4616 changed = true;
4617 }
4618 }
4619 } else if (supportTestPatternDataKey) {
4620 metadata.update(ANDROID_SENSOR_TEST_PATTERN_DATA,
4621 testPatternData, 4);
4622 changed = true;
4623 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004624 }
4625
4626 return changed;
4627}
4628
Cliff Wuc2ad9c82021-04-21 00:58:58 +08004629status_t Camera3Device::RequestThread::setHalInterface(
4630 sp<HalInterface> newHalInterface) {
4631 if (newHalInterface.get() == nullptr) {
4632 ALOGE("%s: The newHalInterface does not exist!", __FUNCTION__);
4633 return DEAD_OBJECT;
4634 }
4635
4636 mInterface = newHalInterface;
4637
4638 return OK;
4639}
4640
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004641/**
4642 * PreparerThread inner class methods
4643 */
4644
4645Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004646 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004647 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004648}
4649
4650Camera3Device::PreparerThread::~PreparerThread() {
4651 Thread::requestExitAndWait();
4652 if (mCurrentStream != nullptr) {
4653 mCurrentStream->cancelPrepare();
4654 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4655 mCurrentStream.clear();
4656 }
4657 clear();
4658}
4659
Ruben Brunkc78ac262015-08-13 17:58:46 -07004660status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004661 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004662 status_t res;
4663
4664 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004665 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004666
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004667 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004668 if (res == OK) {
4669 // No preparation needed, fire listener right off
4670 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004671 if (listener != NULL) {
4672 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004673 }
4674 return OK;
4675 } else if (res != NOT_ENOUGH_DATA) {
4676 return res;
4677 }
4678
4679 // Need to prepare, start up thread if necessary
4680 if (!mActive) {
4681 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
4682 // isn't running
4683 Thread::requestExitAndWait();
4684 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4685 if (res != OK) {
4686 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004687 if (listener != NULL) {
4688 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004689 }
4690 return res;
4691 }
4692 mCancelNow = false;
4693 mActive = true;
4694 ALOGV("%s: Preparer stream started", __FUNCTION__);
4695 }
4696
4697 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004698 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004699 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
4700
4701 return OK;
4702}
4703
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004704void Camera3Device::PreparerThread::pause() {
4705 ATRACE_CALL();
4706
4707 Mutex::Autolock l(mLock);
4708
4709 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
4710 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
4711 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
4712 int currentMaxCount = mCurrentMaxCount;
4713 mPendingStreams.clear();
4714 mCancelNow = true;
4715 while (mActive) {
4716 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
4717 if (res == TIMED_OUT) {
4718 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
4719 return;
4720 } else if (res != OK) {
4721 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
4722 return;
4723 }
4724 }
4725
4726 //Check whether the prepare thread was able to complete the current
4727 //stream. In case work is still pending emplace it along with the rest
4728 //of the streams in the pending list.
4729 if (currentStream != nullptr) {
4730 if (!mCurrentPrepareComplete) {
4731 pendingStreams.emplace(currentMaxCount, currentStream);
4732 }
4733 }
4734
4735 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
4736 for (const auto& it : mPendingStreams) {
4737 it.second->cancelPrepare();
4738 }
4739}
4740
4741status_t Camera3Device::PreparerThread::resume() {
4742 ATRACE_CALL();
4743 status_t res;
4744
4745 Mutex::Autolock l(mLock);
4746 sp<NotificationListener> listener = mListener.promote();
4747
4748 if (mActive) {
4749 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
4750 return NO_INIT;
4751 }
4752
4753 auto it = mPendingStreams.begin();
4754 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004755 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004756 if (res == OK) {
4757 if (listener != NULL) {
4758 listener->notifyPrepared(it->second->getId());
4759 }
4760 it = mPendingStreams.erase(it);
4761 } else if (res != NOT_ENOUGH_DATA) {
4762 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
4763 res, strerror(-res));
4764 it = mPendingStreams.erase(it);
4765 } else {
4766 it++;
4767 }
4768 }
4769
4770 if (mPendingStreams.empty()) {
4771 return OK;
4772 }
4773
4774 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
4775 if (res != OK) {
4776 ALOGE("%s: Unable to start preparer stream: %d (%s)",
4777 __FUNCTION__, res, strerror(-res));
4778 return res;
4779 }
4780 mCancelNow = false;
4781 mActive = true;
4782 ALOGV("%s: Preparer stream started", __FUNCTION__);
4783
4784 return OK;
4785}
4786
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004787status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004788 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004789 Mutex::Autolock l(mLock);
4790
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004791 for (const auto& it : mPendingStreams) {
4792 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004793 }
4794 mPendingStreams.clear();
4795 mCancelNow = true;
4796
4797 return OK;
4798}
4799
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004800void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004801 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004802 Mutex::Autolock l(mLock);
4803 mListener = listener;
4804}
4805
4806bool Camera3Device::PreparerThread::threadLoop() {
4807 status_t res;
4808 {
4809 Mutex::Autolock l(mLock);
4810 if (mCurrentStream == nullptr) {
4811 // End thread if done with work
4812 if (mPendingStreams.empty()) {
4813 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
4814 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
4815 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
4816 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004817 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004818 return false;
4819 }
4820
4821 // Get next stream to prepare
4822 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004823 mCurrentStream = it->second;
4824 mCurrentMaxCount = it->first;
4825 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004826 mPendingStreams.erase(it);
4827 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
4828 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
4829 } else if (mCancelNow) {
4830 mCurrentStream->cancelPrepare();
4831 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4832 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
4833 mCurrentStream.clear();
4834 mCancelNow = false;
4835 return true;
4836 }
4837 }
4838
4839 res = mCurrentStream->prepareNextBuffer();
4840 if (res == NOT_ENOUGH_DATA) return true;
4841 if (res != OK) {
4842 // Something bad happened; try to recover by cancelling prepare and
4843 // signalling listener anyway
4844 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
4845 mCurrentStream->getId(), res, strerror(-res));
4846 mCurrentStream->cancelPrepare();
4847 }
4848
4849 // This stream has finished, notify listener
4850 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004851 sp<NotificationListener> listener = mListener.promote();
4852 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004853 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
4854 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004855 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004856 }
4857
4858 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
4859 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004860 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004861
4862 return true;
4863}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004864
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004865status_t Camera3Device::RequestBufferStateMachine::initialize(
4866 sp<camera3::StatusTracker> statusTracker) {
4867 if (statusTracker == nullptr) {
4868 ALOGE("%s: statusTracker is null", __FUNCTION__);
4869 return BAD_VALUE;
4870 }
4871
4872 std::lock_guard<std::mutex> lock(mLock);
4873 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07004874 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004875 return OK;
4876}
4877
4878bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
4879 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004880 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004881 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004882 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004883 return true;
4884 }
4885 return false;
4886}
4887
4888void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
4889 std::lock_guard<std::mutex> lock(mLock);
4890 if (!mRequestBufferOngoing) {
4891 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
4892 return;
4893 }
4894 mRequestBufferOngoing = false;
4895 if (mStatus == RB_STATUS_PENDING_STOP) {
4896 checkSwitchToStopLocked();
4897 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08004898 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004899}
4900
4901void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
4902 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004903 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004904 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004905 return;
4906}
4907
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004908void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004909 std::lock_guard<std::mutex> lock(mLock);
4910 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004911 // inflight map register actually happens in prepareHalRequest now, but it is close enough
4912 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004913 mInflightMapEmpty = false;
4914 if (mStatus == RB_STATUS_STOPPED) {
4915 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004916 }
4917 return;
4918}
4919
4920void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
4921 std::lock_guard<std::mutex> lock(mLock);
4922 mRequestThreadPaused = true;
4923 if (mStatus == RB_STATUS_PENDING_STOP) {
4924 checkSwitchToStopLocked();
4925 }
4926 return;
4927}
4928
4929void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
4930 std::lock_guard<std::mutex> lock(mLock);
4931 mInflightMapEmpty = true;
4932 if (mStatus == RB_STATUS_PENDING_STOP) {
4933 checkSwitchToStopLocked();
4934 }
4935 return;
4936}
4937
4938void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
4939 std::lock_guard<std::mutex> lock(mLock);
4940 if (!checkSwitchToStopLocked()) {
4941 mStatus = RB_STATUS_PENDING_STOP;
4942 }
4943 return;
4944}
4945
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004946bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
4947 std::lock_guard<std::mutex> lock(mLock);
4948 if (mRequestBufferOngoing) {
4949 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
4950 __FUNCTION__);
4951 return false;
4952 }
4953 mSwitchedToOffline = true;
4954 mInflightMapEmpty = true;
4955 mRequestThreadPaused = true;
4956 mStatus = RB_STATUS_STOPPED;
4957 return true;
4958}
4959
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004960void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
4961 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4962 if (statusTracker != nullptr) {
4963 if (active) {
4964 statusTracker->markComponentActive(mRequestBufferStatusId);
4965 } else {
4966 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
4967 }
4968 }
4969}
4970
4971bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
4972 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
4973 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004974 return true;
4975 }
4976 return false;
4977}
4978
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004979bool Camera3Device::startRequestBuffer() {
4980 return mRequestBufferSM.startRequestBuffer();
4981}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004982
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004983void Camera3Device::endRequestBuffer() {
4984 mRequestBufferSM.endRequestBuffer();
4985}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004986
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004987nsecs_t Camera3Device::getWaitDuration() {
4988 return kBaseGetBufferWait + getExpectedInFlightDuration();
4989}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004990
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004991void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
4992 mInterface->getInflightBufferKeys(out);
4993}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004994
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004995void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
4996 mInterface->getInflightRequestBufferKeys(out);
4997}
Shuzhen Wang268a1362018-10-16 16:32:59 -07004998
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004999std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5000 std::vector<sp<Camera3StreamInterface>> ret;
5001 bool hasInputStream = mInputStream != nullptr;
5002 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5003 if (hasInputStream) {
5004 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005005 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005006 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5007 ret.push_back(mOutputStreams[i]);
5008 }
5009 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5010 ret.push_back(mDeletedStreams[i]);
5011 }
5012 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005013}
5014
Emilian Peevcc0b7952020-01-07 13:54:47 -08005015void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5016 ATRACE_CALL();
5017
5018 if (offlineStreamIds == nullptr) {
5019 return;
5020 }
5021
5022 Mutex::Autolock il(mInterfaceLock);
5023
5024 auto streamIds = mOutputStreams.getStreamIds();
5025 bool hasInputStream = mInputStream != nullptr;
5026 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5027 offlineStreamIds->push_back(mInputStream->getId());
5028 }
5029
5030 for (const auto & streamId : streamIds) {
5031 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5032 // Streams that use the camera buffer manager are currently not supported in
5033 // offline mode
5034 if (stream->getOfflineProcessingSupport() &&
5035 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5036 offlineStreamIds->push_back(streamId);
5037 }
5038 }
5039}
5040
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005041status_t Camera3Device::setRotateAndCropAutoBehavior(
5042 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5043 ATRACE_CALL();
5044 Mutex::Autolock il(mInterfaceLock);
5045 Mutex::Autolock l(mLock);
5046 if (mRequestThread == nullptr) {
5047 return INVALID_OPERATION;
5048 }
5049 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5050}
5051
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005052bool Camera3Device::supportsCameraMute() {
5053 Mutex::Autolock il(mInterfaceLock);
5054 Mutex::Autolock l(mLock);
5055
5056 return mSupportCameraMute;
5057}
5058
5059status_t Camera3Device::setCameraMute(bool enabled) {
5060 ATRACE_CALL();
5061 Mutex::Autolock il(mInterfaceLock);
5062 Mutex::Autolock l(mLock);
5063
5064 if (mRequestThread == nullptr || !mSupportCameraMute) {
5065 return INVALID_OPERATION;
5066 }
Eino-Ville Talvala11afe4f2021-05-27 14:45:31 -07005067 int32_t muteMode =
5068 !enabled ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF :
5069 mSupportTestPatternSolidColor ? ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR :
5070 ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK;
5071 return mRequestThread->setCameraMute(muteMode);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005072}
5073
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005074status_t Camera3Device::injectCamera(const String8& injectedCamId,
5075 sp<CameraProviderManager> manager) {
5076 ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string());
5077 ATRACE_CALL();
5078 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005079 // When the camera device is active, injectCamera() and stopInjection() will call
5080 // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call
5081 // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But
5082 // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked
5083 // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling
5084 // waitUntilStateThenRelock().
5085 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005086
5087 status_t res = NO_ERROR;
5088 if (mInjectionMethods->isInjecting()) {
5089 if (injectedCamId == mInjectionMethods->getInjectedCamId()) {
5090 return OK;
5091 } else {
5092 res = mInjectionMethods->stopInjection();
5093 if (res != OK) {
5094 ALOGE("%s: Failed to stop the injection camera! ret != NO_ERROR: %d",
5095 __FUNCTION__, res);
5096 return res;
5097 }
5098 }
5099 }
5100
Jayant Chowdhary22441f32021-12-26 18:35:41 -08005101 res = injectionCameraInitialize(injectedCamId, manager);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005102 if (res != OK) {
5103 ALOGE("%s: Failed to initialize the injection camera! ret != NO_ERROR: %d",
5104 __FUNCTION__, res);
5105 return res;
5106 }
5107
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005108 // When the second display of android is cast to the remote device, and the opened camera is
5109 // also cast to the second display, in this case, because the camera has configured the streams
5110 // at this time, we can directly call injectCamera() to replace the internal camera with
5111 // injection camera.
Cliff Wu3b268182021-07-06 15:44:43 +08005112 if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) {
5113 ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__);
5114
5115 camera3::camera_stream_configuration injectionConfig;
5116 std::vector<uint32_t> injectionBufferSizes;
5117 mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes);
5118 if (mOperatingMode < 0 || injectionConfig.num_streams <= 0
5119 || injectionBufferSizes.size() <= 0) {
5120 ALOGE("Failed to inject camera due to abandoned configuration! "
5121 "mOperatingMode: %d injectionConfig.num_streams: %d "
5122 "injectionBufferSizes.size(): %zu", mOperatingMode,
5123 injectionConfig.num_streams, injectionBufferSizes.size());
5124 return DEAD_OBJECT;
5125 }
5126
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005127 res = mInjectionMethods->injectCamera(
5128 injectionConfig, injectionBufferSizes);
5129 if (res != OK) {
5130 ALOGE("Can't finish inject camera process!");
5131 return res;
5132 }
5133 }
5134
5135 return OK;
5136}
5137
5138status_t Camera3Device::stopInjection() {
5139 ALOGI("%s: Injection camera: stopInjection", __FUNCTION__);
5140 Mutex::Autolock il(mInterfaceLock);
Cliff Wu3b268182021-07-06 15:44:43 +08005141 Mutex::Autolock l(mLock);
Cliff Wuc2ad9c82021-04-21 00:58:58 +08005142 return mInjectionMethods->stopInjection();
5143}
5144
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005145}; // namespace android