blob: 50ef9538558c08ca2ff74c011834648889fe87e3 [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
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040059#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070063#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070064#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080065
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080066#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080067#include <tuple>
68
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080069using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070using namespace android::hardware::camera;
71using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080072
73namespace android {
74
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080075Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080076 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080077 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070078 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070079 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070080 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070081 mUsePartialResult(false),
82 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080083 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070085 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070088 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000090 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010091 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070092 mLastTemplateId(-1),
93 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094{
95 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080097}
98
99Camera3Device::~Camera3Device()
100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700103 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800107 return mId;
108}
109
Emilian Peevbd8c5032018-02-14 23:05:40 +0000110status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ATRACE_CALL();
112 Mutex::Autolock il(mInterfaceLock);
113 Mutex::Autolock l(mLock);
114
115 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
116 if (mStatus != STATUS_UNINITIALIZED) {
117 CLOGE("Already initialized!");
118 return INVALID_OPERATION;
119 }
120 if (manager == nullptr) return INVALID_OPERATION;
121
122 sp<ICameraDeviceSession> session;
123 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800124 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 /*out*/ &session);
126 ATRACE_END();
127 if (res != OK) {
128 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
129 return res;
130 }
131
Steven Moreland5ff9c912017-03-09 23:13:00 -0800132 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700134 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800135 session->close();
136 return res;
137 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800138 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800139
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700141 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (isLogical) {
143 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700144 res = manager->getCameraCharacteristics(
145 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (res != OK) {
147 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
148 physicalId.c_str(), strerror(-res), res);
149 session->close();
150 return res;
151 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700152
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800153 bool usePrecorrectArray =
154 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
155 if (usePrecorrectArray) {
156 res = mDistortionMappers[physicalId].setupStaticInfo(
157 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158 if (res != OK) {
159 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
160 "correction", physicalId.c_str());
161 session->close();
162 return res;
163 }
164 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800166 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800167 &mPhysicalDeviceInfoMap[physicalId],
168 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700169 }
170 }
171
Yifan Hongf79b5542017-04-11 14:44:25 -0700172 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
174 [&queue](const auto& descriptor) {
175 queue = std::make_shared<RequestMetadataQueue>(descriptor);
176 if (!queue->isValid() || queue->availableToWrite() <= 0) {
177 ALOGE("HAL returns empty request metadata fmq, not use it");
178 queue = nullptr;
179 // don't use the queue onwards.
180 }
181 });
182 if (!requestQueueRet.isOk()) {
183 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
184 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700185 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700186 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700187
188 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700189 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190 [&resQueue](const auto& descriptor) {
191 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
192 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700193 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700194 resQueue = nullptr;
195 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 }
197 });
198 if (!resultQueueRet.isOk()) {
199 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
200 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700201 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700203 IF_ALOGV() {
204 session->interfaceChain([](
205 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
206 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800207 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 ALOGV(" %s", iface.c_str());
209 }
210 });
211 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700212
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800213 camera_metadata_entry bufMgrMode =
214 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
215 if (bufMgrMode.count > 0) {
216 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
217 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
218 }
219
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700220 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
221 for (size_t i = 0; i < capabilities.count; i++) {
222 uint8_t capability = capabilities.data.u8[i];
223 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
224 mSupportOfflineProcessing = true;
225 }
226 }
227
228 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000229 std::string providerType;
230 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000231 mTagMonitor.initialize(mVendorTagId);
232 if (!monitorTags.isEmpty()) {
233 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
234 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800235
Shuzhen Wang268a1362018-10-16 16:32:59 -0700236 // Metadata tags needs fixup for monochrome camera device version less
237 // than 3.5.
238 hardware::hidl_version maxVersion{0,0};
239 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
240 if (res != OK) {
241 ALOGE("%s: Error in getting camera device version id: %s (%d)",
242 __FUNCTION__, strerror(-res), res);
243 return res;
244 }
245 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
246 maxVersion.get_major(), maxVersion.get_minor());
247
248 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700249 for (size_t i = 0; i < capabilities.count; i++) {
250 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700251 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
252 isMonochrome = true;
253 }
254 }
255 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800257 return initializeCommonLocked();
258}
259
260status_t Camera3Device::initializeCommonLocked() {
261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 /** Start up status tracker thread */
263 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 if (res != OK) {
266 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 mStatusTracker.clear();
270 return res;
271 }
272
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700273 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700274 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700275
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700276 if (mUseHalBufManager) {
277 res = mRequestBufferSM.initialize(mStatusTracker);
278 if (res != OK) {
279 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
280 strerror(-res), res);
281 mInterface->close();
282 mStatusTracker.clear();
283 return res;
284 }
285 }
286
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800287 /** Create buffer manager */
288 mBufferManager = new Camera3BufferManager();
289
290 Vector<int32_t> sessionParamKeys;
291 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
292 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
293 if (sessionKeysEntry.count > 0) {
294 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
295 }
296
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700297 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700298 mRequestThread = new RequestThread(
299 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800300 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800301 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700302 SET_ERR_L("Unable to start request queue thread: %s (%d)",
303 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800304 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 return res;
307 }
308
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700309 mPreparerThread = new PreparerThread();
310
Ruben Brunk183f0562015-08-12 12:55:02 -0700311 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400313 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700314 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800316
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800317 // Measure the clock domain offset between camera and video/hw_composer
318 camera_metadata_entry timestampSource =
319 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
320 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
321 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
322 mTimestampOffset = getMonoToBoottimeOffset();
323 }
324
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700325 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100326 camera_metadata_entry partialResultsCount =
327 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
328 if (partialResultsCount.count > 0) {
329 mNumPartialResults = partialResultsCount.data.i32[0];
330 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 }
332
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700333 camera_metadata_entry configs =
334 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
335 for (uint32_t i = 0; i < configs.count; i += 4) {
336 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
337 configs.data.i32[i + 3] ==
338 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
339 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
340 configs.data.i32[i + 2]));
341 }
342 }
343
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
345 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700346 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700347 if (res != OK) {
348 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
349 return res;
350 }
351 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800353 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800355
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800356 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
357 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
358 }
359
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800360 return OK;
361}
362
363status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700364 return disconnectImpl();
365}
366
367status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800368 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700369 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800370
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700371 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700372 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700373 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800374 Mutex::Autolock il(mInterfaceLock);
375 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
376 {
377 Mutex::Autolock l(mLock);
378 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700379
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800380 if (mStatus == STATUS_ACTIVE ||
381 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
382 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800386 } else {
387 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
388 if (res != OK) {
389 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
390 maxExpectedDuration);
391 // Continue to close device even in case of error
392 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700393 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700394 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800395
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800396 if (mStatus == STATUS_ERROR) {
397 CLOGE("Shutting down in an error state");
398 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 if (mStatusTracker != NULL) {
401 mStatusTracker->requestExit();
402 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800404 if (mRequestThread != NULL) {
405 mRequestThread->requestExit();
406 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
409 for (size_t i = 0; i < mOutputStreams.size(); i++) {
410 streams.push_back(mOutputStreams[i]);
411 }
412 if (mInputStream != nullptr) {
413 streams.push_back(mInputStream);
414 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700415 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700416 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800417 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
418 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
420 // HAL may be in a bad state, so waiting for request thread
421 // (which may be stuck in the HAL processCaptureRequest call)
422 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800423 // give up mInterfaceLock here and then lock it again. Could this lead
424 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 mRequestThread->join();
426 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700427 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800428 Mutex::Autolock il(mInterfaceLock);
429 if (mStatusTracker != NULL) {
430 mStatusTracker->join();
431 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800432
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800433 HalInterface* interface;
434 {
435 Mutex::Autolock l(mLock);
436 mRequestThread.clear();
437 Mutex::Autolock stLock(mTrackerLock);
438 mStatusTracker.clear();
439 interface = mInterface.get();
440 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700441
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800442 // Call close without internal mutex held, as the HAL close may need to
443 // wait on assorted callbacks,etc, to complete before it can return.
444 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800446 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800447
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800448 {
449 Mutex::Autolock l(mLock);
450 mInterface->clear();
451 mOutputStreams.clear();
452 mInputStream.clear();
453 mDeletedStreams.clear();
454 mBufferManager.clear();
455 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
456 }
457
458 for (auto& weakStream : streams) {
459 sp<Camera3StreamInterface> stream = weakStream.promote();
460 if (stream != nullptr) {
461 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
462 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
463 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700464 }
465 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700466 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700467 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800468}
469
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700470// For dumping/debugging only -
471// try to acquire a lock a few times, eventually give up to proceed with
472// debug/dump operations
473bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
474 bool gotLock = false;
475 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
476 if (lock.tryLock() == NO_ERROR) {
477 gotLock = true;
478 break;
479 } else {
480 usleep(kDumpSleepDuration);
481 }
482 }
483 return gotLock;
484}
485
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700486Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
487 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100488 const int STREAM_CONFIGURATION_SIZE = 4;
489 const int STREAM_FORMAT_OFFSET = 0;
490 const int STREAM_WIDTH_OFFSET = 1;
491 const int STREAM_HEIGHT_OFFSET = 2;
492 const int STREAM_IS_INPUT_OFFSET = 3;
493 camera_metadata_ro_entry_t availableStreamConfigs =
494 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
495 if (availableStreamConfigs.count == 0 ||
496 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
497 return Size(0, 0);
498 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700499
Emilian Peev08dd2452017-04-06 16:55:14 +0100500 // Get max jpeg size (area-wise).
501 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
502 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
503 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
504 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
505 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
506 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
507 && format == HAL_PIXEL_FORMAT_BLOB &&
508 (width * height > maxJpegWidth * maxJpegHeight)) {
509 maxJpegWidth = width;
510 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700511 }
512 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100513
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700514 return Size(maxJpegWidth, maxJpegHeight);
515}
516
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800517nsecs_t Camera3Device::getMonoToBoottimeOffset() {
518 // try three times to get the clock offset, choose the one
519 // with the minimum gap in measurements.
520 const int tries = 3;
521 nsecs_t bestGap, measured;
522 for (int i = 0; i < tries; ++i) {
523 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
525 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
526 const nsecs_t gap = tmono2 - tmono;
527 if (i == 0 || gap < bestGap) {
528 bestGap = gap;
529 measured = tbase - ((tmono + tmono2) >> 1);
530 }
531 }
532 return measured;
533}
534
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800535hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
536 int frameworkFormat) {
537 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
538}
539
540DataspaceFlags Camera3Device::mapToHidlDataspace(
541 android_dataspace dataSpace) {
542 return dataSpace;
543}
544
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700545BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100546 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700547 return usage;
548}
549
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
551 switch (rotation) {
552 case CAMERA3_STREAM_ROTATION_0:
553 return StreamRotation::ROTATION_0;
554 case CAMERA3_STREAM_ROTATION_90:
555 return StreamRotation::ROTATION_90;
556 case CAMERA3_STREAM_ROTATION_180:
557 return StreamRotation::ROTATION_180;
558 case CAMERA3_STREAM_ROTATION_270:
559 return StreamRotation::ROTATION_270;
560 }
561 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
562 return StreamRotation::ROTATION_0;
563}
564
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800565status_t Camera3Device::mapToStreamConfigurationMode(
566 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
567 if (mode == nullptr) return BAD_VALUE;
568 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
569 switch(operationMode) {
570 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
571 *mode = StreamConfigurationMode::NORMAL_MODE;
572 break;
573 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
574 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
575 break;
576 default:
577 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
578 return BAD_VALUE;
579 }
580 } else {
581 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800583 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584}
585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586int Camera3Device::mapToFrameworkFormat(
587 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
588 return static_cast<uint32_t>(pixelFormat);
589}
590
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700591android_dataspace Camera3Device::mapToFrameworkDataspace(
592 DataspaceFlags dataSpace) {
593 return static_cast<android_dataspace>(dataSpace);
594}
595
Emilian Peev050f5dc2017-05-18 14:43:56 +0100596uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700597 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700598 return usage;
599}
600
Emilian Peev050f5dc2017-05-18 14:43:56 +0100601uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700602 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700603 return usage;
604}
605
Zhijun Hef7da0962014-04-24 13:27:56 -0700606ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700607 // Get max jpeg size (area-wise).
608 Size maxJpegResolution = getMaxJpegResolution();
609 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800610 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
611 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700612 return BAD_VALUE;
613 }
614
Zhijun Hef7da0962014-04-24 13:27:56 -0700615 // Get max jpeg buffer size
616 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700617 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
618 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
620 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700621 return BAD_VALUE;
622 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700623 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800624 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700625
626 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700627 float scaleFactor = ((float) (width * height)) /
628 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800629 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
630 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 if (jpegBufferSize > maxJpegBufferSize) {
632 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 }
634
635 return jpegBufferSize;
636}
637
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700638ssize_t Camera3Device::getPointCloudBufferSize() const {
639 const int FLOATS_PER_POINT=4;
640 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
641 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800642 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
643 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700644 return BAD_VALUE;
645 }
646 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
647 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
648 return maxBytesForPointCloud;
649}
650
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800652 const int PER_CONFIGURATION_SIZE = 3;
653 const int WIDTH_OFFSET = 0;
654 const int HEIGHT_OFFSET = 1;
655 const int SIZE_OFFSET = 2;
656 camera_metadata_ro_entry rawOpaqueSizes =
657 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800658 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800659 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800660 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
661 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800662 return BAD_VALUE;
663 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700664
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800665 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
666 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
667 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
668 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
669 }
670 }
671
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
673 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 return BAD_VALUE;
675}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700676
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800677status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
678 ATRACE_CALL();
679 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700680
681 // Try to lock, but continue in case of failure (to avoid blocking in
682 // deadlocks)
683 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
684 bool gotLock = tryLockSpinRightRound(mLock);
685
686 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800687 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
688 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700689 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800690 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
691 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700692
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800693 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700694
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 String16 templatesOption("-t");
696 int n = args.size();
697 for (int i = 0; i < n; i++) {
698 if (args[i] == templatesOption) {
699 dumpTemplates = true;
700 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000701 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700702 if (i + 1 < n) {
703 String8 monitorTags = String8(args[i + 1]);
704 if (monitorTags == "off") {
705 mTagMonitor.disableMonitoring();
706 } else {
707 mTagMonitor.parseTagsToMonitor(monitorTags);
708 }
709 } else {
710 mTagMonitor.disableMonitoring();
711 }
712 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800713 }
714
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800717 const char *status =
718 mStatus == STATUS_ERROR ? "ERROR" :
719 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700720 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
721 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800722 mStatus == STATUS_ACTIVE ? "ACTIVE" :
723 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700724
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800725 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700726 if (mStatus == STATUS_ERROR) {
727 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800729 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800730 const char *mode =
731 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
732 mOperatingMode == static_cast<int>(
733 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
734 "CUSTOM";
735 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800736
737 if (mInputStream != NULL) {
738 write(fd, lines.string(), lines.size());
739 mInputStream->dump(fd, args);
740 } else {
741 lines.appendFormat(" No input stream.\n");
742 write(fd, lines.string(), lines.size());
743 }
744 for (size_t i = 0; i < mOutputStreams.size(); i++) {
745 mOutputStreams[i]->dump(fd,args);
746 }
747
Zhijun He431503c2016-03-07 17:30:16 -0800748 if (mBufferManager != NULL) {
749 lines = String8(" Camera3 Buffer Manager:\n");
750 write(fd, lines.string(), lines.size());
751 mBufferManager->dump(fd, args);
752 }
Zhijun He125684a2015-12-26 15:07:30 -0800753
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700754 lines = String8(" In-flight requests:\n");
755 if (mInFlightMap.size() == 0) {
756 lines.append(" None\n");
757 } else {
758 for (size_t i = 0; i < mInFlightMap.size(); i++) {
759 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700760 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000761 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800762 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000763 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700764 }
765 }
766 write(fd, lines.string(), lines.size());
767
Shuzhen Wang686f6442017-06-20 16:16:04 -0700768 if (mRequestThread != NULL) {
769 mRequestThread->dumpCaptureRequestLatency(fd,
770 " ProcessCaptureRequest latency histogram:");
771 }
772
Igor Murashkin1e479c02013-09-06 16:55:14 -0700773 {
774 lines = String8(" Last request sent:\n");
775 write(fd, lines.string(), lines.size());
776
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700777 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700778 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
779 }
780
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800782 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800783 "TEMPLATE_PREVIEW",
784 "TEMPLATE_STILL_CAPTURE",
785 "TEMPLATE_VIDEO_RECORD",
786 "TEMPLATE_VIDEO_SNAPSHOT",
787 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800788 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800789 };
790
791 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800792 camera_metadata_t *templateRequest = nullptr;
793 mInterface->constructDefaultRequestSettings(
794 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800796 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800797 lines.append(" Not supported\n");
798 write(fd, lines.string(), lines.size());
799 } else {
800 write(fd, lines.string(), lines.size());
801 dump_indented_camera_metadata(templateRequest,
802 fd, /*verbosity*/2, /*indentation*/8);
803 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800804 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800805 }
806 }
807
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700808 mTagMonitor.dumpMonitoredMetadata(fd);
809
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800810 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800811 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800812 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800813 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800814 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700816 if (gotLock) mLock.unlock();
817 if (gotInterfaceLock) mInterfaceLock.unlock();
818
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800819 return OK;
820}
821
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800822const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800823 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800824 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
825 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700826 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800827 mStatus == STATUS_ERROR ?
828 "when in error state" : "before init");
829 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700830 if (physicalId.isEmpty()) {
831 return mDeviceInfo;
832 } else {
833 std::string id(physicalId.c_str());
834 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
835 return mPhysicalDeviceInfoMap.at(id);
836 } else {
837 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
838 return mDeviceInfo;
839 }
840 }
841}
842
843const CameraMetadata& Camera3Device::info() const {
844 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800845 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846}
847
Jianing Wei90e59c92014-03-12 18:29:36 -0700848status_t Camera3Device::checkStatusOkToCaptureLocked() {
849 switch (mStatus) {
850 case STATUS_ERROR:
851 CLOGE("Device has encountered a serious error");
852 return INVALID_OPERATION;
853 case STATUS_UNINITIALIZED:
854 CLOGE("Device not initialized");
855 return INVALID_OPERATION;
856 case STATUS_UNCONFIGURED:
857 case STATUS_CONFIGURED:
858 case STATUS_ACTIVE:
859 // OK
860 break;
861 default:
862 SET_ERR_L("Unexpected status: %d", mStatus);
863 return INVALID_OPERATION;
864 }
865 return OK;
866}
867
868status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000869 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700870 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700871 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700872 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700873 if (requestList == NULL) {
874 CLOGE("requestList cannot be NULL.");
875 return BAD_VALUE;
876 }
877
Jianing Weicb0652e2014-03-12 18:29:36 -0700878 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700880 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
881 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
882 ++metadataIt, ++surfaceMapIt) {
883 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 if (newRequest == 0) {
885 CLOGE("Can't create capture request");
886 return BAD_VALUE;
887 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700888
Shuzhen Wang9d066012016-09-30 11:30:20 -0700889 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700890 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700891
Jianing Weicb0652e2014-03-12 18:29:36 -0700892 // Setup burst Id and request Id
893 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800894 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
895 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700896 CLOGE("RequestID does not exist in metadata");
897 return BAD_VALUE;
898 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800899 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700900
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700902
903 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700904 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700905 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
906 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
907 return BAD_VALUE;
908 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700909
910 // Setup batch size if this is a high speed video recording request.
911 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
912 auto firstRequest = requestList->begin();
913 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
914 if (outputStream->isVideoStream()) {
915 (*firstRequest)->mBatchSize = requestList->size();
916 break;
917 }
918 }
919 }
920
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 return OK;
922}
923
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800924status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000929 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800931 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932}
933
Emilian Peevaebbe412018-01-15 13:53:24 +0000934void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 std::list<const SurfaceMap>& surfaceMaps,
936 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 PhysicalCameraSettingsList requestList;
938 requestList.push_back({std::string(getId().string()), request});
939 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940
941 SurfaceMap surfaceMap;
942 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
943 // With no surface list passed in, stream and surface will have 1-to-1
944 // mapping. So the surface index is 0 for each stream in the surfaceMap.
945 for (size_t i = 0; i < streams.count; i++) {
946 surfaceMap[streams.data.i32[i]].push_back(0);
947 }
948 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800949}
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000952 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953 const std::list<const SurfaceMap> &surfaceMaps,
954 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700955 /*out*/
956 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700957 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700958 nsecs_t requestTimeNs = systemTime();
959
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 Mutex::Autolock il(mInterfaceLock);
961 Mutex::Autolock l(mLock);
962
963 status_t res = checkStatusOkToCaptureLocked();
964 if (res != OK) {
965 // error logged by previous call
966 return res;
967 }
968
969 RequestList requestList;
970
Shuzhen Wang0129d522016-10-30 22:43:41 -0700971 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700972 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700973 if (res != OK) {
974 // error logged by previous call
975 return res;
976 }
977
978 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700979 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700981 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700982 }
983
984 if (res == OK) {
985 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
986 if (res != OK) {
987 SET_ERR_L("Can't transition to active in %f seconds!",
988 kActiveTimeout/1e9);
989 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 } else {
993 CLOGE("Cannot queue request. Impossible.");
994 return BAD_VALUE;
995 }
996
997 return res;
998}
999
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001000hardware::Return<void> Camera3Device::requestStreamBuffers(
1001 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1002 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001003 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001005 *this, *mInterface, *this};
1006 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001007 return hardware::Void();
1008}
1009
1010hardware::Return<void> Camera3Device::returnStreamBuffers(
1011 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001012 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001013 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001014 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001015 return hardware::Void();
1016}
1017
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001018hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001019 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001020 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001021 // Ideally we should grab mLock, but that can lead to deadlock, and
1022 // it's not super important to get up to date value of mStatus for this
1023 // warning print, hence skipping the lock here
1024 if (mStatus == STATUS_ERROR) {
1025 // Per API contract, HAL should act as closed after device error
1026 // But mStatus can be set to error by framework as well, so just log
1027 // a warning here.
1028 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001029 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001030
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 sp<NotificationListener> listener;
1032 {
1033 std::lock_guard<std::mutex> l(mOutputLock);
1034 listener = mListener.promote();
1035 }
1036
Yifan Honga640c5a2017-04-12 16:30:31 -07001037 if (mProcessCaptureResultLock.tryLock() != OK) {
1038 // This should never happen; it indicates a wrong client implementation
1039 // that doesn't follow the contract. But, we can be tolerant here.
1040 ALOGE("%s: callback overlapped! waiting 1s...",
1041 __FUNCTION__);
1042 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1043 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1044 __FUNCTION__);
1045 // really don't know what to do, so bail out.
1046 return hardware::Void();
1047 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 CaptureOutputStates states {
1050 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001051 mInFlightLock, mLastCompletedRegularFrameNumber,
1052 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1053 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001054 mNextShutterFrameNumber,
1055 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1056 mNextResultFrameNumber,
1057 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1058 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1059 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001060 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001061 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1062 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001063 };
1064
Yifan Honga640c5a2017-04-12 16:30:31 -07001065 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 }
1068 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return hardware::Void();
1070}
1071
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001072// Only one processCaptureResult should be called at a time, so
1073// the locks won't block. The locks are present here simply to enforce this.
1074hardware::Return<void> Camera3Device::processCaptureResult(
1075 const hardware::hidl_vec<
1076 hardware::camera::device::V3_2::CaptureResult>& results) {
1077 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1078
1079 // Ideally we should grab mLock, but that can lead to deadlock, and
1080 // it's not super important to get up to date value of mStatus for this
1081 // warning print, hence skipping the lock here
1082 if (mStatus == STATUS_ERROR) {
1083 // Per API contract, HAL should act as closed after device error
1084 // But mStatus can be set to error by framework as well, so just log
1085 // a warning here.
1086 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1087 }
1088
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001089 sp<NotificationListener> listener;
1090 {
1091 std::lock_guard<std::mutex> l(mOutputLock);
1092 listener = mListener.promote();
1093 }
1094
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001095 if (mProcessCaptureResultLock.tryLock() != OK) {
1096 // This should never happen; it indicates a wrong client implementation
1097 // that doesn't follow the contract. But, we can be tolerant here.
1098 ALOGE("%s: callback overlapped! waiting 1s...",
1099 __FUNCTION__);
1100 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1101 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1102 __FUNCTION__);
1103 // really don't know what to do, so bail out.
1104 return hardware::Void();
1105 }
1106 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001107
1108 CaptureOutputStates states {
1109 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001110 mInFlightLock, mLastCompletedRegularFrameNumber,
1111 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1112 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 mNextShutterFrameNumber,
1114 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1115 mNextResultFrameNumber,
1116 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1117 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1118 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001119 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001120 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1121 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001122 };
1123
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001124 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001125 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001126 }
1127 mProcessCaptureResultLock.unlock();
1128 return hardware::Void();
1129}
1130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001131hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001132 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133 // Ideally we should grab mLock, but that can lead to deadlock, and
1134 // it's not super important to get up to date value of mStatus for this
1135 // warning print, hence skipping the lock here
1136 if (mStatus == STATUS_ERROR) {
1137 // Per API contract, HAL should act as closed after device error
1138 // But mStatus can be set to error by framework as well, so just log
1139 // a warning here.
1140 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001141 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 sp<NotificationListener> listener;
1144 {
1145 std::lock_guard<std::mutex> l(mOutputLock);
1146 listener = mListener.promote();
1147 }
1148
1149 CaptureOutputStates states {
1150 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001151 mInFlightLock, mLastCompletedRegularFrameNumber,
1152 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1153 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 mNextShutterFrameNumber,
1155 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1156 mNextResultFrameNumber,
1157 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1158 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1159 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001160 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001161 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1162 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001163 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001165 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001166 }
1167 return hardware::Void();
1168}
1169
Emilian Peevaebbe412018-01-15 13:53:24 +00001170status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001172 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001173 ATRACE_CALL();
1174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001176}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Jianing Weicb0652e2014-03-12 18:29:36 -07001178status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1179 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001185
Emilian Peevaebbe412018-01-15 13:53:24 +00001186 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001187 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188}
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190status_t Camera3Device::setStreamingRequestList(
1191 const List<const PhysicalCameraSettingsList> &requestsList,
1192 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001193 ATRACE_CALL();
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001196}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197
1198sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 status_t res;
1201
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001203 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1204 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1206 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001207 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001209 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001211 } else if (mStatus == STATUS_UNCONFIGURED) {
1212 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 CLOGE("No streams configured");
1214 return NULL;
1215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 }
1217
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
Jianing Weicb0652e2014-03-12 18:29:36 -07001222status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 switch (mStatus) {
1228 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 case STATUS_UNCONFIGURED:
1235 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 case STATUS_ACTIVE:
1237 // OK
1238 break;
1239 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001240 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 return INVALID_OPERATION;
1242 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001243 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001244
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001245 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
1248status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001252 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255status_t Camera3Device::createInputStream(
1256 uint32_t width, uint32_t height, int format, int *id) {
1257 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001259 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001260 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1262 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001263
1264 status_t res;
1265 bool wasActive = false;
1266
1267 switch (mStatus) {
1268 case STATUS_ERROR:
1269 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1270 return INVALID_OPERATION;
1271 case STATUS_UNINITIALIZED:
1272 ALOGE("%s: Device not initialized", __FUNCTION__);
1273 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 case STATUS_UNCONFIGURED:
1275 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 // OK
1277 break;
1278 case STATUS_ACTIVE:
1279 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001280 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283 return res;
1284 }
1285 wasActive = true;
1286 break;
1287 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 return INVALID_OPERATION;
1290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 if (mInputStream != 0) {
1294 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 }
1297
1298 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1299 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301
1302 mInputStream = newStream;
1303
1304 *id = mNextStreamId++;
1305
1306 // Continue captures if active at start
1307 if (wasActive) {
1308 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001309 // Reuse current operating mode and session parameters for new stream config
1310 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 if (res != OK) {
1312 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1313 __FUNCTION__, mNextStreamId, strerror(-res), res);
1314 return res;
1315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317 }
1318
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001319 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320 return OK;
1321}
1322
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001323status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001324 uint32_t width, uint32_t height, int format,
1325 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001326 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001327 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001328 ATRACE_CALL();
1329
1330 if (consumer == nullptr) {
1331 ALOGE("%s: consumer must not be null", __FUNCTION__);
1332 return BAD_VALUE;
1333 }
1334
1335 std::vector<sp<Surface>> consumers;
1336 consumers.push_back(consumer);
1337
1338 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1340 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341}
1342
1343status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1344 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1345 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001346 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001347 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001348 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001349
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001351 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001353 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001354 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1355 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1356 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001358 status_t res;
1359 bool wasActive = false;
1360
1361 switch (mStatus) {
1362 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001363 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return INVALID_OPERATION;
1365 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001368 case STATUS_UNCONFIGURED:
1369 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 // OK
1371 break;
1372 case STATUS_ACTIVE:
1373 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001374 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001376 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 return res;
1378 }
1379 wasActive = true;
1380 break;
1381 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001382 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 return INVALID_OPERATION;
1384 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001385 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386
1387 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001388
Shuzhen Wang0129d522016-10-30 22:43:41 -07001389 if (consumers.size() == 0 && !hasDeferredConsumer) {
1390 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1391 return BAD_VALUE;
1392 }
Zhijun He5d677d12016-05-29 16:52:39 -07001393
Shuzhen Wang0129d522016-10-30 22:43:41 -07001394 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001395 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1396 return BAD_VALUE;
1397 }
1398
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001400 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001401 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001402 blobBufferSize = getPointCloudBufferSize();
1403 if (blobBufferSize <= 0) {
1404 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1405 return BAD_VALUE;
1406 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001407 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1408 blobBufferSize = width * height;
1409 } else {
1410 blobBufferSize = getJpegBufferSize(width, height);
1411 if (blobBufferSize <= 0) {
1412 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1413 return BAD_VALUE;
1414 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001415 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001416 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001417 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001418 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001419 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1420 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1421 if (rawOpaqueBufferSize <= 0) {
1422 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1423 return BAD_VALUE;
1424 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001426 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001427 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001428 } else if (isShared) {
1429 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1430 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001431 mTimestampOffset, physicalCameraId, streamSetId,
1432 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001433 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001434 newStream = new Camera3OutputStream(mNextStreamId,
1435 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001436 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001439 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001440 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 }
Emilian Peev40ead602017-09-26 15:46:36 +01001442
1443 size_t consumerCount = consumers.size();
1444 for (size_t i = 0; i < consumerCount; i++) {
1445 int id = newStream->getSurfaceId(consumers[i]);
1446 if (id < 0) {
1447 SET_ERR_L("Invalid surface id");
1448 return BAD_VALUE;
1449 }
1450 if (surfaceIds != nullptr) {
1451 surfaceIds->push_back(id);
1452 }
1453 }
1454
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001455 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456
Emilian Peev08dd2452017-04-06 16:55:14 +01001457 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 res = mOutputStreams.add(mNextStreamId, newStream);
1460 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001461 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 return res;
1463 }
1464
Shuzhen Wang316781a2020-08-18 18:11:01 -07001465 mSessionStatsBuilder.addStream(mNextStreamId);
1466
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001468 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469
1470 // Continue captures if active at start
1471 if (wasActive) {
1472 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001473 // Reuse current operating mode and session parameters for new stream config
1474 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001475 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001476 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1477 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 return res;
1479 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001480 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001482 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001484}
1485
Emilian Peev710c1422017-08-30 11:19:38 +01001486status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001487 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001488 if (nullptr == streamInfo) {
1489 return BAD_VALUE;
1490 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001491 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001493
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 switch (mStatus) {
1495 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001496 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 return INVALID_OPERATION;
1498 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001499 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001501 case STATUS_UNCONFIGURED:
1502 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 case STATUS_ACTIVE:
1504 // OK
1505 break;
1506 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001507 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508 return INVALID_OPERATION;
1509 }
1510
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001511 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1512 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001513 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001514 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 }
1516
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001517 streamInfo->width = stream->getWidth();
1518 streamInfo->height = stream->getHeight();
1519 streamInfo->format = stream->getFormat();
1520 streamInfo->dataSpace = stream->getDataSpace();
1521 streamInfo->formatOverridden = stream->isFormatOverridden();
1522 streamInfo->originalFormat = stream->getOriginalFormat();
1523 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1524 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001526}
1527
1528status_t Camera3Device::setStreamTransform(int id,
1529 int transform) {
1530 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001533
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 switch (mStatus) {
1535 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001536 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return INVALID_OPERATION;
1538 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001539 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 case STATUS_UNCONFIGURED:
1542 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 case STATUS_ACTIVE:
1544 // OK
1545 break;
1546 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001547 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001548 return INVALID_OPERATION;
1549 }
1550
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001551 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1552 if (stream == nullptr) {
1553 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 return BAD_VALUE;
1555 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001556 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557}
1558
1559status_t Camera3Device::deleteStream(int id) {
1560 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 Mutex::Autolock l(mLock);
1563 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001564
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001565 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001566
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 // CameraDevice semantics require device to already be idle before
1568 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001570 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001571 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 }
1573
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001574 if (mStatus == STATUS_ERROR) {
1575 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1576 __FUNCTION__, mId.string());
1577 return -EBUSY;
1578 }
1579
Igor Murashkin2fba5842013-04-22 14:03:54 -07001580 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001581 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001582 if (mInputStream != NULL && id == mInputStream->getId()) {
1583 deletedStream = mInputStream;
1584 mInputStream.clear();
1585 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001586 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001587 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 return BAD_VALUE;
1589 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001590 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001591 }
1592
1593 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001594 if (stream != nullptr) {
1595 deletedStream = stream;
1596 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597 }
1598
1599 // Free up the stream endpoint so that it can be used by some other stream
1600 res = deletedStream->disconnect();
1601 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001602 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001603 // fall through since we want to still list the stream as deleted.
1604 }
1605 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001606 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001607
1608 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001609}
1610
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001611status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001612 ATRACE_CALL();
1613 ALOGV("%s: E", __FUNCTION__);
1614
1615 Mutex::Autolock il(mInterfaceLock);
1616 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001617
Emilian Peev811d2952018-05-25 11:08:40 +01001618 // In case the client doesn't include any session parameter, try a
1619 // speculative configuration using the values from the last cached
1620 // default request.
1621 if (sessionParams.isEmpty() &&
1622 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1623 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1624 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1625 mLastTemplateId);
1626 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1627 operatingMode);
1628 }
1629
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001630 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1631}
1632
1633status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1634 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001635 //Filter out any incoming session parameters
1636 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001637 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1638 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001639 CameraMetadata filteredParams(availableSessionKeys.count);
1640 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1641 filteredParams.getAndLock());
1642 set_camera_metadata_vendor_id(meta, mVendorTagId);
1643 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001644 if (availableSessionKeys.count > 0) {
1645 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1646 camera_metadata_ro_entry entry = params.find(
1647 availableSessionKeys.data.i32[i]);
1648 if (entry.count > 0) {
1649 filteredParams.update(entry);
1650 }
1651 }
1652 }
1653
1654 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001655}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001656
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001657status_t Camera3Device::getInputBufferProducer(
1658 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001659 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001660 Mutex::Autolock il(mInterfaceLock);
1661 Mutex::Autolock l(mLock);
1662
1663 if (producer == NULL) {
1664 return BAD_VALUE;
1665 } else if (mInputStream == NULL) {
1666 return INVALID_OPERATION;
1667 }
1668
1669 return mInputStream->getInputBufferProducer(producer);
1670}
1671
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001672status_t Camera3Device::createDefaultRequest(int templateId,
1673 CameraMetadata *request) {
1674 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001675 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001676
1677 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1678 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001679 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001680 return BAD_VALUE;
1681 }
1682
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001683 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001684
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001685 {
1686 Mutex::Autolock l(mLock);
1687 switch (mStatus) {
1688 case STATUS_ERROR:
1689 CLOGE("Device has encountered a serious error");
1690 return INVALID_OPERATION;
1691 case STATUS_UNINITIALIZED:
1692 CLOGE("Device is not initialized!");
1693 return INVALID_OPERATION;
1694 case STATUS_UNCONFIGURED:
1695 case STATUS_CONFIGURED:
1696 case STATUS_ACTIVE:
1697 // OK
1698 break;
1699 default:
1700 SET_ERR_L("Unexpected status: %d", mStatus);
1701 return INVALID_OPERATION;
1702 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001703
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001704 if (!mRequestTemplateCache[templateId].isEmpty()) {
1705 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001706 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001707 return OK;
1708 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001709 }
1710
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001711 camera_metadata_t *rawRequest;
1712 status_t res = mInterface->constructDefaultRequestSettings(
1713 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001714
1715 {
1716 Mutex::Autolock l(mLock);
1717 if (res == BAD_VALUE) {
1718 ALOGI("%s: template %d is not supported on this camera device",
1719 __FUNCTION__, templateId);
1720 return res;
1721 } else if (res != OK) {
1722 CLOGE("Unable to construct request template %d: %s (%d)",
1723 templateId, strerror(-res), res);
1724 return res;
1725 }
1726
1727 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1728 mRequestTemplateCache[templateId].acquire(rawRequest);
1729
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001730 // Override the template request with zoomRatioMapper
1731 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1732 &mRequestTemplateCache[templateId]);
1733 if (res != OK) {
1734 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1735 templateId, strerror(-res), res);
1736 return res;
1737 }
1738
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001739 // Fill in JPEG_QUALITY if not available
1740 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1741 static const uint8_t kDefaultJpegQuality = 95;
1742 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1743 &kDefaultJpegQuality, 1);
1744 }
1745
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001746 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001747 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001748 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749 return OK;
1750}
1751
1752status_t Camera3Device::waitUntilDrained() {
1753 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001755 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001758 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001759}
1760
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001761status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 switch (mStatus) {
1763 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001764 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 ALOGV("%s: Already idle", __FUNCTION__);
1766 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001767 case STATUS_CONFIGURED:
1768 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 case STATUS_ERROR:
1770 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772 break;
1773 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001774 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 return INVALID_OPERATION;
1776 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001777 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1778 maxExpectedDuration);
1779 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001780 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001781 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001782 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1783 res);
1784 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 return res;
1786}
1787
Ruben Brunk183f0562015-08-12 12:55:02 -07001788
1789void Camera3Device::internalUpdateStatusLocked(Status status) {
1790 mStatus = status;
1791 mRecentStatusUpdates.add(mStatus);
1792 mStatusChanged.broadcast();
1793}
1794
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001796status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001797 if (mRequestThread.get() != nullptr) {
1798 mRequestThread->setPaused(true);
1799 } else {
1800 return NO_INIT;
1801 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001803 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1804 maxExpectedDuration);
1805 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806 if (res != OK) {
1807 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001808 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809 }
1810
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001811 return res;
1812}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814// Resume after internalPauseAndWaitLocked
1815status_t Camera3Device::internalResumeLocked() {
1816 status_t res;
1817
1818 mRequestThread->setPaused(false);
1819
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001820 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1821 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1823 if (res != OK) {
1824 SET_ERR_L("Can't transition to active in %f seconds!",
1825 kActiveTimeout/1e9);
1826 }
1827 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829}
1830
Ruben Brunk183f0562015-08-12 12:55:02 -07001831status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001833
1834 size_t startIndex = 0;
1835 if (mStatusWaiters == 0) {
1836 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1837 // this status list
1838 mRecentStatusUpdates.clear();
1839 } else {
1840 // If other threads are waiting on updates to this status list, set the position of the
1841 // first element that this list will check rather than clearing the list.
1842 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 }
1844
Ruben Brunk183f0562015-08-12 12:55:02 -07001845 mStatusWaiters++;
1846
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001847 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001848 if (!active && mUseHalBufManager) {
1849 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001850 if (mStatus == STATUS_ACTIVE) {
1851 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001852 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001853 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001854 mRequestBufferSM.onWaitUntilIdle();
1855 }
1856
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001857 bool stateSeen = false;
1858 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001859 if (active == (mStatus == STATUS_ACTIVE)) {
1860 // Desired state is current
1861 break;
1862 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863
1864 res = mStatusChanged.waitRelative(mLock, timeout);
1865 if (res != OK) break;
1866
Ruben Brunk183f0562015-08-12 12:55:02 -07001867 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1868 // transitions.
1869 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1870 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1871 __FUNCTION__);
1872
1873 // Encountered desired state since we began waiting
1874 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1876 stateSeen = true;
1877 break;
1878 }
1879 }
1880 } while (!stateSeen);
1881
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001882 if (signalPipelineDrain) {
1883 mRequestThread->resetPipelineDrain();
1884 }
1885
Ruben Brunk183f0562015-08-12 12:55:02 -07001886 mStatusWaiters--;
1887
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888 return res;
1889}
1890
1891
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001892status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001894 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001896 if (listener != NULL && mListener != NULL) {
1897 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1898 }
1899 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001900 mRequestThread->setNotificationListener(listener);
1901 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001902
1903 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001904}
1905
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001906bool Camera3Device::willNotify3A() {
1907 return false;
1908}
1909
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001910status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001911 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001912 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001914 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001915 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1916 if (st == std::cv_status::timeout) {
1917 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001918 }
1919 }
1920 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001921}
1922
Jianing Weicb0652e2014-03-12 18:29:36 -07001923status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001925 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001927 if (mResultQueue.empty()) {
1928 return NOT_ENOUGH_DATA;
1929 }
1930
Jianing Weicb0652e2014-03-12 18:29:36 -07001931 if (frame == NULL) {
1932 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1933 return BAD_VALUE;
1934 }
1935
1936 CaptureResult &result = *(mResultQueue.begin());
1937 frame->mResultExtras = result.mResultExtras;
1938 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001939 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001940 mResultQueue.erase(mResultQueue.begin());
1941
1942 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001943}
1944
1945status_t Camera3Device::triggerAutofocus(uint32_t id) {
1946 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001948
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001949 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1950 // Mix-in this trigger into the next request and only the next request.
1951 RequestTrigger trigger[] = {
1952 {
1953 ANDROID_CONTROL_AF_TRIGGER,
1954 ANDROID_CONTROL_AF_TRIGGER_START
1955 },
1956 {
1957 ANDROID_CONTROL_AF_TRIGGER_ID,
1958 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001959 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001960 };
1961
1962 return mRequestThread->queueTrigger(trigger,
1963 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001964}
1965
1966status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1967 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001968 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001969
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001970 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1971 // Mix-in this trigger into the next request and only the next request.
1972 RequestTrigger trigger[] = {
1973 {
1974 ANDROID_CONTROL_AF_TRIGGER,
1975 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1976 },
1977 {
1978 ANDROID_CONTROL_AF_TRIGGER_ID,
1979 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001980 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001983 return mRequestThread->queueTrigger(trigger,
1984 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985}
1986
1987status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1988 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001989 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001991 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1992 // Mix-in this trigger into the next request and only the next request.
1993 RequestTrigger trigger[] = {
1994 {
1995 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1996 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1997 },
1998 {
1999 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2000 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002001 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002002 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002003
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002004 return mRequestThread->queueTrigger(trigger,
2005 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006}
2007
Jianing Weicb0652e2014-03-12 18:29:36 -07002008status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002009 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002010 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002011 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002012
Zhijun He7ef20392014-04-21 16:04:17 -07002013 {
2014 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002015
2016 // b/116514106 "disconnect()" can get called twice for the same device. The
2017 // camera device will not be initialized during the second run.
2018 if (mStatus == STATUS_UNINITIALIZED) {
2019 return OK;
2020 }
2021
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002022 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002023
2024 // Stop session and stream counter
2025 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002026 }
2027
Emilian Peev08dd2452017-04-06 16:55:14 +01002028 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002029}
2030
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002031status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002032 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2033}
2034
2035status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002036 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002037 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002038 Mutex::Autolock il(mInterfaceLock);
2039 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002040
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002041 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2042 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002043 CLOGE("Stream %d does not exist", streamId);
2044 return BAD_VALUE;
2045 }
2046
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002047 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002048 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002049 return BAD_VALUE;
2050 }
2051
2052 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002053 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002054 return BAD_VALUE;
2055 }
2056
Ruben Brunkc78ac262015-08-13 17:58:46 -07002057 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002058}
2059
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002060status_t Camera3Device::tearDown(int streamId) {
2061 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002062 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002063 Mutex::Autolock il(mInterfaceLock);
2064 Mutex::Autolock l(mLock);
2065
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002066 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2067 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002068 CLOGE("Stream %d does not exist", streamId);
2069 return BAD_VALUE;
2070 }
2071
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002072 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2073 CLOGE("Stream %d is a target of a in-progress request", streamId);
2074 return BAD_VALUE;
2075 }
2076
2077 return stream->tearDown();
2078}
2079
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002080status_t Camera3Device::addBufferListenerForStream(int streamId,
2081 wp<Camera3StreamBufferListener> listener) {
2082 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002083 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002084 Mutex::Autolock il(mInterfaceLock);
2085 Mutex::Autolock l(mLock);
2086
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002087 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2088 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002089 CLOGE("Stream %d does not exist", streamId);
2090 return BAD_VALUE;
2091 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002092 stream->addBufferListener(listener);
2093
2094 return OK;
2095}
2096
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002098 * Methods called by subclasses
2099 */
2100
2101void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002102 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002103 std::vector<int> streamIds;
2104 std::vector<hardware::CameraStreamStats> streamStats;
2105
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002106 {
2107 // Need mLock to safely update state and synchronize to current
2108 // state of methods in flight.
2109 Mutex::Autolock l(mLock);
2110 // We can get various system-idle notices from the status tracker
2111 // while starting up. Only care about them if we've actually sent
2112 // in some requests recently.
2113 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2114 return;
2115 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002116 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2117 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002118 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002119
2120 // Skip notifying listener if we're doing some user-transparent
2121 // state changes
2122 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002123
2124 // Populate stream statistics in case of Idle
2125 if (idle) {
2126 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2127 auto stream = mOutputStreams[i];
2128 if (stream.get() == nullptr) continue;
2129 streamIds.push_back(stream->getId());
2130 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2131 int64_t usage = 0LL;
2132 if (camera3Stream != nullptr) {
2133 usage = camera3Stream->getUsage();
2134 }
2135 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2136 stream->getFormat(), stream->getDataSpace(), usage,
2137 stream->getMaxHalBuffers(),
2138 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2139 }
2140 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002142
2143 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002145 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002146 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002147 }
2148 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002149 // Get session stats from the builder, and notify the listener.
2150 int64_t requestCount, resultErrorCount;
2151 bool deviceError;
2152 std::map<int, StreamStats> streamStatsMap;
2153 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2154 &deviceError, &streamStatsMap);
2155 for (size_t i = 0; i < streamIds.size(); i++) {
2156 int streamId = streamIds[i];
2157 auto stats = streamStatsMap.find(streamId);
2158 if (stats != streamStatsMap.end()) {
2159 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2160 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2161 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
2162 }
2163 }
2164 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002165 }
2166}
2167
Shuzhen Wang758c2152017-01-10 18:26:18 -08002168status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002169 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002170 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002171 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2172 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002173
2174 if (surfaceIds == nullptr) {
2175 return BAD_VALUE;
2176 }
2177
Zhijun He5d677d12016-05-29 16:52:39 -07002178 Mutex::Autolock il(mInterfaceLock);
2179 Mutex::Autolock l(mLock);
2180
Shuzhen Wang758c2152017-01-10 18:26:18 -08002181 if (consumers.size() == 0) {
2182 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002183 return BAD_VALUE;
2184 }
2185
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002186 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2187 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002188 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002189 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002190 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002191
2192 // isConsumerConfigurationDeferred will be off after setConsumers
2193 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002194 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002195 if (res != OK) {
2196 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2197 return res;
2198 }
2199
Emilian Peev40ead602017-09-26 15:46:36 +01002200 for (auto &consumer : consumers) {
2201 int id = stream->getSurfaceId(consumer);
2202 if (id < 0) {
2203 CLOGE("Invalid surface id!");
2204 return BAD_VALUE;
2205 }
2206 surfaceIds->push_back(id);
2207 }
2208
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002209 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002210 if (!stream->isConfiguring()) {
2211 CLOGE("Stream %d was already fully configured.", streamId);
2212 return INVALID_OPERATION;
2213 }
Zhijun He5d677d12016-05-29 16:52:39 -07002214
Shuzhen Wang0129d522016-10-30 22:43:41 -07002215 res = stream->finishConfiguration();
2216 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002217 // If finishConfiguration fails due to abandoned surface, do not set
2218 // device to error state.
2219 bool isSurfaceAbandoned =
2220 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2221 if (!isSurfaceAbandoned) {
2222 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2223 stream->getId(), strerror(-res), res);
2224 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002225 return res;
2226 }
Zhijun He5d677d12016-05-29 16:52:39 -07002227 }
2228
2229 return OK;
2230}
2231
Emilian Peev40ead602017-09-26 15:46:36 +01002232status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2233 const std::vector<OutputStreamInfo> &outputInfo,
2234 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2235 Mutex::Autolock il(mInterfaceLock);
2236 Mutex::Autolock l(mLock);
2237
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002238 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2239 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002240 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002241 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002242 }
2243
2244 for (const auto &it : removedSurfaceIds) {
2245 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2246 CLOGE("Shared surface still part of a pending request!");
2247 return -EBUSY;
2248 }
2249 }
2250
Emilian Peev40ead602017-09-26 15:46:36 +01002251 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2252 if (res != OK) {
2253 CLOGE("Stream %d failed to update stream (error %d %s) ",
2254 streamId, res, strerror(-res));
2255 if (res == UNKNOWN_ERROR) {
2256 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2257 __FUNCTION__);
2258 }
2259 return res;
2260 }
2261
2262 return res;
2263}
2264
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002265status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2266 Mutex::Autolock il(mInterfaceLock);
2267 Mutex::Autolock l(mLock);
2268
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002269 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2270 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002271 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2272 return BAD_VALUE;
2273 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002274
2275 if (dropping) {
2276 mSessionStatsBuilder.stopCounter(streamId);
2277 } else {
2278 mSessionStatsBuilder.startCounter(streamId);
2279 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002280 return stream->dropBuffers(dropping);
2281}
2282
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002283/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 * Camera3Device private methods
2285 */
2286
2287sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002288 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002291 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002292 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293
2294 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002295 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296 if (inputStreams.count > 0) {
2297 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002298 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002299 CLOGE("Request references unknown input stream %d",
2300 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 return NULL;
2302 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002305 SET_ERR_L("%s: input stream %d is not configured!",
2306 __FUNCTION__, mInputStream->getId());
2307 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002309 // Check if stream prepare is blocking requests.
2310 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002311 CLOGE("Request references an input stream that's being prepared!");
2312 return NULL;
2313 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002314
2315 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002316 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002317 }
2318
2319 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002320 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002321 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002322 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323 return NULL;
2324 }
2325
2326 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002327 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2328 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002329 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002330 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331 return NULL;
2332 }
Zhijun He5d677d12016-05-29 16:52:39 -07002333 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002334 auto iter = surfaceMap.find(streams.data.i32[i]);
2335 if (iter != surfaceMap.end()) {
2336 const std::vector<size_t>& surfaces = iter->second;
2337 for (const auto& surface : surfaces) {
2338 if (stream->isConsumerConfigurationDeferred(surface)) {
2339 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2340 "due to deferred consumer", stream->getId(), surface);
2341 return NULL;
2342 }
2343 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002344 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002345 }
2346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002347 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002348 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2349 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002350 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002351 // Check if stream prepare is blocking requests.
2352 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002353 CLOGE("Request references an output stream that's being prepared!");
2354 return NULL;
2355 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002356
2357 newRequest->mOutputStreams.push(stream);
2358 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002359 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002360 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002362 auto rotateAndCropEntry =
2363 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2364 if (rotateAndCropEntry.count > 0 &&
2365 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2366 newRequest->mRotateAndCropAuto = true;
2367 } else {
2368 newRequest->mRotateAndCropAuto = false;
2369 }
2370
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002371 auto zoomRatioEntry =
2372 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2373 if (zoomRatioEntry.count > 0 &&
2374 zoomRatioEntry.data.f[0] == 1.0f) {
2375 newRequest->mZoomRatioIs1x = true;
2376 } else {
2377 newRequest->mZoomRatioIs1x = false;
2378 }
2379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002380 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002381}
2382
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002383void Camera3Device::cancelStreamsConfigurationLocked() {
2384 int res = OK;
2385 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2386 res = mInputStream->cancelConfiguration();
2387 if (res != OK) {
2388 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2389 mInputStream->getId(), strerror(-res), res);
2390 }
2391 }
2392
2393 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002394 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002395 if (outputStream->isConfiguring()) {
2396 res = outputStream->cancelConfiguration();
2397 if (res != OK) {
2398 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2399 outputStream->getId(), strerror(-res), res);
2400 }
2401 }
2402 }
2403
2404 // Return state to that at start of call, so that future configures
2405 // properly clean things up
2406 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2407 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002408
2409 res = mPreparerThread->resume();
2410 if (res != OK) {
2411 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2412 }
2413}
2414
Emilian Peev0d0191e2020-04-21 17:01:18 -07002415bool Camera3Device::checkAbandonedStreamsLocked() {
2416 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2417 return true;
2418 }
2419
2420 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2421 auto stream = mOutputStreams[i];
2422 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2423 return true;
2424 }
2425 }
2426
2427 return false;
2428}
2429
Emilian Peev3bead5f2020-05-28 17:29:08 -07002430bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002431 ATRACE_CALL();
2432 bool ret = false;
2433
Shuzhen Wang316781a2020-08-18 18:11:01 -07002434 nsecs_t startTime = systemTime();
2435
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002436 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002437 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2438
2439 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002440 if (checkAbandonedStreamsLocked()) {
2441 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2442 __FUNCTION__);
2443 return true;
2444 }
2445
Emilian Peev3bead5f2020-05-28 17:29:08 -07002446 status_t rc = NO_ERROR;
2447 bool markClientActive = false;
2448 if (mStatus == STATUS_ACTIVE) {
2449 markClientActive = true;
2450 mPauseStateNotify = true;
2451 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2452
2453 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2454 }
2455
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002456 if (rc == NO_ERROR) {
2457 mNeedConfig = true;
2458 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2459 if (rc == NO_ERROR) {
2460 ret = true;
2461 mPauseStateNotify = false;
2462 //Moving to active state while holding 'mLock' is important.
2463 //There could be pending calls to 'create-/deleteStream' which
2464 //will trigger another stream configuration while the already
2465 //present streams end up with outstanding buffers that will
2466 //not get drained.
2467 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002468 } else if (rc == DEAD_OBJECT) {
2469 // DEAD_OBJECT can be returned if either the consumer surface is
2470 // abandoned, or the HAL has died.
2471 // - If the HAL has died, configureStreamsLocked call will set
2472 // device to error state,
2473 // - If surface is abandoned, we should not set device to error
2474 // state.
2475 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002476 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002477 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002478 }
2479 } else {
2480 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2481 }
2482
Shuzhen Wang316781a2020-08-18 18:11:01 -07002483 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2484 ns2ms(systemTime() - startTime));
2485
Emilian Peev3bead5f2020-05-28 17:29:08 -07002486 if (markClientActive) {
2487 mStatusTracker->markComponentActive(clientStatusId);
2488 }
2489
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002490 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002491}
2492
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002493status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002494 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495 ATRACE_CALL();
2496 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002498 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002499 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002500 return INVALID_OPERATION;
2501 }
2502
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002503 if (operatingMode < 0) {
2504 CLOGE("Invalid operating mode: %d", operatingMode);
2505 return BAD_VALUE;
2506 }
2507
2508 bool isConstrainedHighSpeed =
2509 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2510 operatingMode;
2511
2512 if (mOperatingMode != operatingMode) {
2513 mNeedConfig = true;
2514 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2515 mOperatingMode = operatingMode;
2516 }
2517
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002518 // In case called from configureStreams, abort queued input buffers not belonging to
2519 // any pending requests.
2520 if (mInputStream != NULL && notifyRequestThread) {
2521 while (true) {
2522 camera3_stream_buffer_t inputBuffer;
2523 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2524 /*respectHalLimit*/ false);
2525 if (res != OK) {
2526 // Exhausted acquiring all input buffers.
2527 break;
2528 }
2529
2530 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2531 res = mInputStream->returnInputBuffer(inputBuffer);
2532 if (res != OK) {
2533 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2534 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2535 }
2536 }
2537 }
2538
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002539 if (!mNeedConfig) {
2540 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2541 return OK;
2542 }
2543
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002544 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002545 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002546 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2547 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002548 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002549 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002551 }
2552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002553 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002554 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002555
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002556 mPreparerThread->pause();
2557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002558 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002559 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2561
2562 Vector<camera3_stream_t*> streams;
2563 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002564 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002565
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566
2567 if (mInputStream != NULL) {
2568 camera3_stream_t *inputStream;
2569 inputStream = mInputStream->startConfiguration();
2570 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002571 CLOGE("Can't start input stream configuration");
2572 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002573 return INVALID_OPERATION;
2574 }
2575 streams.add(inputStream);
2576 }
2577
2578 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002579
2580 // Don't configure bidi streams twice, nor add them twice to the list
2581 if (mOutputStreams[i].get() ==
2582 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2583
2584 config.num_streams--;
2585 continue;
2586 }
2587
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002588 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002590 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002591 CLOGE("Can't start output stream configuration");
2592 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 return INVALID_OPERATION;
2594 }
2595 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002596
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002597 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002598 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2599 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002600 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2601 bufferSizes[k] = static_cast<uint32_t>(
2602 getJpegBufferSize(outputStream->width, outputStream->height));
2603 } else if (outputStream->data_space ==
2604 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2605 bufferSizes[k] = outputStream->width * outputStream->height;
2606 } else {
2607 ALOGW("%s: Blob dataSpace %d not supported",
2608 __FUNCTION__, outputStream->data_space);
2609 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002610 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002611 }
2612
2613 config.streams = streams.editArray();
2614
2615 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002616 // max_buffers, usage, and priv fields, as well as data_space and format
2617 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002618
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002619 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002620 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002621 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002623 if (res == BAD_VALUE) {
2624 // HAL rejected this set of streams as unsupported, clean up config
2625 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002626 CLOGE("Set of requested inputs/outputs not supported by HAL");
2627 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002628 return BAD_VALUE;
2629 } else if (res != OK) {
2630 // Some other kind of error from configure_streams - this is not
2631 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002632 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2633 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634 return res;
2635 }
2636
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002637 // Finish all stream configuration immediately.
2638 // TODO: Try to relax this later back to lazy completion, which should be
2639 // faster
2640
Igor Murashkin073f8572013-05-02 14:59:28 -07002641 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002642 bool streamReConfigured = false;
2643 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002644 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002645 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002646 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002647 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002648 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2649 return DEAD_OBJECT;
2650 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002651 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002652 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002653 if (streamReConfigured) {
2654 mInterface->onStreamReConfigured(mInputStream->getId());
2655 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002656 }
2657
2658 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002659 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002660 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002661 bool streamReConfigured = false;
2662 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002663 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002664 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002665 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002666 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002667 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2668 return DEAD_OBJECT;
2669 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002670 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002671 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002672 if (streamReConfigured) {
2673 mInterface->onStreamReConfigured(outputStream->getId());
2674 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002675 }
2676 }
2677
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678 // Request thread needs to know to avoid using repeat-last-settings protocol
2679 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002680 if (notifyRequestThread) {
2681 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2682 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683
Zhijun He90f7c372016-08-16 16:19:43 -07002684 char value[PROPERTY_VALUE_MAX];
2685 property_get("camera.fifo.disable", value, "0");
2686 int32_t disableFifo = atoi(value);
2687 if (disableFifo != 1) {
2688 // Boost priority of request thread to SCHED_FIFO.
2689 pid_t requestThreadTid = mRequestThread->getTid();
2690 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002691 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002692 if (res != OK) {
2693 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2694 strerror(-res), res);
2695 } else {
2696 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2697 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002698 }
2699
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002700 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002701 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2702 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2703 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2704 sessionParams.unlock(newSessionParams);
2705 mSessionParams.unlock(currentSessionParams);
2706 if (updateSessionParams) {
2707 mSessionParams = sessionParams;
2708 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002709
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002710 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002712 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002713 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002714
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002715 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002716
Zhijun He0a210512014-07-24 13:45:15 -07002717 // tear down the deleted streams after configure streams.
2718 mDeletedStreams.clear();
2719
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002720 auto rc = mPreparerThread->resume();
2721 if (rc != OK) {
2722 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2723 return rc;
2724 }
2725
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002726 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002727 mRequestBufferSM.onStreamsConfigured();
2728 }
2729
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002730 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002731}
2732
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002733status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002734 ATRACE_CALL();
2735 status_t res;
2736
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002737 if (mFakeStreamId != NO_STREAM) {
2738 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002739 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002740 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002741 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002742 return INVALID_OPERATION;
2743 }
2744
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002745 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002746
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002747 sp<Camera3OutputStreamInterface> fakeStream =
2748 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002749
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002750 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002751 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002752 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002753 return res;
2754 }
2755
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002756 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002757 mNextStreamId++;
2758
2759 return OK;
2760}
2761
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002762status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002763 ATRACE_CALL();
2764 status_t res;
2765
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002766 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002767 if (mOutputStreams.size() == 1) return OK;
2768
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002769 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002770
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002771 // Ok, have a fake stream and there's at least one other output stream,
2772 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002773
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002774 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002775 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002776 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002777 return INVALID_OPERATION;
2778 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002779 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002780
2781 // Free up the stream endpoint so that it can be used by some other stream
2782 res = deletedStream->disconnect();
2783 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002784 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002785 // fall through since we want to still list the stream as deleted.
2786 }
2787 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002788 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002789
2790 return res;
2791}
2792
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002793void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002794 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002795 Mutex::Autolock l(mLock);
2796 va_list args;
2797 va_start(args, fmt);
2798
2799 setErrorStateLockedV(fmt, args);
2800
2801 va_end(args);
2802}
2803
2804void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002805 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002806 Mutex::Autolock l(mLock);
2807 setErrorStateLockedV(fmt, args);
2808}
2809
2810void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2811 va_list args;
2812 va_start(args, fmt);
2813
2814 setErrorStateLockedV(fmt, args);
2815
2816 va_end(args);
2817}
2818
2819void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002820 // Print out all error messages to log
2821 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002822 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002823
2824 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002825 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002826
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002827 mErrorCause = errorCause;
2828
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002829 if (mRequestThread != nullptr) {
2830 mRequestThread->setPaused(true);
2831 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002832 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002833
2834 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002835 sp<NotificationListener> listener = mListener.promote();
2836 if (listener != NULL) {
2837 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002838 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002839 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 }
2841
2842 // Save stack trace. View by dumping it later.
2843 CameraTraces::saveTrace();
2844 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002845}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002846
2847/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002848 * In-flight request management
2849 */
2850
Jianing Weicb0652e2014-03-12 18:29:36 -07002851status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002852 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002853 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002854 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002855 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002856 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002857 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002858 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002859
2860 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002861 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002862 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002863 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002864 if (res < 0) return res;
2865
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002866 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002867 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2868 // avoid a deadlock during reprocess requests.
2869 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002870 if (mStatusTracker != nullptr) {
2871 mStatusTracker->markComponentActive(mInFlightStatusId);
2872 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002873 }
2874
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002875 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002876 return OK;
2877}
2878
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002879void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002880 // Indicate idle inFlightMap to the status tracker
2881 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002882 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002883 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2884 // avoid a deadlock during reprocess requests.
2885 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002886 if (mStatusTracker != nullptr) {
2887 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2888 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002889 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002890 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002891}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002892
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002893void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002894 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002895 // something has likely gone wrong. This might still be legit only if application send in
2896 // a long burst of long exposure requests.
2897 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2898 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2899 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2900 mInFlightMap.size(), mExpectedInflightDuration);
2901 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2902 kInFlightWarnLimitHighSpeed) {
2903 CLOGW("In-flight list too large for high speed configuration: %zu,"
2904 "total inflight duration %" PRIu64,
2905 mInFlightMap.size(), mExpectedInflightDuration);
2906 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002907 }
2908}
2909
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002910void Camera3Device::onInflightMapFlushedLocked() {
2911 mExpectedInflightDuration = 0;
2912}
2913
2914void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002915 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002916 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2917 mInFlightMap.removeItemsAt(idx, 1);
2918
2919 onInflightEntryRemovedLocked(duration);
2920}
2921
2922
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002923void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002924 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002925 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002926 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002927 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002928 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002929 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002930
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002931 FlushInflightReqStates states {
2932 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002933 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002934
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002935 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002936}
2937
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002938CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002939 ALOGV("%s", __FUNCTION__);
2940
Igor Murashkin1e479c02013-09-06 16:55:14 -07002941 CameraMetadata retVal;
2942
2943 if (mRequestThread != NULL) {
2944 retVal = mRequestThread->getLatestRequest();
2945 }
2946
Igor Murashkin1e479c02013-09-06 16:55:14 -07002947 return retVal;
2948}
2949
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002950void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002951 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2952 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2953
2954 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2955 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002956}
2957
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002958/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002959 * HalInterface inner class methods
2960 */
2961
Yifan Hongf79b5542017-04-11 14:44:25 -07002962Camera3Device::HalInterface::HalInterface(
2963 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002964 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002965 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002966 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002967 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002968 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002969 mIsReconfigurationQuerySupported(true),
2970 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002971 // Check with hardware service manager if we can downcast these interfaces
2972 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002973 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2974 if (castResult_3_6.isOk()) {
2975 mHidlSession_3_6 = castResult_3_6;
2976 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002977 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2978 if (castResult_3_5.isOk()) {
2979 mHidlSession_3_5 = castResult_3_5;
2980 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002981 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2982 if (castResult_3_4.isOk()) {
2983 mHidlSession_3_4 = castResult_3_4;
2984 }
2985 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2986 if (castResult_3_3.isOk()) {
2987 mHidlSession_3_3 = castResult_3_3;
2988 }
2989}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002991Camera3Device::HalInterface::HalInterface() :
2992 mUseHalBufManager(false),
2993 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002994
2995Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002996 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002997 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002998 mUseHalBufManager(other.mUseHalBufManager),
2999 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003000
3001bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003002 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003003}
3004
3005void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003006 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003007 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003008 mHidlSession_3_4.clear();
3009 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003010 mHidlSession.clear();
3011}
3012
3013status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3014 camera3_request_template_t templateId,
3015 /*out*/ camera_metadata_t **requestTemplate) {
3016 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3017 if (!valid()) return INVALID_OPERATION;
3018 status_t res = OK;
3019
Emilian Peev31abd0a2017-05-11 18:37:46 +01003020 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003021
3022 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003023 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003024 status = s;
3025 if (status == common::V1_0::Status::OK) {
3026 const camera_metadata *r =
3027 reinterpret_cast<const camera_metadata_t*>(request.data());
3028 size_t expectedSize = request.size();
3029 int ret = validate_camera_metadata_structure(r, &expectedSize);
3030 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3031 *requestTemplate = clone_camera_metadata(r);
3032 if (*requestTemplate == nullptr) {
3033 ALOGE("%s: Unable to clone camera metadata received from HAL",
3034 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003035 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003036 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003037 } else {
3038 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3039 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003040 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003041 }
3042 };
3043 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003044 RequestTemplate id;
3045 switch (templateId) {
3046 case CAMERA3_TEMPLATE_PREVIEW:
3047 id = RequestTemplate::PREVIEW;
3048 break;
3049 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3050 id = RequestTemplate::STILL_CAPTURE;
3051 break;
3052 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3053 id = RequestTemplate::VIDEO_RECORD;
3054 break;
3055 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3056 id = RequestTemplate::VIDEO_SNAPSHOT;
3057 break;
3058 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3059 id = RequestTemplate::ZERO_SHUTTER_LAG;
3060 break;
3061 case CAMERA3_TEMPLATE_MANUAL:
3062 id = RequestTemplate::MANUAL;
3063 break;
3064 default:
3065 // Unknown template ID, or this HAL is too old to support it
3066 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003067 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003068 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003069
Emilian Peev31abd0a2017-05-11 18:37:46 +01003070 if (!err.isOk()) {
3071 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3072 res = DEAD_OBJECT;
3073 } else {
3074 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003075 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003076
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003077 return res;
3078}
3079
Emilian Peev4ec17882019-01-24 17:16:58 -08003080bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3081 CameraMetadata& newSessionParams) {
3082 // We do reconfiguration by default;
3083 bool ret = true;
3084 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3085 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3086 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3087 oldSessionParams.getAndLock());
3088 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3089 newSessionParams.getAndLock());
3090 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3091 get_camera_metadata_size(oldSessioMeta));
3092 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3093 get_camera_metadata_size(newSessioMeta));
3094 hardware::camera::common::V1_0::Status callStatus;
3095 bool required;
3096 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3097 bool requiredFlag) {
3098 callStatus = s;
3099 required = requiredFlag;
3100 };
3101 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3102 oldSessionParams.unlock(oldSessioMeta);
3103 newSessionParams.unlock(newSessioMeta);
3104 if (err.isOk()) {
3105 switch (callStatus) {
3106 case hardware::camera::common::V1_0::Status::OK:
3107 ret = required;
3108 break;
3109 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3110 mIsReconfigurationQuerySupported = false;
3111 ret = true;
3112 break;
3113 default:
3114 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3115 ret = true;
3116 }
3117 } else {
3118 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3119 ret = true;
3120 }
3121 }
3122
3123 return ret;
3124}
3125
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003126status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003127 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003128 ATRACE_NAME("CameraHal::configureStreams");
3129 if (!valid()) return INVALID_OPERATION;
3130 status_t res = OK;
3131
Emilian Peev31abd0a2017-05-11 18:37:46 +01003132 // Convert stream config to HIDL
3133 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003134 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3135 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3136 requestedConfiguration3_2.streams.resize(config->num_streams);
3137 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003138 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003139 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3140 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003141 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003142
Emilian Peev31abd0a2017-05-11 18:37:46 +01003143 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3144 cam3stream->setBufferFreedListener(this);
3145 int streamId = cam3stream->getId();
3146 StreamType streamType;
3147 switch (src->stream_type) {
3148 case CAMERA3_STREAM_OUTPUT:
3149 streamType = StreamType::OUTPUT;
3150 break;
3151 case CAMERA3_STREAM_INPUT:
3152 streamType = StreamType::INPUT;
3153 break;
3154 default:
3155 ALOGE("%s: Stream %d: Unsupported stream type %d",
3156 __FUNCTION__, streamId, config->streams[i]->stream_type);
3157 return BAD_VALUE;
3158 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003159 dst3_2.id = streamId;
3160 dst3_2.streamType = streamType;
3161 dst3_2.width = src->width;
3162 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003163 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003164 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003165 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3166 // to HAL are original, not the overriden ones.
3167 if (mHidlSession_3_5 != nullptr) {
3168 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3169 cam3stream->getOriginalFormat() : src->format);
3170 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3171 cam3stream->getOriginalDataSpace() : src->data_space);
3172 } else {
3173 dst3_2.format = mapToPixelFormat(src->format);
3174 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3175 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003176 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003177 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003178 if (src->physical_camera_id != nullptr) {
3179 dst3_4.physicalCameraId = src->physical_camera_id;
3180 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003181
3182 activeStreams.insert(streamId);
3183 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003184 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003185 }
3186 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003187 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003188
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003189 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003190 res = mapToStreamConfigurationMode(
3191 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003192 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003193 if (res != OK) {
3194 return res;
3195 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003196 requestedConfiguration3_2.operationMode = operationMode;
3197 requestedConfiguration3_4.operationMode = operationMode;
3198 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003199 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3200 get_camera_metadata_size(sessionParams));
3201
Emilian Peev31abd0a2017-05-11 18:37:46 +01003202 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003203 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003204 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003205 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003206 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003207
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003208 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003209 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3210 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003211 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003212 };
3213
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003214 auto configStream36Cb = [&status, &finalConfiguration3_6]
3215 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3216 finalConfiguration3_6 = halConfiguration;
3217 status = s;
3218 };
3219
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003220 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3221 (hardware::Return<void>& err) -> status_t {
3222 if (!err.isOk()) {
3223 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3224 return DEAD_OBJECT;
3225 }
3226 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3227 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3228 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3229 }
3230 return OK;
3231 };
3232
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003233 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3234 (hardware::Return<void>& err) -> status_t {
3235 if (!err.isOk()) {
3236 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3237 return DEAD_OBJECT;
3238 }
3239 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3240 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3241 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3242 }
3243 return OK;
3244 };
3245
Shuzhen Wang92653952019-05-07 15:11:43 -07003246 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003247 if (mHidlSession_3_6 != nullptr) {
3248 ALOGV("%s: v3.6 device found", __FUNCTION__);
3249 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3250 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3251 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3252 auto err = mHidlSession_3_6->configureStreams_3_6(
3253 requestedConfiguration3_5, configStream36Cb);
3254 res = postprocConfigStream36(err);
3255 if (res != OK) {
3256 return res;
3257 }
3258 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003259 ALOGV("%s: v3.5 device found", __FUNCTION__);
3260 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3261 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3262 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3263 auto err = mHidlSession_3_5->configureStreams_3_5(
3264 requestedConfiguration3_5, configStream34Cb);
3265 res = postprocConfigStream34(err);
3266 if (res != OK) {
3267 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003268 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003269 } else if (mHidlSession_3_4 != nullptr) {
3270 // We do; use v3.4 for the call
3271 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003272 auto err = mHidlSession_3_4->configureStreams_3_4(
3273 requestedConfiguration3_4, configStream34Cb);
3274 res = postprocConfigStream34(err);
3275 if (res != OK) {
3276 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003277 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003278 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003279 // We do; use v3.3 for the call
3280 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003281 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003282 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003283 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003284 finalConfiguration = halConfiguration;
3285 status = s;
3286 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003287 if (!err.isOk()) {
3288 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3289 return DEAD_OBJECT;
3290 }
3291 } else {
3292 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3293 ALOGV("%s: v3.2 device found", __FUNCTION__);
3294 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003295 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003296 [&status, &finalConfiguration_3_2]
3297 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3298 finalConfiguration_3_2 = halConfiguration;
3299 status = s;
3300 });
3301 if (!err.isOk()) {
3302 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3303 return DEAD_OBJECT;
3304 }
3305 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3306 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3307 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3308 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003309 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003310 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003311 }
3312
3313 if (status != common::V1_0::Status::OK ) {
3314 return CameraProviderManager::mapToStatusT(status);
3315 }
3316
3317 // And convert output stream configuration from HIDL
3318
3319 for (size_t i = 0; i < config->num_streams; i++) {
3320 camera3_stream_t *dst = config->streams[i];
3321 int streamId = Camera3Stream::cast(dst)->getId();
3322
3323 // Start scan at i, with the assumption that the stream order matches
3324 size_t realIdx = i;
3325 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003326 size_t halStreamCount = finalConfiguration.streams.size();
3327 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003328 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003329 found = true;
3330 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003331 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003332 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003333 }
3334 if (!found) {
3335 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3336 __FUNCTION__, streamId);
3337 return INVALID_OPERATION;
3338 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003339 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003340 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003341
Emilian Peev710c1422017-08-30 11:19:38 +01003342 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003343 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3344 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3345
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003346 if (mHidlSession_3_6 != nullptr) {
3347 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3348 }
3349
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003350 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003351 dstStream->setFormatOverride(false);
3352 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003353 if (dst->format != overrideFormat) {
3354 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3355 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003356 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003357 if (dst->data_space != overrideDataSpace) {
3358 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3359 streamId, dst->format);
3360 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003361 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003362 bool needFormatOverride =
3363 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3364 bool needDataspaceOverride =
3365 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003366 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003367 dstStream->setFormatOverride(needFormatOverride);
3368 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003369 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003370 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003371 }
3372
Emilian Peev31abd0a2017-05-11 18:37:46 +01003373 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003374 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003375 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003376 __FUNCTION__, streamId);
3377 return INVALID_OPERATION;
3378 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003379 dstStream->setUsage(
3380 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003381 } else {
3382 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003383 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003384 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3385 __FUNCTION__, streamId);
3386 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003387 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003388 dstStream->setUsage(
3389 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003390 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003391 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003392 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003394 return res;
3395}
3396
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003397status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003398 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003399 /*out*/std::vector<native_handle_t*>* handlesCreated,
3400 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003401 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003402 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3403 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3404 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003405 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003406 }
3407
3408 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003409
3410 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003411
3412 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003413 if (request->input_buffer != nullptr) {
3414 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3415 buffer_handle_t buf = *(request->input_buffer->buffer);
3416 auto pair = getBufferId(buf, streamId);
3417 bool isNewBuffer = pair.first;
3418 uint64_t bufferId = pair.second;
3419 captureRequest->inputBuffer.streamId = streamId;
3420 captureRequest->inputBuffer.bufferId = bufferId;
3421 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3422 captureRequest->inputBuffer.status = BufferStatus::OK;
3423 native_handle_t *acquireFence = nullptr;
3424 if (request->input_buffer->acquire_fence != -1) {
3425 acquireFence = native_handle_create(1,0);
3426 acquireFence->data[0] = request->input_buffer->acquire_fence;
3427 handlesCreated->push_back(acquireFence);
3428 }
3429 captureRequest->inputBuffer.acquireFence = acquireFence;
3430 captureRequest->inputBuffer.releaseFence = nullptr;
3431
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003432 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003433 request->input_buffer->buffer);
3434 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003435 } else {
3436 captureRequest->inputBuffer.streamId = -1;
3437 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3438 }
3439
3440 captureRequest->outputBuffers.resize(request->num_output_buffers);
3441 for (size_t i = 0; i < request->num_output_buffers; i++) {
3442 const camera3_stream_buffer_t *src = request->output_buffers + i;
3443 StreamBuffer &dst = captureRequest->outputBuffers[i];
3444 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003445 if (src->buffer != nullptr) {
3446 buffer_handle_t buf = *(src->buffer);
3447 auto pair = getBufferId(buf, streamId);
3448 bool isNewBuffer = pair.first;
3449 dst.bufferId = pair.second;
3450 dst.buffer = isNewBuffer ? buf : nullptr;
3451 native_handle_t *acquireFence = nullptr;
3452 if (src->acquire_fence != -1) {
3453 acquireFence = native_handle_create(1,0);
3454 acquireFence->data[0] = src->acquire_fence;
3455 handlesCreated->push_back(acquireFence);
3456 }
3457 dst.acquireFence = acquireFence;
3458 } else if (mUseHalBufManager) {
3459 // HAL buffer management path
3460 dst.bufferId = BUFFER_ID_NO_BUFFER;
3461 dst.buffer = nullptr;
3462 dst.acquireFence = nullptr;
3463 } else {
3464 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3465 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003466 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003467 dst.streamId = streamId;
3468 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003469 dst.releaseFence = nullptr;
3470
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003471 // Output buffers are empty when using HAL buffer manager
3472 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003473 mBufferRecords.pushInflightBuffer(
3474 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003475 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003476 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003477 }
3478 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003479 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003480}
3481
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003482void Camera3Device::HalInterface::cleanupNativeHandles(
3483 std::vector<native_handle_t*> *handles, bool closeFd) {
3484 if (handles == nullptr) {
3485 return;
3486 }
3487 if (closeFd) {
3488 for (auto& handle : *handles) {
3489 native_handle_close(handle);
3490 }
3491 }
3492 for (auto& handle : *handles) {
3493 native_handle_delete(handle);
3494 }
3495 handles->clear();
3496 return;
3497}
3498
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003499status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3500 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3501 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3502 if (!valid()) return INVALID_OPERATION;
3503
Emilian Peevaebbe412018-01-15 13:53:24 +00003504 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3505 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3506 if (castResult_3_4.isOk()) {
3507 hidlSession_3_4 = castResult_3_4;
3508 }
3509
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003510 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003511 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003512 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003513 if (hidlSession_3_4 != nullptr) {
3514 captureRequests_3_4.resize(batchSize);
3515 } else {
3516 captureRequests.resize(batchSize);
3517 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003518 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003519 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003520
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003521 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003522 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003523 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003524 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003525 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003526 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003527 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3528 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003529 }
3530 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003531 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003532 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003533 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003534 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003535 }
3536
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003537 std::vector<device::V3_2::BufferCache> cachesToRemove;
3538 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003539 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003540 for (auto& pair : mFreedBuffers) {
3541 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003542 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003543 cachesToRemove.push_back({pair.first, pair.second});
3544 }
3545 }
3546 mFreedBuffers.clear();
3547 }
3548
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003549 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3550 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003551
3552 // Write metadata to FMQ.
3553 for (size_t i = 0; i < batchSize; i++) {
3554 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003555 device::V3_2::CaptureRequest* captureRequest;
3556 if (hidlSession_3_4 != nullptr) {
3557 captureRequest = &captureRequests_3_4[i].v3_2;
3558 } else {
3559 captureRequest = &captureRequests[i];
3560 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003561
3562 if (request->settings != nullptr) {
3563 size_t settingsSize = get_camera_metadata_size(request->settings);
3564 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3565 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3566 captureRequest->settings.resize(0);
3567 captureRequest->fmqSettingsSize = settingsSize;
3568 } else {
3569 if (mRequestMetadataQueue != nullptr) {
3570 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3571 }
3572 captureRequest->settings.setToExternal(
3573 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3574 get_camera_metadata_size(request->settings));
3575 captureRequest->fmqSettingsSize = 0u;
3576 }
3577 } else {
3578 // A null request settings maps to a size-0 CameraMetadata
3579 captureRequest->settings.resize(0);
3580 captureRequest->fmqSettingsSize = 0u;
3581 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003582
3583 if (hidlSession_3_4 != nullptr) {
3584 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3585 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003586 if (request->physcam_settings != nullptr) {
3587 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3588 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3589 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3590 settingsSize)) {
3591 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3592 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3593 settingsSize;
3594 } else {
3595 if (mRequestMetadataQueue != nullptr) {
3596 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3597 }
3598 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3599 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3600 request->physcam_settings[j])),
3601 get_camera_metadata_size(request->physcam_settings[j]));
3602 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003603 }
Emilian Peev00420d22018-02-05 21:33:13 +00003604 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003605 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003606 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003607 }
3608 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3609 request->physcam_id[j];
3610 }
3611 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003612 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003613
3614 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003615 auto resultCallback =
3616 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3617 status = s;
3618 *numRequestProcessed = n;
3619 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003620 if (hidlSession_3_4 != nullptr) {
3621 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003622 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003623 } else {
3624 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003625 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003626 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003627 if (!err.isOk()) {
3628 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003629 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003630 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003631
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003632 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3633 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3634 __FUNCTION__, *numRequestProcessed, batchSize);
3635 status = common::V1_0::Status::INTERNAL_ERROR;
3636 }
3637
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003638 res = CameraProviderManager::mapToStatusT(status);
3639 if (res == OK) {
3640 if (mHidlSession->isRemote()) {
3641 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3642 // sent to camera HAL processes)
3643 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3644 } else {
3645 // In passthrough mode the FDs are now owned by HAL
3646 cleanupNativeHandles(&handlesCreated);
3647 }
3648 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003649 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003650 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003651 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003652 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003653}
3654
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003655status_t Camera3Device::HalInterface::flush() {
3656 ATRACE_NAME("CameraHal::flush");
3657 if (!valid()) return INVALID_OPERATION;
3658 status_t res = OK;
3659
Emilian Peev31abd0a2017-05-11 18:37:46 +01003660 auto err = mHidlSession->flush();
3661 if (!err.isOk()) {
3662 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3663 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003664 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003665 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003666 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003667
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003668 return res;
3669}
3670
Emilian Peev31abd0a2017-05-11 18:37:46 +01003671status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003672 ATRACE_NAME("CameraHal::dump");
3673 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003674
Emilian Peev31abd0a2017-05-11 18:37:46 +01003675 // Handled by CameraProviderManager::dump
3676
3677 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003678}
3679
3680status_t Camera3Device::HalInterface::close() {
3681 ATRACE_NAME("CameraHal::close()");
3682 if (!valid()) return INVALID_OPERATION;
3683 status_t res = OK;
3684
Emilian Peev31abd0a2017-05-11 18:37:46 +01003685 auto err = mHidlSession->close();
3686 // Interface will be dead shortly anyway, so don't log errors
3687 if (!err.isOk()) {
3688 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003689 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003690
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003691 return res;
3692}
3693
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003694void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3695 ATRACE_NAME("CameraHal::signalPipelineDrain");
3696 if (!valid() || mHidlSession_3_5 == nullptr) {
3697 ALOGE("%s called on invalid camera!", __FUNCTION__);
3698 return;
3699 }
3700
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003701 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003702 if (!err.isOk()) {
3703 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3704 return;
3705 }
3706}
3707
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003708status_t Camera3Device::HalInterface::switchToOffline(
3709 const std::vector<int32_t>& streamsToKeep,
3710 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003711 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3712 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003713 ATRACE_NAME("CameraHal::switchToOffline");
3714 if (!valid() || mHidlSession_3_6 == nullptr) {
3715 ALOGE("%s called on invalid camera!", __FUNCTION__);
3716 return INVALID_OPERATION;
3717 }
3718
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003719 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3720 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003721 return INVALID_OPERATION;
3722 }
3723
3724 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003725 auto resultCallback =
3726 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3727 status = s;
3728 *offlineSessionInfo = info;
3729 *offlineSession = session;
3730 };
3731 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3732
3733 if (!err.isOk()) {
3734 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3735 return DEAD_OBJECT;
3736 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003737
3738 status_t ret = CameraProviderManager::mapToStatusT(status);
3739 if (ret != OK) {
3740 return ret;
3741 }
3742
3743 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3744 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3745 // returns from switchToOffline.
3746
3747
3748 // Validate buffer caches
3749 std::vector<int32_t> streams;
3750 streams.reserve(offlineSessionInfo->offlineStreams.size());
3751 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3752 int32_t id = offlineStream.id;
3753 streams.push_back(id);
3754 // Verify buffer caches
3755 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3756 offlineStream.circulatingBufferIds.end());
3757 if (!verifyBufferIds(id, bufIds)) {
3758 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3759 return UNKNOWN_ERROR;
3760 }
3761 }
3762
3763 // Move buffer records
3764 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3765 bufferRecords->takeInflightBufferMap(mBufferRecords);
3766 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3767 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003768}
3769
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003770void Camera3Device::HalInterface::getInflightBufferKeys(
3771 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003772 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003773 return;
3774}
3775
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003776void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3777 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003778 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003779 return;
3780}
3781
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003782bool Camera3Device::HalInterface::verifyBufferIds(
3783 int32_t streamId, std::vector<uint64_t>& bufIds) {
3784 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003785}
3786
3787status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003788 int32_t frameNumber, int32_t streamId,
3789 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003790 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003791}
3792
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003793status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003794 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003795 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003796}
3797
3798// Find and pop a buffer_handle_t based on bufferId
3799status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003800 uint64_t bufferId,
3801 /*out*/ buffer_handle_t** buffer,
3802 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003803 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003804}
3805
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003806std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3807 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003808 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003809}
3810
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003811void Camera3Device::HalInterface::onBufferFreed(
3812 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003813 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3814 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3815 if (bufferId != BUFFER_ID_NO_BUFFER) {
3816 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003817 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003818}
3819
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003820void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003821 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3822 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3823 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003824 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3825 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003826}
3827
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003828/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003829 * RequestThread inner class methods
3830 */
3831
3832Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003833 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003834 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3835 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003836 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003837 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003838 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003839 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003840 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003841 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003842 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003843 mReconfigured(false),
3844 mDoPause(false),
3845 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003846 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003847 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003848 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003849 mCurrentAfTriggerId(0),
3850 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003851 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003852 mRepeatingLastFrameNumber(
3853 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003854 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003855 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003856 mRequestLatency(kRequestLatencyBinSize),
3857 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003858 mLatestSessionParams(sessionParamKeys.size()),
3859 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003860 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003861}
3862
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003863Camera3Device::RequestThread::~RequestThread() {}
3864
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003865void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003866 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003867 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003868 Mutex::Autolock l(mRequestLock);
3869 mListener = listener;
3870}
3871
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003872void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3873 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003874 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003875 Mutex::Autolock l(mRequestLock);
3876 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003877 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003878 // Prepare video stream for high speed recording.
3879 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003880 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003881}
3882
Jianing Wei90e59c92014-03-12 18:29:36 -07003883status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003884 List<sp<CaptureRequest> > &requests,
3885 /*out*/
3886 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003887 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003888 Mutex::Autolock l(mRequestLock);
3889 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3890 ++it) {
3891 mRequestQueue.push_back(*it);
3892 }
3893
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003894 if (lastFrameNumber != NULL) {
3895 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3896 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3897 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3898 *lastFrameNumber);
3899 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003900
Jianing Wei90e59c92014-03-12 18:29:36 -07003901 unpauseForNewRequests();
3902
3903 return OK;
3904}
3905
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003906
3907status_t Camera3Device::RequestThread::queueTrigger(
3908 RequestTrigger trigger[],
3909 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003910 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003911 Mutex::Autolock l(mTriggerMutex);
3912 status_t ret;
3913
3914 for (size_t i = 0; i < count; ++i) {
3915 ret = queueTriggerLocked(trigger[i]);
3916
3917 if (ret != OK) {
3918 return ret;
3919 }
3920 }
3921
3922 return OK;
3923}
3924
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003925const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3926 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003927 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003928 if (d != nullptr) return d->mId;
3929 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003930}
3931
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003932status_t Camera3Device::RequestThread::queueTriggerLocked(
3933 RequestTrigger trigger) {
3934
3935 uint32_t tag = trigger.metadataTag;
3936 ssize_t index = mTriggerMap.indexOfKey(tag);
3937
3938 switch (trigger.getTagType()) {
3939 case TYPE_BYTE:
3940 // fall-through
3941 case TYPE_INT32:
3942 break;
3943 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003944 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3945 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003946 return INVALID_OPERATION;
3947 }
3948
3949 /**
3950 * Collect only the latest trigger, since we only have 1 field
3951 * in the request settings per trigger tag, and can't send more than 1
3952 * trigger per request.
3953 */
3954 if (index != NAME_NOT_FOUND) {
3955 mTriggerMap.editValueAt(index) = trigger;
3956 } else {
3957 mTriggerMap.add(tag, trigger);
3958 }
3959
3960 return OK;
3961}
3962
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003963status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003964 const RequestList &requests,
3965 /*out*/
3966 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003967 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003968 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003969 if (lastFrameNumber != NULL) {
3970 *lastFrameNumber = mRepeatingLastFrameNumber;
3971 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003972 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003973 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003974 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3975 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003976
3977 unpauseForNewRequests();
3978
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003979 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003980 return OK;
3981}
3982
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003983bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003984 if (mRepeatingRequests.empty()) {
3985 return false;
3986 }
3987 int32_t requestId = requestIn->mResultExtras.requestId;
3988 const RequestList &repeatRequests = mRepeatingRequests;
3989 // All repeating requests are guaranteed to have same id so only check first quest
3990 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3991 return (firstRequest->mResultExtras.requestId == requestId);
3992}
3993
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003994status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003995 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003996 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003997 return clearRepeatingRequestsLocked(lastFrameNumber);
3998
3999}
4000
4001status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004002 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004003 if (lastFrameNumber != NULL) {
4004 *lastFrameNumber = mRepeatingLastFrameNumber;
4005 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004006 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004007 return OK;
4008}
4009
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004010status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004011 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004012 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004013 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004014 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004015
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004016 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004017
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004018 // Send errors for all requests pending in the request queue, including
4019 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004020 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004021 if (listener != NULL) {
4022 for (RequestList::iterator it = mRequestQueue.begin();
4023 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004024 // Abort the input buffers for reprocess requests.
4025 if ((*it)->mInputStream != NULL) {
4026 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004027 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4028 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004029 if (res != OK) {
4030 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4031 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4032 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07004033 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004034 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4035 if (res != OK) {
4036 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4037 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4038 }
4039 }
4040 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004041 // Set the frame number this request would have had, if it
4042 // had been submitted; this frame number will not be reused.
4043 // The requestId and burstId fields were set when the request was
4044 // submitted originally (in convertMetadataListToRequestListLocked)
4045 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004046 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004047 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004048 }
4049 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004050 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004051
4052 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004053 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004054 if (lastFrameNumber != NULL) {
4055 *lastFrameNumber = mRepeatingLastFrameNumber;
4056 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004057 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004058 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004059 return OK;
4060}
4061
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004062status_t Camera3Device::RequestThread::flush() {
4063 ATRACE_CALL();
4064 Mutex::Autolock l(mFlushLock);
4065
Emilian Peev08dd2452017-04-06 16:55:14 +01004066 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004067}
4068
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004069void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004070 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004071 Mutex::Autolock l(mPauseLock);
4072 mDoPause = paused;
4073 mDoPauseSignal.signal();
4074}
4075
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004076status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4077 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004078 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004079 Mutex::Autolock l(mLatestRequestMutex);
4080 status_t res;
4081 while (mLatestRequestId != requestId) {
4082 nsecs_t startTime = systemTime();
4083
4084 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4085 if (res != OK) return res;
4086
4087 timeout -= (systemTime() - startTime);
4088 }
4089
4090 return OK;
4091}
4092
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004093void Camera3Device::RequestThread::requestExit() {
4094 // Call parent to set up shutdown
4095 Thread::requestExit();
4096 // The exit from any possible waits
4097 mDoPauseSignal.signal();
4098 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004099
4100 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4101 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004102}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004103
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004104void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004105 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004106 bool surfaceAbandoned = false;
4107 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004108 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004109 {
4110 Mutex::Autolock l(mRequestLock);
4111 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4112 // repeating requests.
4113 for (const auto& request : mRepeatingRequests) {
4114 for (const auto& s : request->mOutputStreams) {
4115 if (s->isAbandoned()) {
4116 surfaceAbandoned = true;
4117 clearRepeatingRequestsLocked(&lastFrameNumber);
4118 break;
4119 }
4120 }
4121 if (surfaceAbandoned) {
4122 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004123 }
4124 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004125 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004126 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004127
4128 if (listener != NULL && surfaceAbandoned) {
4129 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004130 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004131}
4132
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004133bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004134 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004135 status_t res;
4136 size_t batchSize = mNextRequests.size();
4137 std::vector<camera3_capture_request_t*> requests(batchSize);
4138 uint32_t numRequestProcessed = 0;
4139 for (size_t i = 0; i < batchSize; i++) {
4140 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004141 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004142 }
4143
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004144 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4145
4146 bool triggerRemoveFailed = false;
4147 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4148 for (size_t i = 0; i < numRequestProcessed; i++) {
4149 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4150 nextRequest.submitted = true;
4151
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004152 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004153
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004154 if (!triggerRemoveFailed) {
4155 // Remove any previously queued triggers (after unlock)
4156 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4157 if (removeTriggerRes != OK) {
4158 triggerRemoveFailed = true;
4159 triggerFailedRequest = nextRequest;
4160 }
4161 }
4162 }
4163
4164 if (triggerRemoveFailed) {
4165 SET_ERR("RequestThread: Unable to remove triggers "
4166 "(capture request %d, HAL device: %s (%d)",
4167 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4168 cleanUpFailedRequests(/*sendRequestError*/ false);
4169 return false;
4170 }
4171
4172 if (res != OK) {
4173 // Should only get a failure here for malformed requests or device-level
4174 // errors, so consider all errors fatal. Bad metadata failures should
4175 // come through notify.
4176 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4177 mNextRequests[numRequestProcessed].halRequest.frame_number,
4178 strerror(-res), res);
4179 cleanUpFailedRequests(/*sendRequestError*/ false);
4180 return false;
4181 }
4182 return true;
4183}
4184
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004185nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4186 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4187 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4188 find_camera_metadata_ro_entry(request,
4189 ANDROID_CONTROL_AE_MODE,
4190 &e);
4191 if (e.count == 0) return maxExpectedDuration;
4192
4193 switch (e.data.u8[0]) {
4194 case ANDROID_CONTROL_AE_MODE_OFF:
4195 find_camera_metadata_ro_entry(request,
4196 ANDROID_SENSOR_EXPOSURE_TIME,
4197 &e);
4198 if (e.count > 0) {
4199 maxExpectedDuration = e.data.i64[0];
4200 }
4201 find_camera_metadata_ro_entry(request,
4202 ANDROID_SENSOR_FRAME_DURATION,
4203 &e);
4204 if (e.count > 0) {
4205 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4206 }
4207 break;
4208 default:
4209 find_camera_metadata_ro_entry(request,
4210 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4211 &e);
4212 if (e.count > 1) {
4213 maxExpectedDuration = 1e9 / e.data.u8[0];
4214 }
4215 break;
4216 }
4217
4218 return maxExpectedDuration;
4219}
4220
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004221bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4222 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4223 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4224 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4225 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4226 return true;
4227 }
4228
4229 return false;
4230}
4231
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004232void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4233 // Update the latest request sent to HAL
4234 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4235 Mutex::Autolock al(mLatestRequestMutex);
4236
4237 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4238 mLatestRequest.acquire(cloned);
4239
4240 mLatestPhysicalRequest.clear();
4241 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4242 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4243 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4244 CameraMetadata(cloned));
4245 }
4246
4247 sp<Camera3Device> parent = mParent.promote();
4248 if (parent != NULL) {
4249 parent->monitorMetadata(TagMonitor::REQUEST,
4250 nextRequest.halRequest.frame_number,
4251 0, mLatestRequest, mLatestPhysicalRequest);
4252 }
4253 }
4254
4255 if (nextRequest.halRequest.settings != NULL) {
4256 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4257 nextRequest.halRequest.settings);
4258 }
4259
4260 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4261}
4262
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004263bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4264 ATRACE_CALL();
4265 bool updatesDetected = false;
4266
Emilian Peev4ec17882019-01-24 17:16:58 -08004267 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004268 for (auto tag : mSessionParamKeys) {
4269 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004270 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004271
4272 if (entry.count > 0) {
4273 bool isDifferent = false;
4274 if (lastEntry.count > 0) {
4275 // Have a last value, compare to see if changed
4276 if (lastEntry.type == entry.type &&
4277 lastEntry.count == entry.count) {
4278 // Same type and count, compare values
4279 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4280 size_t entryBytes = bytesPerValue * lastEntry.count;
4281 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4282 if (cmp != 0) {
4283 isDifferent = true;
4284 }
4285 } else {
4286 // Count or type has changed
4287 isDifferent = true;
4288 }
4289 } else {
4290 // No last entry, so always consider to be different
4291 isDifferent = true;
4292 }
4293
4294 if (isDifferent) {
4295 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004296 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4297 updatesDetected = true;
4298 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004299 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004300 }
4301 } else if (lastEntry.count > 0) {
4302 // Value has been removed
4303 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004304 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004305 updatesDetected = true;
4306 }
4307 }
4308
Emilian Peev4ec17882019-01-24 17:16:58 -08004309 bool reconfigureRequired;
4310 if (updatesDetected) {
4311 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4312 updatedParams);
4313 mLatestSessionParams = updatedParams;
4314 } else {
4315 reconfigureRequired = false;
4316 }
4317
4318 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004319}
4320
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004321bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004322 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004324 // Any function called from threadLoop() must not hold mInterfaceLock since
4325 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4326 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004327
4328 // Handle paused state.
4329 if (waitIfPaused()) {
4330 return true;
4331 }
4332
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004333 // Wait for the next batch of requests.
4334 waitForNextRequestBatch();
4335 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004336 return true;
4337 }
4338
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004339 // Get the latest request ID, if any
4340 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004341 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004342 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004343 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004344 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004345 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004346 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4347 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004348 }
4349
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004350 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4351 // or a single request from streaming or burst. In either case the first element
4352 // should contain the latest camera settings that we need to check for any session
4353 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004354 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004355 res = OK;
4356
4357 //Input stream buffers are already acquired at this point so an input stream
4358 //will not be able to move to idle state unless we force it.
4359 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4360 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4361 if (res != OK) {
4362 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4363 cleanUpFailedRequests(/*sendRequestError*/ false);
4364 return false;
4365 }
4366 }
4367
4368 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004369 sp<Camera3Device> parent = mParent.promote();
4370 if (parent != nullptr) {
4371 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004372 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004373 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004374
4375 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4376 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4377 if (res != OK) {
4378 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4379 cleanUpFailedRequests(/*sendRequestError*/ false);
4380 return false;
4381 }
4382 }
4383 }
4384 }
4385
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004386 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004387 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004388 if (res == TIMED_OUT) {
4389 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004390 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004391 // Check if any stream is abandoned.
4392 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004393 return true;
4394 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004395 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004396 return false;
4397 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004398
Zhijun Hecc27e112013-10-03 16:12:43 -07004399 // Inform waitUntilRequestProcessed thread of a new request ID
4400 {
4401 Mutex::Autolock al(mLatestRequestMutex);
4402
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004403 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004404 mLatestRequestSignal.signal();
4405 }
4406
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004407 // Submit a batch of requests to HAL.
4408 // Use flush lock only when submitting multilple requests in a batch.
4409 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4410 // which may take a long time to finish so synchronizing flush() and
4411 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4412 // For now, only synchronize for high speed recording and we should figure something out for
4413 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004414 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004415
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004416 if (useFlushLock) {
4417 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 }
4419
Zhijun Hef0645c12016-08-02 00:58:11 -07004420 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004421 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004422
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004423 sp<Camera3Device> parent = mParent.promote();
4424 if (parent != nullptr) {
4425 parent->mRequestBufferSM.onSubmittingRequest();
4426 }
4427
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004428 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004429 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004430 submitRequestSuccess = sendRequestsBatch();
4431
Shuzhen Wang686f6442017-06-20 16:16:04 -07004432 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4433 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004434
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004435 if (useFlushLock) {
4436 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004437 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004438
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004439 // Unset as current request
4440 {
4441 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004442 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004443 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004444 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004445
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004446 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004447}
4448
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004449status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004450 ATRACE_CALL();
4451
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004452 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004453 for (size_t i = 0; i < mNextRequests.size(); i++) {
4454 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004455 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4456 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4457 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4458
4459 // Prepare a request to HAL
4460 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4461
4462 // Insert any queued triggers (before metadata is locked)
4463 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004464 if (res < 0) {
4465 SET_ERR("RequestThread: Unable to insert triggers "
4466 "(capture request %d, HAL device: %s (%d)",
4467 halRequest->frame_number, strerror(-res), res);
4468 return INVALID_OPERATION;
4469 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004470
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004471 int triggerCount = res;
4472 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4473 mPrevTriggers = triggerCount;
4474
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004475 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004477 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004478 bool newRequest =
4479 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004480 // Request settings are all the same within one batch, so only treat the first
4481 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004482 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004483 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004484 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004485 /**
4486 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004487 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004488 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004489 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004490 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004491 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004492 "(capture request %d, HAL device: %s (%d)",
4493 halRequest->frame_number, strerror(-res), res);
4494 return INVALID_OPERATION;
4495 }
4496
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004497 {
4498 // Correct metadata regions for distortion correction if enabled
4499 sp<Camera3Device> parent = mParent.promote();
4500 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004501 List<PhysicalCameraSettings>::iterator it;
4502 for (it = captureRequest->mSettingsList.begin();
4503 it != captureRequest->mSettingsList.end(); it++) {
4504 if (parent->mDistortionMappers.find(it->cameraId) ==
4505 parent->mDistortionMappers.end()) {
4506 continue;
4507 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004508
4509 if (!captureRequest->mDistortionCorrectionUpdated) {
4510 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4511 &(it->metadata));
4512 if (res != OK) {
4513 SET_ERR("RequestThread: Unable to correct capture requests "
4514 "for lens distortion for request %d: %s (%d)",
4515 halRequest->frame_number, strerror(-res), res);
4516 return INVALID_OPERATION;
4517 }
4518 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004519 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004520 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004521
4522 for (it = captureRequest->mSettingsList.begin();
4523 it != captureRequest->mSettingsList.end(); it++) {
4524 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4525 parent->mZoomRatioMappers.end()) {
4526 continue;
4527 }
4528
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004529 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004530 cameraIdsWithZoom.insert(it->cameraId);
4531 }
4532
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004533 if (!captureRequest->mZoomRatioUpdated) {
4534 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4535 &(it->metadata));
4536 if (res != OK) {
4537 SET_ERR("RequestThread: Unable to correct capture requests "
4538 "for zoom ratio for request %d: %s (%d)",
4539 halRequest->frame_number, strerror(-res), res);
4540 return INVALID_OPERATION;
4541 }
4542 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004543 }
4544 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004545 if (captureRequest->mRotateAndCropAuto &&
4546 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004547 for (it = captureRequest->mSettingsList.begin();
4548 it != captureRequest->mSettingsList.end(); it++) {
4549 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4550 if (mapper != parent->mRotateAndCropMappers.end()) {
4551 res = mapper->second.updateCaptureRequest(&(it->metadata));
4552 if (res != OK) {
4553 SET_ERR("RequestThread: Unable to correct capture requests "
4554 "for rotate-and-crop for request %d: %s (%d)",
4555 halRequest->frame_number, strerror(-res), res);
4556 return INVALID_OPERATION;
4557 }
4558 }
4559 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004560 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004561 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004562 }
4563 }
4564
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004565 /**
4566 * The request should be presorted so accesses in HAL
4567 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4568 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004569 captureRequest->mSettingsList.begin()->metadata.sort();
4570 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004571 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004572 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004573 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4574
4575 IF_ALOGV() {
4576 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4577 find_camera_metadata_ro_entry(
4578 halRequest->settings,
4579 ANDROID_CONTROL_AF_TRIGGER,
4580 &e
4581 );
4582 if (e.count > 0) {
4583 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4584 __FUNCTION__,
4585 halRequest->frame_number,
4586 e.data.u8[0]);
4587 }
4588 }
4589 } else {
4590 // leave request.settings NULL to indicate 'reuse latest given'
4591 ALOGVV("%s: Request settings are REUSED",
4592 __FUNCTION__);
4593 }
4594
Emilian Peevaebbe412018-01-15 13:53:24 +00004595 if (captureRequest->mSettingsList.size() > 1) {
4596 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4597 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004598 if (newRequest) {
4599 halRequest->physcam_settings =
4600 new const camera_metadata* [halRequest->num_physcam_settings];
4601 } else {
4602 halRequest->physcam_settings = nullptr;
4603 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004604 auto it = ++captureRequest->mSettingsList.begin();
4605 size_t i = 0;
4606 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4607 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004608 if (newRequest) {
4609 it->metadata.sort();
4610 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4611 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004612 }
4613 }
4614
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004615 uint32_t totalNumBuffers = 0;
4616
4617 // Fill in buffers
4618 if (captureRequest->mInputStream != NULL) {
4619 halRequest->input_buffer = &captureRequest->mInputBuffer;
4620 totalNumBuffers += 1;
4621 } else {
4622 halRequest->input_buffer = NULL;
4623 }
4624
4625 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4626 captureRequest->mOutputStreams.size());
4627 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004628 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004629
4630 sp<Camera3Device> parent = mParent.promote();
4631 if (parent == NULL) {
4632 // Should not happen, and nowhere to send errors to, so just log it
4633 CLOGE("RequestThread: Parent is gone");
4634 return INVALID_OPERATION;
4635 }
4636 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4637
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004638 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004639 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004640 sp<Camera3OutputStreamInterface> outputStream =
4641 captureRequest->mOutputStreams.editItemAt(j);
4642 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004643
4644 // Prepare video buffers for high speed recording on the first video request.
4645 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4646 // Only try to prepare video stream on the first video request.
4647 mPrepareVideoStream = false;
4648
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004649 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4650 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004651 while (res == NOT_ENOUGH_DATA) {
4652 res = outputStream->prepareNextBuffer();
4653 }
4654 if (res != OK) {
4655 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4656 __FUNCTION__, strerror(-res), res);
4657 outputStream->cancelPrepare();
4658 }
4659 }
4660
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004661 std::vector<size_t> uniqueSurfaceIds;
4662 res = outputStream->getUniqueSurfaceIds(
4663 captureRequest->mOutputSurfaces[streamId],
4664 &uniqueSurfaceIds);
4665 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4666 if (res != OK && res != INVALID_OPERATION) {
4667 ALOGE("%s: failed to query stream %d unique surface IDs",
4668 __FUNCTION__, streamId);
4669 return res;
4670 }
4671 if (res == OK) {
4672 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4673 }
4674
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004675 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004676 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004677 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004678 return TIMED_OUT;
4679 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004680 // HAL will request buffer through requestStreamBuffer API
4681 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4682 buffer.stream = outputStream->asHalStream();
4683 buffer.buffer = nullptr;
4684 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4685 buffer.acquire_fence = -1;
4686 buffer.release_fence = -1;
4687 } else {
4688 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4689 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004690 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004691 if (res != OK) {
4692 // Can't get output buffer from gralloc queue - this could be due to
4693 // abandoned queue or other consumer misbehavior, so not a fatal
4694 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004695 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004696 " %s (%d)", strerror(-res), res);
4697
4698 return TIMED_OUT;
4699 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004700 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004701
4702 {
4703 sp<Camera3Device> parent = mParent.promote();
4704 if (parent != nullptr) {
4705 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4706 for (const auto& settings : captureRequest->mSettingsList) {
4707 if ((streamCameraId.isEmpty() &&
4708 parent->getId() == settings.cameraId.c_str()) ||
4709 streamCameraId == settings.cameraId.c_str()) {
4710 outputStream->fireBufferRequestForFrameNumber(
4711 captureRequest->mResultExtras.frameNumber,
4712 settings.metadata);
4713 }
4714 }
4715 }
4716 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004717
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004718 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4719
4720 if (!physicalCameraId.isEmpty()) {
4721 // Physical stream isn't supported for input request.
4722 if (halRequest->input_buffer) {
4723 CLOGE("Physical stream is not supported for input request");
4724 return INVALID_OPERATION;
4725 }
4726 requestedPhysicalCameras.insert(physicalCameraId);
4727 }
4728 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004729 }
4730 totalNumBuffers += halRequest->num_output_buffers;
4731
4732 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004733 // If this request list is for constrained high speed recording (not
4734 // preview), and the current request is not the last one in the batch,
4735 // do not send callback to the app.
4736 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004737 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004738 hasCallback = false;
4739 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004740 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004741 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004742 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4743 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4744 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4745 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4746 isStillCapture = true;
4747 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4748 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004749
4750 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4751 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4752 isZslCapture = true;
4753 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004754 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004755 res = parent->registerInFlight(halRequest->frame_number,
4756 totalNumBuffers, captureRequest->mResultExtras,
4757 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004758 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004759 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004760 requestedPhysicalCameras, isStillCapture, isZslCapture,
4761 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004762 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004763 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004764 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4765 ", burstId = %" PRId32 ".",
4766 __FUNCTION__,
4767 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4768 captureRequest->mResultExtras.burstId);
4769 if (res != OK) {
4770 SET_ERR("RequestThread: Unable to register new in-flight request:"
4771 " %s (%d)", strerror(-res), res);
4772 return INVALID_OPERATION;
4773 }
4774 }
4775
4776 return OK;
4777}
4778
Igor Murashkin1e479c02013-09-06 16:55:14 -07004779CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004780 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004781 Mutex::Autolock al(mLatestRequestMutex);
4782
4783 ALOGV("RequestThread::%s", __FUNCTION__);
4784
4785 return mLatestRequest;
4786}
4787
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004788bool Camera3Device::RequestThread::isStreamPending(
4789 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004790 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004791 Mutex::Autolock l(mRequestLock);
4792
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004793 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004794 if (!nextRequest.submitted) {
4795 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4796 if (stream == s) return true;
4797 }
4798 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004799 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004800 }
4801
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004802 for (const auto& request : mRequestQueue) {
4803 for (const auto& s : request->mOutputStreams) {
4804 if (stream == s) return true;
4805 }
4806 if (stream == request->mInputStream) return true;
4807 }
4808
4809 for (const auto& request : mRepeatingRequests) {
4810 for (const auto& s : request->mOutputStreams) {
4811 if (stream == s) return true;
4812 }
4813 if (stream == request->mInputStream) return true;
4814 }
4815
4816 return false;
4817}
Jianing Weicb0652e2014-03-12 18:29:36 -07004818
Emilian Peev40ead602017-09-26 15:46:36 +01004819bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4820 ATRACE_CALL();
4821 Mutex::Autolock l(mRequestLock);
4822
4823 for (const auto& nextRequest : mNextRequests) {
4824 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4825 if (s.first == streamId) {
4826 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4827 if (it != s.second.end()) {
4828 return true;
4829 }
4830 }
4831 }
4832 }
4833
4834 for (const auto& request : mRequestQueue) {
4835 for (const auto& s : request->mOutputSurfaces) {
4836 if (s.first == streamId) {
4837 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4838 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004839 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004840 }
4841 }
4842 }
4843 }
4844
4845 for (const auto& request : mRepeatingRequests) {
4846 for (const auto& s : request->mOutputSurfaces) {
4847 if (s.first == streamId) {
4848 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4849 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004850 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004851 }
4852 }
4853 }
4854 }
4855
4856 return false;
4857}
4858
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004859void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4860 if (!mUseHalBufManager) {
4861 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4862 return;
4863 }
4864
4865 Mutex::Autolock pl(mPauseLock);
4866 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004867 mInterface->signalPipelineDrain(streamIds);
4868 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004869 }
4870 // If request thread is still busy, wait until paused then notify HAL
4871 mNotifyPipelineDrain = true;
4872 mStreamIdsToBeDrained = streamIds;
4873}
4874
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004875void Camera3Device::RequestThread::resetPipelineDrain() {
4876 Mutex::Autolock pl(mPauseLock);
4877 mNotifyPipelineDrain = false;
4878 mStreamIdsToBeDrained.clear();
4879}
4880
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004881void Camera3Device::RequestThread::clearPreviousRequest() {
4882 Mutex::Autolock l(mRequestLock);
4883 mPrevRequest.clear();
4884}
4885
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004886status_t Camera3Device::RequestThread::switchToOffline(
4887 const std::vector<int32_t>& streamsToKeep,
4888 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004889 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4890 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004891 Mutex::Autolock l(mRequestLock);
4892 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4893
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004894 // Wait until request thread is fully stopped
4895 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4896
4897 // We could also check for mRepeatingRequests.empty(), but the API interface
4898 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4899 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004900 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4901 while (!queueEmpty) {
4902 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4903 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004904 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004905 return res;
4906 } else if (res != OK) {
4907 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4908 __FUNCTION__, strerror(-res), res);
4909 return res;
4910 }
4911 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4912 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004913
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004914 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004915 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004916}
4917
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004918status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4919 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4920 ATRACE_CALL();
4921 Mutex::Autolock l(mTriggerMutex);
4922 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4923 return BAD_VALUE;
4924 }
4925 mRotateAndCropOverride = rotateAndCropValue;
4926 return OK;
4927}
4928
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004929nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004930 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004931 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004932 return mExpectedInflightDuration > kMinInflightDuration ?
4933 mExpectedInflightDuration : kMinInflightDuration;
4934}
4935
Emilian Peevaebbe412018-01-15 13:53:24 +00004936void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4937 camera3_capture_request_t *halRequest) {
4938 if ((request == nullptr) || (halRequest == nullptr)) {
4939 ALOGE("%s: Invalid request!", __FUNCTION__);
4940 return;
4941 }
4942
4943 if (halRequest->num_physcam_settings > 0) {
4944 if (halRequest->physcam_id != nullptr) {
4945 delete [] halRequest->physcam_id;
4946 halRequest->physcam_id = nullptr;
4947 }
4948 if (halRequest->physcam_settings != nullptr) {
4949 auto it = ++(request->mSettingsList.begin());
4950 size_t i = 0;
4951 for (; it != request->mSettingsList.end(); it++, i++) {
4952 it->metadata.unlock(halRequest->physcam_settings[i]);
4953 }
4954 delete [] halRequest->physcam_settings;
4955 halRequest->physcam_settings = nullptr;
4956 }
4957 }
4958}
4959
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004960void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4961 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004962 return;
4963 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004964
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004965 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004966 // Skip the ones that have been submitted successfully.
4967 if (nextRequest.submitted) {
4968 continue;
4969 }
4970
4971 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4972 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4973 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4974
4975 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004976 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004977 }
4978
Emilian Peevaebbe412018-01-15 13:53:24 +00004979 cleanupPhysicalSettings(captureRequest, halRequest);
4980
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004981 if (captureRequest->mInputStream != NULL) {
4982 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4983 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4984 }
4985
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004986 // No output buffer can be returned when using HAL buffer manager
4987 if (!mUseHalBufManager) {
4988 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4989 //Buffers that failed processing could still have
4990 //valid acquire fence.
4991 int acquireFence = (*outputBuffers)[i].acquire_fence;
4992 if (0 <= acquireFence) {
4993 close(acquireFence);
4994 outputBuffers->editItemAt(i).acquire_fence = -1;
4995 }
4996 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4997 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4998 /*timestampIncreasing*/true, std::vector<size_t> (),
4999 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005000 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005001 }
5002
5003 if (sendRequestError) {
5004 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005005 sp<NotificationListener> listener = mListener.promote();
5006 if (listener != NULL) {
5007 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005008 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005009 captureRequest->mResultExtras);
5010 }
5011 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005012
5013 // Remove yet-to-be submitted inflight request from inflightMap
5014 {
5015 sp<Camera3Device> parent = mParent.promote();
5016 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005017 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005018 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5019 if (idx >= 0) {
5020 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5021 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5022 parent->removeInFlightMapEntryLocked(idx);
5023 }
5024 }
5025 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005026 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005027
5028 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005029 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005030}
5031
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005032void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005033 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034 // Optimized a bit for the simple steady-state case (single repeating
5035 // request), to avoid putting that request in the queue temporarily.
5036 Mutex::Autolock l(mRequestLock);
5037
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005038 assert(mNextRequests.empty());
5039
5040 NextRequest nextRequest;
5041 nextRequest.captureRequest = waitForNextRequestLocked();
5042 if (nextRequest.captureRequest == nullptr) {
5043 return;
5044 }
5045
5046 nextRequest.halRequest = camera3_capture_request_t();
5047 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005048 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005049
5050 // Wait for additional requests
5051 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5052
5053 for (size_t i = 1; i < batchSize; i++) {
5054 NextRequest additionalRequest;
5055 additionalRequest.captureRequest = waitForNextRequestLocked();
5056 if (additionalRequest.captureRequest == nullptr) {
5057 break;
5058 }
5059
5060 additionalRequest.halRequest = camera3_capture_request_t();
5061 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005062 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005063 }
5064
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005065 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005066 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005067 mNextRequests.size(), batchSize);
5068 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005069 }
5070
5071 return;
5072}
5073
5074sp<Camera3Device::CaptureRequest>
5075 Camera3Device::RequestThread::waitForNextRequestLocked() {
5076 status_t res;
5077 sp<CaptureRequest> nextRequest;
5078
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005079 while (mRequestQueue.empty()) {
5080 if (!mRepeatingRequests.empty()) {
5081 // Always atomically enqueue all requests in a repeating request
5082 // list. Guarantees a complete in-sequence set of captures to
5083 // application.
5084 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005085 if (mFirstRepeating) {
5086 mFirstRepeating = false;
5087 } else {
5088 for (auto& request : requests) {
5089 // For repeating requests, override timestamp request using
5090 // the time a request is inserted into the request queue,
5091 // because the original repeating request will have an old
5092 // fixed timestamp.
5093 request->mRequestTimeNs = systemTime();
5094 }
5095 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005096 RequestList::const_iterator firstRequest =
5097 requests.begin();
5098 nextRequest = *firstRequest;
5099 mRequestQueue.insert(mRequestQueue.end(),
5100 ++firstRequest,
5101 requests.end());
5102 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005103
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005104 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005105
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005106 break;
5107 }
5108
5109 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5110
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005111 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5112 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005113 Mutex::Autolock pl(mPauseLock);
5114 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005115 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005116 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005117 if (mNotifyPipelineDrain) {
5118 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5119 mNotifyPipelineDrain = false;
5120 mStreamIdsToBeDrained.clear();
5121 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005122 // Let the tracker know
5123 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5124 if (statusTracker != 0) {
5125 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5126 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005127 sp<Camera3Device> parent = mParent.promote();
5128 if (parent != nullptr) {
5129 parent->mRequestBufferSM.onRequestThreadPaused();
5130 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005131 }
5132 // Stop waiting for now and let thread management happen
5133 return NULL;
5134 }
5135 }
5136
5137 if (nextRequest == NULL) {
5138 // Don't have a repeating request already in hand, so queue
5139 // must have an entry now.
5140 RequestList::iterator firstRequest =
5141 mRequestQueue.begin();
5142 nextRequest = *firstRequest;
5143 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005144 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5145 sp<NotificationListener> listener = mListener.promote();
5146 if (listener != NULL) {
5147 listener->notifyRequestQueueEmpty();
5148 }
5149 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005150 }
5151
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005152 // In case we've been unpaused by setPaused clearing mDoPause, need to
5153 // update internal pause state (capture/setRepeatingRequest unpause
5154 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005155 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005156 if (mPaused) {
5157 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5158 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5159 if (statusTracker != 0) {
5160 statusTracker->markComponentActive(mStatusId);
5161 }
5162 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005163 mPaused = false;
5164
5165 // Check if we've reconfigured since last time, and reset the preview
5166 // request if so. Can't use 'NULL request == repeat' across configure calls.
5167 if (mReconfigured) {
5168 mPrevRequest.clear();
5169 mReconfigured = false;
5170 }
5171
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005172 if (nextRequest != NULL) {
5173 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005174 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5175 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005176
5177 // Since RequestThread::clear() removes buffers from the input stream,
5178 // get the right buffer here before unlocking mRequestLock
5179 if (nextRequest->mInputStream != NULL) {
5180 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5181 if (res != OK) {
5182 // Can't get input buffer from gralloc queue - this could be due to
5183 // disconnected queue or other producer misbehavior, so not a fatal
5184 // error
5185 ALOGE("%s: Can't get input buffer, skipping request:"
5186 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005187
5188 sp<NotificationListener> listener = mListener.promote();
5189 if (listener != NULL) {
5190 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005191 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005192 nextRequest->mResultExtras);
5193 }
5194 return NULL;
5195 }
5196 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005197 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005198
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005199 return nextRequest;
5200}
5201
5202bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005203 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005204 status_t res;
5205 Mutex::Autolock l(mPauseLock);
5206 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005207 if (mPaused == false) {
5208 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005209 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005210 if (mNotifyPipelineDrain) {
5211 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5212 mNotifyPipelineDrain = false;
5213 mStreamIdsToBeDrained.clear();
5214 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005215 // Let the tracker know
5216 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5217 if (statusTracker != 0) {
5218 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5219 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005220 sp<Camera3Device> parent = mParent.promote();
5221 if (parent != nullptr) {
5222 parent->mRequestBufferSM.onRequestThreadPaused();
5223 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005226 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005227 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005228 return true;
5229 }
5230 }
5231 // We don't set mPaused to false here, because waitForNextRequest needs
5232 // to further manage the paused state in case of starvation.
5233 return false;
5234}
5235
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005236void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005237 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005238 // With work to do, mark thread as unpaused.
5239 // If paused by request (setPaused), don't resume, to avoid
5240 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005241 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005242 Mutex::Autolock p(mPauseLock);
5243 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005244 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5245 if (mPaused) {
5246 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5247 if (statusTracker != 0) {
5248 statusTracker->markComponentActive(mStatusId);
5249 }
5250 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005251 mPaused = false;
5252 }
5253}
5254
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005255void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5256 sp<Camera3Device> parent = mParent.promote();
5257 if (parent != NULL) {
5258 va_list args;
5259 va_start(args, fmt);
5260
5261 parent->setErrorStateV(fmt, args);
5262
5263 va_end(args);
5264 }
5265}
5266
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005267status_t Camera3Device::RequestThread::insertTriggers(
5268 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005269 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005270 Mutex::Autolock al(mTriggerMutex);
5271
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005272 sp<Camera3Device> parent = mParent.promote();
5273 if (parent == NULL) {
5274 CLOGE("RequestThread: Parent is gone");
5275 return DEAD_OBJECT;
5276 }
5277
Emilian Peevaebbe412018-01-15 13:53:24 +00005278 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005279 size_t count = mTriggerMap.size();
5280
5281 for (size_t i = 0; i < count; ++i) {
5282 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005283 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005284
5285 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5286 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5287 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005288 if (isAeTrigger) {
5289 request->mResultExtras.precaptureTriggerId = triggerId;
5290 mCurrentPreCaptureTriggerId = triggerId;
5291 } else {
5292 request->mResultExtras.afTriggerId = triggerId;
5293 mCurrentAfTriggerId = triggerId;
5294 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005295 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005296 }
5297
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005298 camera_metadata_entry entry = metadata.find(tag);
5299
5300 if (entry.count > 0) {
5301 /**
5302 * Already has an entry for this trigger in the request.
5303 * Rewrite it with our requested trigger value.
5304 */
5305 RequestTrigger oldTrigger = trigger;
5306
5307 oldTrigger.entryValue = entry.data.u8[0];
5308
5309 mTriggerReplacedMap.add(tag, oldTrigger);
5310 } else {
5311 /**
5312 * More typical, no trigger entry, so we just add it
5313 */
5314 mTriggerRemovedMap.add(tag, trigger);
5315 }
5316
5317 status_t res;
5318
5319 switch (trigger.getTagType()) {
5320 case TYPE_BYTE: {
5321 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5322 res = metadata.update(tag,
5323 &entryValue,
5324 /*count*/1);
5325 break;
5326 }
5327 case TYPE_INT32:
5328 res = metadata.update(tag,
5329 &trigger.entryValue,
5330 /*count*/1);
5331 break;
5332 default:
5333 ALOGE("%s: Type not supported: 0x%x",
5334 __FUNCTION__,
5335 trigger.getTagType());
5336 return INVALID_OPERATION;
5337 }
5338
5339 if (res != OK) {
5340 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5341 ", value %d", __FUNCTION__, trigger.getTagName(),
5342 trigger.entryValue);
5343 return res;
5344 }
5345
5346 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5347 trigger.getTagName(),
5348 trigger.entryValue);
5349 }
5350
5351 mTriggerMap.clear();
5352
5353 return count;
5354}
5355
5356status_t Camera3Device::RequestThread::removeTriggers(
5357 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005358 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005359 Mutex::Autolock al(mTriggerMutex);
5360
Emilian Peevaebbe412018-01-15 13:53:24 +00005361 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005362
5363 /**
5364 * Replace all old entries with their old values.
5365 */
5366 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5367 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5368
5369 status_t res;
5370
5371 uint32_t tag = trigger.metadataTag;
5372 switch (trigger.getTagType()) {
5373 case TYPE_BYTE: {
5374 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5375 res = metadata.update(tag,
5376 &entryValue,
5377 /*count*/1);
5378 break;
5379 }
5380 case TYPE_INT32:
5381 res = metadata.update(tag,
5382 &trigger.entryValue,
5383 /*count*/1);
5384 break;
5385 default:
5386 ALOGE("%s: Type not supported: 0x%x",
5387 __FUNCTION__,
5388 trigger.getTagType());
5389 return INVALID_OPERATION;
5390 }
5391
5392 if (res != OK) {
5393 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5394 ", trigger value %d", __FUNCTION__,
5395 trigger.getTagName(), trigger.entryValue);
5396 return res;
5397 }
5398 }
5399 mTriggerReplacedMap.clear();
5400
5401 /**
5402 * Remove all new entries.
5403 */
5404 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5405 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5406 status_t res = metadata.erase(trigger.metadataTag);
5407
5408 if (res != OK) {
5409 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5410 ", trigger value %d", __FUNCTION__,
5411 trigger.getTagName(), trigger.entryValue);
5412 return res;
5413 }
5414 }
5415 mTriggerRemovedMap.clear();
5416
5417 return OK;
5418}
5419
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005420status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005421 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005422 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005423 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005424 status_t res;
5425
Emilian Peevaebbe412018-01-15 13:53:24 +00005426 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005427
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005428 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005429 // exists
5430 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5431 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5432 if (afTrigger.count > 0 &&
5433 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5434 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005435 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005436 if (res != OK) return res;
5437 }
5438
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005439 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005440 // if none already exists
5441 camera_metadata_entry pcTrigger =
5442 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5443 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5444 if (pcTrigger.count > 0 &&
5445 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5446 pcId.count == 0) {
5447 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005448 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005449 if (res != OK) return res;
5450 }
5451
5452 return OK;
5453}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005454
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005455bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5456 const sp<CaptureRequest> &request) {
5457 ATRACE_CALL();
5458
5459 if (request->mRotateAndCropAuto) {
5460 Mutex::Autolock l(mTriggerMutex);
5461 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5462
5463 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5464 if (rotateAndCropEntry.count > 0) {
5465 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5466 return false;
5467 } else {
5468 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5469 return true;
5470 }
5471 } else {
5472 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5473 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5474 &rotateAndCrop_u8, 1);
5475 return true;
5476 }
5477 }
5478 return false;
5479}
5480
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005481/**
5482 * PreparerThread inner class methods
5483 */
5484
5485Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005486 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005487 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005488}
5489
5490Camera3Device::PreparerThread::~PreparerThread() {
5491 Thread::requestExitAndWait();
5492 if (mCurrentStream != nullptr) {
5493 mCurrentStream->cancelPrepare();
5494 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5495 mCurrentStream.clear();
5496 }
5497 clear();
5498}
5499
Ruben Brunkc78ac262015-08-13 17:58:46 -07005500status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005501 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005502 status_t res;
5503
5504 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005505 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005506
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005507 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005508 if (res == OK) {
5509 // No preparation needed, fire listener right off
5510 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005511 if (listener != NULL) {
5512 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005513 }
5514 return OK;
5515 } else if (res != NOT_ENOUGH_DATA) {
5516 return res;
5517 }
5518
5519 // Need to prepare, start up thread if necessary
5520 if (!mActive) {
5521 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5522 // isn't running
5523 Thread::requestExitAndWait();
5524 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5525 if (res != OK) {
5526 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005527 if (listener != NULL) {
5528 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005529 }
5530 return res;
5531 }
5532 mCancelNow = false;
5533 mActive = true;
5534 ALOGV("%s: Preparer stream started", __FUNCTION__);
5535 }
5536
5537 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005538 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005539 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5540
5541 return OK;
5542}
5543
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005544void Camera3Device::PreparerThread::pause() {
5545 ATRACE_CALL();
5546
5547 Mutex::Autolock l(mLock);
5548
5549 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5550 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5551 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5552 int currentMaxCount = mCurrentMaxCount;
5553 mPendingStreams.clear();
5554 mCancelNow = true;
5555 while (mActive) {
5556 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5557 if (res == TIMED_OUT) {
5558 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5559 return;
5560 } else if (res != OK) {
5561 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5562 return;
5563 }
5564 }
5565
5566 //Check whether the prepare thread was able to complete the current
5567 //stream. In case work is still pending emplace it along with the rest
5568 //of the streams in the pending list.
5569 if (currentStream != nullptr) {
5570 if (!mCurrentPrepareComplete) {
5571 pendingStreams.emplace(currentMaxCount, currentStream);
5572 }
5573 }
5574
5575 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5576 for (const auto& it : mPendingStreams) {
5577 it.second->cancelPrepare();
5578 }
5579}
5580
5581status_t Camera3Device::PreparerThread::resume() {
5582 ATRACE_CALL();
5583 status_t res;
5584
5585 Mutex::Autolock l(mLock);
5586 sp<NotificationListener> listener = mListener.promote();
5587
5588 if (mActive) {
5589 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5590 return NO_INIT;
5591 }
5592
5593 auto it = mPendingStreams.begin();
5594 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005595 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005596 if (res == OK) {
5597 if (listener != NULL) {
5598 listener->notifyPrepared(it->second->getId());
5599 }
5600 it = mPendingStreams.erase(it);
5601 } else if (res != NOT_ENOUGH_DATA) {
5602 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5603 res, strerror(-res));
5604 it = mPendingStreams.erase(it);
5605 } else {
5606 it++;
5607 }
5608 }
5609
5610 if (mPendingStreams.empty()) {
5611 return OK;
5612 }
5613
5614 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5615 if (res != OK) {
5616 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5617 __FUNCTION__, res, strerror(-res));
5618 return res;
5619 }
5620 mCancelNow = false;
5621 mActive = true;
5622 ALOGV("%s: Preparer stream started", __FUNCTION__);
5623
5624 return OK;
5625}
5626
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005627status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005628 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005629 Mutex::Autolock l(mLock);
5630
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005631 for (const auto& it : mPendingStreams) {
5632 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005633 }
5634 mPendingStreams.clear();
5635 mCancelNow = true;
5636
5637 return OK;
5638}
5639
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005640void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005641 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005642 Mutex::Autolock l(mLock);
5643 mListener = listener;
5644}
5645
5646bool Camera3Device::PreparerThread::threadLoop() {
5647 status_t res;
5648 {
5649 Mutex::Autolock l(mLock);
5650 if (mCurrentStream == nullptr) {
5651 // End thread if done with work
5652 if (mPendingStreams.empty()) {
5653 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5654 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5655 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5656 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005657 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005658 return false;
5659 }
5660
5661 // Get next stream to prepare
5662 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005663 mCurrentStream = it->second;
5664 mCurrentMaxCount = it->first;
5665 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005666 mPendingStreams.erase(it);
5667 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5668 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5669 } else if (mCancelNow) {
5670 mCurrentStream->cancelPrepare();
5671 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5672 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5673 mCurrentStream.clear();
5674 mCancelNow = false;
5675 return true;
5676 }
5677 }
5678
5679 res = mCurrentStream->prepareNextBuffer();
5680 if (res == NOT_ENOUGH_DATA) return true;
5681 if (res != OK) {
5682 // Something bad happened; try to recover by cancelling prepare and
5683 // signalling listener anyway
5684 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5685 mCurrentStream->getId(), res, strerror(-res));
5686 mCurrentStream->cancelPrepare();
5687 }
5688
5689 // This stream has finished, notify listener
5690 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005691 sp<NotificationListener> listener = mListener.promote();
5692 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005693 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5694 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005695 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005696 }
5697
5698 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5699 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005700 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005701
5702 return true;
5703}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005704
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005705status_t Camera3Device::RequestBufferStateMachine::initialize(
5706 sp<camera3::StatusTracker> statusTracker) {
5707 if (statusTracker == nullptr) {
5708 ALOGE("%s: statusTracker is null", __FUNCTION__);
5709 return BAD_VALUE;
5710 }
5711
5712 std::lock_guard<std::mutex> lock(mLock);
5713 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005714 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005715 return OK;
5716}
5717
5718bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5719 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005720 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005721 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005722 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005723 return true;
5724 }
5725 return false;
5726}
5727
5728void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5729 std::lock_guard<std::mutex> lock(mLock);
5730 if (!mRequestBufferOngoing) {
5731 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5732 return;
5733 }
5734 mRequestBufferOngoing = false;
5735 if (mStatus == RB_STATUS_PENDING_STOP) {
5736 checkSwitchToStopLocked();
5737 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005738 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005739}
5740
5741void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5742 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005743 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005744 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005745 return;
5746}
5747
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005748void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005749 std::lock_guard<std::mutex> lock(mLock);
5750 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005751 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5752 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005753 mInflightMapEmpty = false;
5754 if (mStatus == RB_STATUS_STOPPED) {
5755 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005756 }
5757 return;
5758}
5759
5760void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5761 std::lock_guard<std::mutex> lock(mLock);
5762 mRequestThreadPaused = true;
5763 if (mStatus == RB_STATUS_PENDING_STOP) {
5764 checkSwitchToStopLocked();
5765 }
5766 return;
5767}
5768
5769void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5770 std::lock_guard<std::mutex> lock(mLock);
5771 mInflightMapEmpty = true;
5772 if (mStatus == RB_STATUS_PENDING_STOP) {
5773 checkSwitchToStopLocked();
5774 }
5775 return;
5776}
5777
5778void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5779 std::lock_guard<std::mutex> lock(mLock);
5780 if (!checkSwitchToStopLocked()) {
5781 mStatus = RB_STATUS_PENDING_STOP;
5782 }
5783 return;
5784}
5785
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005786bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5787 std::lock_guard<std::mutex> lock(mLock);
5788 if (mRequestBufferOngoing) {
5789 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5790 __FUNCTION__);
5791 return false;
5792 }
5793 mSwitchedToOffline = true;
5794 mInflightMapEmpty = true;
5795 mRequestThreadPaused = true;
5796 mStatus = RB_STATUS_STOPPED;
5797 return true;
5798}
5799
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005800void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5801 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5802 if (statusTracker != nullptr) {
5803 if (active) {
5804 statusTracker->markComponentActive(mRequestBufferStatusId);
5805 } else {
5806 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5807 }
5808 }
5809}
5810
5811bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5812 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5813 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005814 return true;
5815 }
5816 return false;
5817}
5818
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005819bool Camera3Device::startRequestBuffer() {
5820 return mRequestBufferSM.startRequestBuffer();
5821}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005822
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005823void Camera3Device::endRequestBuffer() {
5824 mRequestBufferSM.endRequestBuffer();
5825}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005826
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005827nsecs_t Camera3Device::getWaitDuration() {
5828 return kBaseGetBufferWait + getExpectedInFlightDuration();
5829}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005830
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005831void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5832 mInterface->getInflightBufferKeys(out);
5833}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005834
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005835void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5836 mInterface->getInflightRequestBufferKeys(out);
5837}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005838
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005839std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5840 std::vector<sp<Camera3StreamInterface>> ret;
5841 bool hasInputStream = mInputStream != nullptr;
5842 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5843 if (hasInputStream) {
5844 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005845 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005846 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5847 ret.push_back(mOutputStreams[i]);
5848 }
5849 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5850 ret.push_back(mDeletedStreams[i]);
5851 }
5852 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005853}
5854
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005855status_t Camera3Device::switchToOffline(
5856 const std::vector<int32_t>& streamsToKeep,
5857 /*out*/ sp<CameraOfflineSessionBase>* session) {
5858 ATRACE_CALL();
5859 if (session == nullptr) {
5860 ALOGE("%s: session must not be null", __FUNCTION__);
5861 return BAD_VALUE;
5862 }
5863
5864 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005865
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005866 bool hasInputStream = mInputStream != nullptr;
5867 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5868 bool inputStreamSupportsOffline = hasInputStream ?
5869 mInputStream->getOfflineProcessingSupport() : false;
5870 auto outputStreamIds = mOutputStreams.getStreamIds();
5871 auto streamIds = outputStreamIds;
5872 if (hasInputStream) {
5873 streamIds.push_back(mInputStream->getId());
5874 }
5875
5876 // Check all streams in streamsToKeep supports offline mode
5877 for (auto id : streamsToKeep) {
5878 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5879 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5880 return BAD_VALUE;
5881 } else if (id == inputStreamId) {
5882 if (!inputStreamSupportsOffline) {
5883 ALOGE("%s: input stream %d cannot be switched to offline",
5884 __FUNCTION__, id);
5885 return BAD_VALUE;
5886 }
5887 } else {
5888 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5889 if (!stream->getOfflineProcessingSupport()) {
5890 ALOGE("%s: output stream %d cannot be switched to offline",
5891 __FUNCTION__, id);
5892 return BAD_VALUE;
5893 }
5894 }
5895 }
5896
5897 // TODO: block surface sharing and surface group streams until we can support them
5898
5899 // Stop repeating request, wait until all remaining requests are submitted, then call into
5900 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005901 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5902 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005903 camera3::BufferRecords bufferRecords;
5904 status_t ret = mRequestThread->switchToOffline(
5905 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005906
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005907 if (ret != OK) {
5908 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5909 return ret;
5910 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005911
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005912 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5913 if (!succ) {
5914 SET_ERR("HAL must not be calling requestStreamBuffers call");
5915 // TODO: block ALL callbacks from HAL till app configured new streams?
5916 return UNKNOWN_ERROR;
5917 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005918
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005919 // Verify offlineSessionInfo
5920 std::vector<int32_t> offlineStreamIds;
5921 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5922 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5923 // verify stream IDs
5924 int32_t id = offlineStream.id;
5925 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5926 SET_ERR("stream ID %d not found!", id);
5927 return UNKNOWN_ERROR;
5928 }
5929
5930 // When not using HAL buf manager, only allow streams requested by app to be preserved
5931 if (!mUseHalBufManager) {
5932 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5933 SET_ERR("stream ID %d must not be switched to offline!", id);
5934 return UNKNOWN_ERROR;
5935 }
5936 }
5937
5938 offlineStreamIds.push_back(id);
5939 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5940 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5941 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5942 // Verify number of outstanding buffers
5943 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5944 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5945 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5946 return UNKNOWN_ERROR;
5947 }
5948 }
5949
5950 // Verify all streams to be deleted don't have any outstanding buffers
5951 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5952 inputStreamId) == offlineStreamIds.end()) {
5953 if (mInputStream->hasOutstandingBuffers()) {
5954 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5955 inputStreamId, mInputStream->getOutstandingBuffersCount());
5956 return UNKNOWN_ERROR;
5957 }
5958 }
5959
5960 for (const auto& outStreamId : outputStreamIds) {
5961 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5962 outStreamId) == offlineStreamIds.end()) {
5963 auto outStream = mOutputStreams.get(outStreamId);
5964 if (outStream->hasOutstandingBuffers()) {
5965 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5966 outStreamId, outStream->getOutstandingBuffersCount());
5967 return UNKNOWN_ERROR;
5968 }
5969 }
5970 }
5971
5972 InFlightRequestMap offlineReqs;
5973 // Verify inflight requests and their pending buffers
5974 {
5975 std::lock_guard<std::mutex> l(mInFlightLock);
5976 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5977 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5978 if (idx == NAME_NOT_FOUND) {
5979 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5980 return UNKNOWN_ERROR;
5981 }
5982
5983 const auto& inflightReq = mInFlightMap.valueAt(idx);
5984 // TODO: check specific stream IDs
5985 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5986 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5987 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5988 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5989 return UNKNOWN_ERROR;
5990 }
5991 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5992 }
5993 }
5994
5995 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005996 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005997 camera3::StreamSet offlineStreamSet;
5998 sp<camera3::Camera3Stream> inputStream;
5999 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6000 int32_t id = offlineStream.id;
6001 if (mInputStream != nullptr && id == mInputStream->getId()) {
6002 inputStream = mInputStream;
6003 } else {
6004 offlineStreamSet.add(id, mOutputStreams.get(id));
6005 }
6006 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006007
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006008 // TODO: check if we need to lock before copying states
6009 // though technically no other thread should be talking to Camera3Device at this point
6010 Camera3OfflineStates offlineStates(
6011 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006012 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6013 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6014 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6015 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6016 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6017 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6018 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006019
6020 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6021 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6022
6023 // Delete all streams that has been transferred to offline session
6024 Mutex::Autolock l(mLock);
6025 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6026 int32_t id = offlineStream.id;
6027 if (mInputStream != nullptr && id == mInputStream->getId()) {
6028 mInputStream.clear();
6029 } else {
6030 mOutputStreams.remove(id);
6031 }
6032 }
6033
6034 // disconnect all other streams and switch to UNCONFIGURED state
6035 if (mInputStream != nullptr) {
6036 ret = mInputStream->disconnect();
6037 if (ret != OK) {
6038 SET_ERR_L("disconnect input stream failed!");
6039 return UNKNOWN_ERROR;
6040 }
6041 }
6042
6043 for (auto streamId : mOutputStreams.getStreamIds()) {
6044 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6045 ret = stream->disconnect();
6046 if (ret != OK) {
6047 SET_ERR_L("disconnect output stream %d failed!", streamId);
6048 return UNKNOWN_ERROR;
6049 }
6050 }
6051
6052 mInputStream.clear();
6053 mOutputStreams.clear();
6054 mNeedConfig = true;
6055 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6056 mOperatingMode = NO_MODE;
6057 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006058 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006059
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006060 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006061 // TO be done by CameraDeviceClient/Camera3OfflineSession
6062 // register the offline client to camera service
6063 // Setup result passthing threads etc
6064 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6065 // TODO: check how many onIdle callback will be sent
6066 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006067}
6068
Emilian Peevcc0b7952020-01-07 13:54:47 -08006069void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6070 ATRACE_CALL();
6071
6072 if (offlineStreamIds == nullptr) {
6073 return;
6074 }
6075
6076 Mutex::Autolock il(mInterfaceLock);
6077
6078 auto streamIds = mOutputStreams.getStreamIds();
6079 bool hasInputStream = mInputStream != nullptr;
6080 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6081 offlineStreamIds->push_back(mInputStream->getId());
6082 }
6083
6084 for (const auto & streamId : streamIds) {
6085 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6086 // Streams that use the camera buffer manager are currently not supported in
6087 // offline mode
6088 if (stream->getOfflineProcessingSupport() &&
6089 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6090 offlineStreamIds->push_back(streamId);
6091 }
6092 }
6093}
6094
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006095status_t Camera3Device::setRotateAndCropAutoBehavior(
6096 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6097 ATRACE_CALL();
6098 Mutex::Autolock il(mInterfaceLock);
6099 Mutex::Autolock l(mLock);
6100 if (mRequestThread == nullptr) {
6101 return INVALID_OPERATION;
6102 }
6103 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6104}
6105
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006106}; // namespace android