blob: 95a9ad0ee1ed96e133a80c4adbd70de8b1248de9 [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
Emilian Peevf4816702020-04-03 15:44:51 -0700550StreamRotation Camera3Device::mapToStreamRotation(camera_stream_rotation_t rotation) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551 switch (rotation) {
Emilian Peevf4816702020-04-03 15:44:51 -0700552 case CAMERA_STREAM_ROTATION_0:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800553 return StreamRotation::ROTATION_0;
Emilian Peevf4816702020-04-03 15:44:51 -0700554 case CAMERA_STREAM_ROTATION_90:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 return StreamRotation::ROTATION_90;
Emilian Peevf4816702020-04-03 15:44:51 -0700556 case CAMERA_STREAM_ROTATION_180:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 return StreamRotation::ROTATION_180;
Emilian Peevf4816702020-04-03 15:44:51 -0700558 case CAMERA_STREAM_ROTATION_270:
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800559 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(
Emilian Peevf4816702020-04-03 15:44:51 -0700566 camera_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800567 if (mode == nullptr) return BAD_VALUE;
Emilian Peevf4816702020-04-03 15:44:51 -0700568 if (operationMode < CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START) {
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800569 switch(operationMode) {
Emilian Peevf4816702020-04-03 15:44:51 -0700570 case CAMERA_STREAM_CONFIGURATION_NORMAL_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800571 *mode = StreamConfigurationMode::NORMAL_MODE;
572 break;
Emilian Peevf4816702020-04-03 15:44:51 -0700573 case CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800574 *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) {
Emilian Peevf4816702020-04-03 15:44:51 -0700782 const char *templateNames[CAMERA_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
Emilian Peevf4816702020-04-03 15:44:51 -0700791 for (int i = 1; i < CAMERA_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800792 camera_metadata_t *templateRequest = nullptr;
793 mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -0700794 (camera_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();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800916 outputStream->setBatchSize(requestList->size());
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700917 break;
918 }
919 }
920 }
921
Jianing Wei90e59c92014-03-12 18:29:36 -0700922 return OK;
923}
924
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800925status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800927
Emilian Peevaebbe412018-01-15 13:53:24 +0000928 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700929 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000930 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700931
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800932 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933}
934
Emilian Peevaebbe412018-01-15 13:53:24 +0000935void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700936 std::list<const SurfaceMap>& surfaceMaps,
937 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000938 PhysicalCameraSettingsList requestList;
939 requestList.push_back({std::string(getId().string()), request});
940 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700941
942 SurfaceMap surfaceMap;
943 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
944 // With no surface list passed in, stream and surface will have 1-to-1
945 // mapping. So the surface index is 0 for each stream in the surfaceMap.
946 for (size_t i = 0; i < streams.count; i++) {
947 surfaceMap[streams.data.i32[i]].push_back(0);
948 }
949 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800950}
951
Jianing Wei90e59c92014-03-12 18:29:36 -0700952status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000953 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700954 const std::list<const SurfaceMap> &surfaceMaps,
955 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700956 /*out*/
957 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700958 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700959 nsecs_t requestTimeNs = systemTime();
960
Jianing Wei90e59c92014-03-12 18:29:36 -0700961 Mutex::Autolock il(mInterfaceLock);
962 Mutex::Autolock l(mLock);
963
964 status_t res = checkStatusOkToCaptureLocked();
965 if (res != OK) {
966 // error logged by previous call
967 return res;
968 }
969
970 RequestList requestList;
971
Shuzhen Wang0129d522016-10-30 22:43:41 -0700972 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700973 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700974 if (res != OK) {
975 // error logged by previous call
976 return res;
977 }
978
979 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700980 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700981 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700982 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700983 }
984
985 if (res == OK) {
986 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
987 if (res != OK) {
988 SET_ERR_L("Can't transition to active in %f seconds!",
989 kActiveTimeout/1e9);
990 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800991 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700992 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 } else {
994 CLOGE("Cannot queue request. Impossible.");
995 return BAD_VALUE;
996 }
997
998 return res;
999}
1000
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001001hardware::Return<void> Camera3Device::requestStreamBuffers(
1002 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1003 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001004 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001005 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001006 *this, *mInterface, *this};
1007 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001008 return hardware::Void();
1009}
1010
1011hardware::Return<void> Camera3Device::returnStreamBuffers(
1012 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001013 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001014 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001015 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001016 return hardware::Void();
1017}
1018
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001019hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001020 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001021 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001022 // Ideally we should grab mLock, but that can lead to deadlock, and
1023 // it's not super important to get up to date value of mStatus for this
1024 // warning print, hence skipping the lock here
1025 if (mStatus == STATUS_ERROR) {
1026 // Per API contract, HAL should act as closed after device error
1027 // But mStatus can be set to error by framework as well, so just log
1028 // a warning here.
1029 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001030 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001031
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001032 sp<NotificationListener> listener;
1033 {
1034 std::lock_guard<std::mutex> l(mOutputLock);
1035 listener = mListener.promote();
1036 }
1037
Yifan Honga640c5a2017-04-12 16:30:31 -07001038 if (mProcessCaptureResultLock.tryLock() != OK) {
1039 // This should never happen; it indicates a wrong client implementation
1040 // that doesn't follow the contract. But, we can be tolerant here.
1041 ALOGE("%s: callback overlapped! waiting 1s...",
1042 __FUNCTION__);
1043 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1044 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1045 __FUNCTION__);
1046 // really don't know what to do, so bail out.
1047 return hardware::Void();
1048 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001050 CaptureOutputStates states {
1051 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001052 mInFlightLock, mLastCompletedRegularFrameNumber,
1053 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1054 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001055 mNextShutterFrameNumber,
1056 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1057 mNextResultFrameNumber,
1058 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1059 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1060 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001061 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001062 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1063 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001064 };
1065
Yifan Honga640c5a2017-04-12 16:30:31 -07001066 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001067 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001068 }
1069 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001070 return hardware::Void();
1071}
1072
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001073// Only one processCaptureResult should be called at a time, so
1074// the locks won't block. The locks are present here simply to enforce this.
1075hardware::Return<void> Camera3Device::processCaptureResult(
1076 const hardware::hidl_vec<
1077 hardware::camera::device::V3_2::CaptureResult>& results) {
1078 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1079
1080 // Ideally we should grab mLock, but that can lead to deadlock, and
1081 // it's not super important to get up to date value of mStatus for this
1082 // warning print, hence skipping the lock here
1083 if (mStatus == STATUS_ERROR) {
1084 // Per API contract, HAL should act as closed after device error
1085 // But mStatus can be set to error by framework as well, so just log
1086 // a warning here.
1087 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1088 }
1089
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001090 sp<NotificationListener> listener;
1091 {
1092 std::lock_guard<std::mutex> l(mOutputLock);
1093 listener = mListener.promote();
1094 }
1095
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001096 if (mProcessCaptureResultLock.tryLock() != OK) {
1097 // This should never happen; it indicates a wrong client implementation
1098 // that doesn't follow the contract. But, we can be tolerant here.
1099 ALOGE("%s: callback overlapped! waiting 1s...",
1100 __FUNCTION__);
1101 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1102 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1103 __FUNCTION__);
1104 // really don't know what to do, so bail out.
1105 return hardware::Void();
1106 }
1107 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001108
1109 CaptureOutputStates states {
1110 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001111 mInFlightLock, mLastCompletedRegularFrameNumber,
1112 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1113 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001114 mNextShutterFrameNumber,
1115 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1116 mNextResultFrameNumber,
1117 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1118 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1119 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001120 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001121 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1122 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001123 };
1124
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001125 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001126 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001127 }
1128 mProcessCaptureResultLock.unlock();
1129 return hardware::Void();
1130}
1131
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001132hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001133 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001134 // Ideally we should grab mLock, but that can lead to deadlock, and
1135 // it's not super important to get up to date value of mStatus for this
1136 // warning print, hence skipping the lock here
1137 if (mStatus == STATUS_ERROR) {
1138 // Per API contract, HAL should act as closed after device error
1139 // But mStatus can be set to error by framework as well, so just log
1140 // a warning here.
1141 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001142 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001143
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001144 sp<NotificationListener> listener;
1145 {
1146 std::lock_guard<std::mutex> l(mOutputLock);
1147 listener = mListener.promote();
1148 }
1149
1150 CaptureOutputStates states {
1151 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001152 mInFlightLock, mLastCompletedRegularFrameNumber,
1153 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1154 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 mNextShutterFrameNumber,
1156 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1157 mNextResultFrameNumber,
1158 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1159 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1160 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001161 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001162 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1163 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001164 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001165 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001166 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001167 }
1168 return hardware::Void();
1169}
1170
Emilian Peevaebbe412018-01-15 13:53:24 +00001171status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001173 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001174 ATRACE_CALL();
1175
Emilian Peevaebbe412018-01-15 13:53:24 +00001176 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001177}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001178
Jianing Weicb0652e2014-03-12 18:29:36 -07001179status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1180 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001182
Emilian Peevaebbe412018-01-15 13:53:24 +00001183 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001184 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001185 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001186
Emilian Peevaebbe412018-01-15 13:53:24 +00001187 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001188 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189}
1190
Emilian Peevaebbe412018-01-15 13:53:24 +00001191status_t Camera3Device::setStreamingRequestList(
1192 const List<const PhysicalCameraSettingsList> &requestsList,
1193 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001194 ATRACE_CALL();
1195
Emilian Peevaebbe412018-01-15 13:53:24 +00001196 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001197}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001198
1199sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001200 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 status_t res;
1202
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001203 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001204 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1205 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001206 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001207 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001208 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001210 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001212 } else if (mStatus == STATUS_UNCONFIGURED) {
1213 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001214 CLOGE("No streams configured");
1215 return NULL;
1216 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 }
1218
Shuzhen Wang0129d522016-10-30 22:43:41 -07001219 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001221}
1222
Jianing Weicb0652e2014-03-12 18:29:36 -07001223status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001224 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001225 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001227
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 switch (mStatus) {
1229 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001230 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001231 return INVALID_OPERATION;
1232 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001235 case STATUS_UNCONFIGURED:
1236 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 case STATUS_ACTIVE:
1238 // OK
1239 break;
1240 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001241 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001242 return INVALID_OPERATION;
1243 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001244 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001245
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001246 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247}
1248
1249status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1250 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001253 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001254}
1255
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001256status_t Camera3Device::createInputStream(
1257 uint32_t width, uint32_t height, int format, int *id) {
1258 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001260 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001261 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001262 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1263 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001264
1265 status_t res;
1266 bool wasActive = false;
1267
1268 switch (mStatus) {
1269 case STATUS_ERROR:
1270 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1271 return INVALID_OPERATION;
1272 case STATUS_UNINITIALIZED:
1273 ALOGE("%s: Device not initialized", __FUNCTION__);
1274 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 case STATUS_UNCONFIGURED:
1276 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001277 // OK
1278 break;
1279 case STATUS_ACTIVE:
1280 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001281 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001282 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284 return res;
1285 }
1286 wasActive = true;
1287 break;
1288 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290 return INVALID_OPERATION;
1291 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293
1294 if (mInputStream != 0) {
1295 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1296 return INVALID_OPERATION;
1297 }
1298
1299 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1300 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001301 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001302
1303 mInputStream = newStream;
1304
1305 *id = mNextStreamId++;
1306
1307 // Continue captures if active at start
1308 if (wasActive) {
1309 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001310 // Reuse current operating mode and session parameters for new stream config
1311 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 if (res != OK) {
1313 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1314 __FUNCTION__, mNextStreamId, strerror(-res), res);
1315 return res;
1316 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001318 }
1319
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001320 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321 return OK;
1322}
1323
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001324status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001325 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001326 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001327 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001328 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001329 ATRACE_CALL();
1330
1331 if (consumer == nullptr) {
1332 ALOGE("%s: consumer must not be null", __FUNCTION__);
1333 return BAD_VALUE;
1334 }
1335
1336 std::vector<sp<Surface>> consumers;
1337 consumers.push_back(consumer);
1338
1339 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001340 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1341 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001342}
1343
1344status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1345 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001346 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001347 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001348 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001349 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001351 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001352 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001354 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001355 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1356 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1357 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001358
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 status_t res;
1360 bool wasActive = false;
1361
1362 switch (mStatus) {
1363 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001364 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001365 return INVALID_OPERATION;
1366 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001367 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001369 case STATUS_UNCONFIGURED:
1370 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001371 // OK
1372 break;
1373 case STATUS_ACTIVE:
1374 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001375 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001377 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378 return res;
1379 }
1380 wasActive = true;
1381 break;
1382 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001383 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001384 return INVALID_OPERATION;
1385 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001386 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387
1388 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001389
Shuzhen Wang0129d522016-10-30 22:43:41 -07001390 if (consumers.size() == 0 && !hasDeferredConsumer) {
1391 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1392 return BAD_VALUE;
1393 }
Zhijun He5d677d12016-05-29 16:52:39 -07001394
Shuzhen Wang0129d522016-10-30 22:43:41 -07001395 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001396 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1397 return BAD_VALUE;
1398 }
1399
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001401 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001402 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001403 blobBufferSize = getPointCloudBufferSize();
1404 if (blobBufferSize <= 0) {
1405 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1406 return BAD_VALUE;
1407 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001408 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1409 blobBufferSize = width * height;
1410 } else {
1411 blobBufferSize = getJpegBufferSize(width, height);
1412 if (blobBufferSize <= 0) {
1413 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1414 return BAD_VALUE;
1415 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001416 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001417 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001418 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001419 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001420 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1421 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1422 if (rawOpaqueBufferSize <= 0) {
1423 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1424 return BAD_VALUE;
1425 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001426 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001427 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001428 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001429 } else if (isShared) {
1430 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1431 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001432 mTimestampOffset, physicalCameraId, streamSetId,
1433 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001434 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001435 newStream = new Camera3OutputStream(mNextStreamId,
1436 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001437 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001438 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001439 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001440 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001441 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001442 }
Emilian Peev40ead602017-09-26 15:46:36 +01001443
1444 size_t consumerCount = consumers.size();
1445 for (size_t i = 0; i < consumerCount; i++) {
1446 int id = newStream->getSurfaceId(consumers[i]);
1447 if (id < 0) {
1448 SET_ERR_L("Invalid surface id");
1449 return BAD_VALUE;
1450 }
1451 if (surfaceIds != nullptr) {
1452 surfaceIds->push_back(id);
1453 }
1454 }
1455
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001456 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001457
Emilian Peev08dd2452017-04-06 16:55:14 +01001458 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001459
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001460 newStream->setImageDumpMask(mImageDumpMask);
1461
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 res = mOutputStreams.add(mNextStreamId, newStream);
1463 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001464 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 return res;
1466 }
1467
Shuzhen Wang316781a2020-08-18 18:11:01 -07001468 mSessionStatsBuilder.addStream(mNextStreamId);
1469
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001471 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472
1473 // Continue captures if active at start
1474 if (wasActive) {
1475 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001476 // Reuse current operating mode and session parameters for new stream config
1477 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001479 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1480 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 return res;
1482 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001483 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001485 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001486 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001487}
1488
Emilian Peev710c1422017-08-30 11:19:38 +01001489status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001490 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001491 if (nullptr == streamInfo) {
1492 return BAD_VALUE;
1493 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001494 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001496
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 switch (mStatus) {
1498 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001499 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 return INVALID_OPERATION;
1501 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001502 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 case STATUS_UNCONFIGURED:
1505 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 case STATUS_ACTIVE:
1507 // OK
1508 break;
1509 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001510 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 return INVALID_OPERATION;
1512 }
1513
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001514 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1515 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001516 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001517 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 }
1519
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001520 streamInfo->width = stream->getWidth();
1521 streamInfo->height = stream->getHeight();
1522 streamInfo->format = stream->getFormat();
1523 streamInfo->dataSpace = stream->getDataSpace();
1524 streamInfo->formatOverridden = stream->isFormatOverridden();
1525 streamInfo->originalFormat = stream->getOriginalFormat();
1526 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1527 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001529}
1530
1531status_t Camera3Device::setStreamTransform(int id,
1532 int transform) {
1533 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001534 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001536
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 switch (mStatus) {
1538 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001539 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001540 return INVALID_OPERATION;
1541 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001542 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001543 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 case STATUS_UNCONFIGURED:
1545 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001546 case STATUS_ACTIVE:
1547 // OK
1548 break;
1549 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001550 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 return INVALID_OPERATION;
1552 }
1553
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001554 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1555 if (stream == nullptr) {
1556 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return BAD_VALUE;
1558 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001559 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001560}
1561
1562status_t Camera3Device::deleteStream(int id) {
1563 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001565 Mutex::Autolock l(mLock);
1566 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001567
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001568 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001569
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 // CameraDevice semantics require device to already be idle before
1571 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001573 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001574 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 }
1576
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001577 if (mStatus == STATUS_ERROR) {
1578 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1579 __FUNCTION__, mId.string());
1580 return -EBUSY;
1581 }
1582
Igor Murashkin2fba5842013-04-22 14:03:54 -07001583 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001584 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001585 if (mInputStream != NULL && id == mInputStream->getId()) {
1586 deletedStream = mInputStream;
1587 mInputStream.clear();
1588 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001589 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001590 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 return BAD_VALUE;
1592 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001593 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001594 }
1595
1596 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001597 if (stream != nullptr) {
1598 deletedStream = stream;
1599 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 }
1601
1602 // Free up the stream endpoint so that it can be used by some other stream
1603 res = deletedStream->disconnect();
1604 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001605 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 // fall through since we want to still list the stream as deleted.
1607 }
1608 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001609 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610
1611 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001612}
1613
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001614status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001615 ATRACE_CALL();
1616 ALOGV("%s: E", __FUNCTION__);
1617
1618 Mutex::Autolock il(mInterfaceLock);
1619 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001620
Emilian Peev811d2952018-05-25 11:08:40 +01001621 // In case the client doesn't include any session parameter, try a
1622 // speculative configuration using the values from the last cached
1623 // default request.
1624 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001625 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001626 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1627 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1628 mLastTemplateId);
1629 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1630 operatingMode);
1631 }
1632
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001633 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1634}
1635
1636status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1637 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001638 //Filter out any incoming session parameters
1639 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001640 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1641 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001642 CameraMetadata filteredParams(availableSessionKeys.count);
1643 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1644 filteredParams.getAndLock());
1645 set_camera_metadata_vendor_id(meta, mVendorTagId);
1646 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001647 if (availableSessionKeys.count > 0) {
1648 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1649 camera_metadata_ro_entry entry = params.find(
1650 availableSessionKeys.data.i32[i]);
1651 if (entry.count > 0) {
1652 filteredParams.update(entry);
1653 }
1654 }
1655 }
1656
1657 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001658}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001659
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001660status_t Camera3Device::getInputBufferProducer(
1661 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001662 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001663 Mutex::Autolock il(mInterfaceLock);
1664 Mutex::Autolock l(mLock);
1665
1666 if (producer == NULL) {
1667 return BAD_VALUE;
1668 } else if (mInputStream == NULL) {
1669 return INVALID_OPERATION;
1670 }
1671
1672 return mInputStream->getInputBufferProducer(producer);
1673}
1674
Emilian Peevf4816702020-04-03 15:44:51 -07001675status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676 CameraMetadata *request) {
1677 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001678 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001679
Emilian Peevf4816702020-04-03 15:44:51 -07001680 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001681 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001682 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001683 return BAD_VALUE;
1684 }
1685
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001687
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001688 {
1689 Mutex::Autolock l(mLock);
1690 switch (mStatus) {
1691 case STATUS_ERROR:
1692 CLOGE("Device has encountered a serious error");
1693 return INVALID_OPERATION;
1694 case STATUS_UNINITIALIZED:
1695 CLOGE("Device is not initialized!");
1696 return INVALID_OPERATION;
1697 case STATUS_UNCONFIGURED:
1698 case STATUS_CONFIGURED:
1699 case STATUS_ACTIVE:
1700 // OK
1701 break;
1702 default:
1703 SET_ERR_L("Unexpected status: %d", mStatus);
1704 return INVALID_OPERATION;
1705 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001706
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001707 if (!mRequestTemplateCache[templateId].isEmpty()) {
1708 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001709 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 return OK;
1711 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001712 }
1713
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001714 camera_metadata_t *rawRequest;
1715 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001716 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001717
1718 {
1719 Mutex::Autolock l(mLock);
1720 if (res == BAD_VALUE) {
1721 ALOGI("%s: template %d is not supported on this camera device",
1722 __FUNCTION__, templateId);
1723 return res;
1724 } else if (res != OK) {
1725 CLOGE("Unable to construct request template %d: %s (%d)",
1726 templateId, strerror(-res), res);
1727 return res;
1728 }
1729
1730 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1731 mRequestTemplateCache[templateId].acquire(rawRequest);
1732
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001733 // Override the template request with zoomRatioMapper
1734 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1735 &mRequestTemplateCache[templateId]);
1736 if (res != OK) {
1737 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1738 templateId, strerror(-res), res);
1739 return res;
1740 }
1741
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001742 // Fill in JPEG_QUALITY if not available
1743 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1744 static const uint8_t kDefaultJpegQuality = 95;
1745 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1746 &kDefaultJpegQuality, 1);
1747 }
1748
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001749 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001750 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001751 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752 return OK;
1753}
1754
1755status_t Camera3Device::waitUntilDrained() {
1756 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001758 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001760
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001761 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001762}
1763
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001764status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 switch (mStatus) {
1766 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001767 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001768 ALOGV("%s: Already idle", __FUNCTION__);
1769 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001770 case STATUS_CONFIGURED:
1771 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772 case STATUS_ERROR:
1773 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 break;
1776 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001777 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778 return INVALID_OPERATION;
1779 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001780 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1781 maxExpectedDuration);
1782 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001783 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001784 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001785 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1786 res);
1787 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001788 return res;
1789}
1790
Ruben Brunk183f0562015-08-12 12:55:02 -07001791
1792void Camera3Device::internalUpdateStatusLocked(Status status) {
1793 mStatus = status;
1794 mRecentStatusUpdates.add(mStatus);
1795 mStatusChanged.broadcast();
1796}
1797
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001799status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001800 if (mRequestThread.get() != nullptr) {
1801 mRequestThread->setPaused(true);
1802 } else {
1803 return NO_INIT;
1804 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001805
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001806 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1807 maxExpectedDuration);
1808 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001809 if (res != OK) {
1810 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001811 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001812 }
1813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 return res;
1815}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001817// Resume after internalPauseAndWaitLocked
1818status_t Camera3Device::internalResumeLocked() {
1819 status_t res;
1820
1821 mRequestThread->setPaused(false);
1822
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001823 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1824 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1826 if (res != OK) {
1827 SET_ERR_L("Can't transition to active in %f seconds!",
1828 kActiveTimeout/1e9);
1829 }
1830 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001832}
1833
Ruben Brunk183f0562015-08-12 12:55:02 -07001834status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001836
1837 size_t startIndex = 0;
1838 if (mStatusWaiters == 0) {
1839 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1840 // this status list
1841 mRecentStatusUpdates.clear();
1842 } else {
1843 // If other threads are waiting on updates to this status list, set the position of the
1844 // first element that this list will check rather than clearing the list.
1845 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 }
1847
Ruben Brunk183f0562015-08-12 12:55:02 -07001848 mStatusWaiters++;
1849
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001850 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001851 if (!active && mUseHalBufManager) {
1852 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001853 if (mStatus == STATUS_ACTIVE) {
1854 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001855 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001856 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001857 mRequestBufferSM.onWaitUntilIdle();
1858 }
1859
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860 bool stateSeen = false;
1861 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001862 if (active == (mStatus == STATUS_ACTIVE)) {
1863 // Desired state is current
1864 break;
1865 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001866
1867 res = mStatusChanged.waitRelative(mLock, timeout);
1868 if (res != OK) break;
1869
Ruben Brunk183f0562015-08-12 12:55:02 -07001870 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1871 // transitions.
1872 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1873 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1874 __FUNCTION__);
1875
1876 // Encountered desired state since we began waiting
1877 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1879 stateSeen = true;
1880 break;
1881 }
1882 }
1883 } while (!stateSeen);
1884
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001885 if (signalPipelineDrain) {
1886 mRequestThread->resetPipelineDrain();
1887 }
1888
Ruben Brunk183f0562015-08-12 12:55:02 -07001889 mStatusWaiters--;
1890
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 return res;
1892}
1893
1894
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001895status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001897 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001898
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001899 if (listener != NULL && mListener != NULL) {
1900 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1901 }
1902 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001903 mRequestThread->setNotificationListener(listener);
1904 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001905
1906 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907}
1908
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001909bool Camera3Device::willNotify3A() {
1910 return false;
1911}
1912
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001914 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001915 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001917 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001918 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1919 if (st == std::cv_status::timeout) {
1920 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001921 }
1922 }
1923 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924}
1925
Jianing Weicb0652e2014-03-12 18:29:36 -07001926status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001928 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001929
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001930 if (mResultQueue.empty()) {
1931 return NOT_ENOUGH_DATA;
1932 }
1933
Jianing Weicb0652e2014-03-12 18:29:36 -07001934 if (frame == NULL) {
1935 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1936 return BAD_VALUE;
1937 }
1938
1939 CaptureResult &result = *(mResultQueue.begin());
1940 frame->mResultExtras = result.mResultExtras;
1941 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001942 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001943 mResultQueue.erase(mResultQueue.begin());
1944
1945 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001946}
1947
1948status_t Camera3Device::triggerAutofocus(uint32_t id) {
1949 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001950 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001952 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1953 // Mix-in this trigger into the next request and only the next request.
1954 RequestTrigger trigger[] = {
1955 {
1956 ANDROID_CONTROL_AF_TRIGGER,
1957 ANDROID_CONTROL_AF_TRIGGER_START
1958 },
1959 {
1960 ANDROID_CONTROL_AF_TRIGGER_ID,
1961 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001962 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001963 };
1964
1965 return mRequestThread->queueTrigger(trigger,
1966 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967}
1968
1969status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1970 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001971 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001973 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1974 // Mix-in this trigger into the next request and only the next request.
1975 RequestTrigger trigger[] = {
1976 {
1977 ANDROID_CONTROL_AF_TRIGGER,
1978 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1979 },
1980 {
1981 ANDROID_CONTROL_AF_TRIGGER_ID,
1982 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001983 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001984 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001986 return mRequestThread->queueTrigger(trigger,
1987 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001988}
1989
1990status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1991 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001992 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001993
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001994 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1995 // Mix-in this trigger into the next request and only the next request.
1996 RequestTrigger trigger[] = {
1997 {
1998 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1999 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2000 },
2001 {
2002 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2003 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002004 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002005 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002007 return mRequestThread->queueTrigger(trigger,
2008 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002009}
2010
Jianing Weicb0652e2014-03-12 18:29:36 -07002011status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002012 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002013 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002014 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002015
Zhijun He7ef20392014-04-21 16:04:17 -07002016 {
2017 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002018
2019 // b/116514106 "disconnect()" can get called twice for the same device. The
2020 // camera device will not be initialized during the second run.
2021 if (mStatus == STATUS_UNINITIALIZED) {
2022 return OK;
2023 }
2024
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002025 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002026
2027 // Stop session and stream counter
2028 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002029 }
2030
Emilian Peev08dd2452017-04-06 16:55:14 +01002031 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002032}
2033
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002034status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002035 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2036}
2037
2038status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002039 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002040 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002041 Mutex::Autolock il(mInterfaceLock);
2042 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002043
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002044 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2045 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002046 CLOGE("Stream %d does not exist", streamId);
2047 return BAD_VALUE;
2048 }
2049
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002050 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002051 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002052 return BAD_VALUE;
2053 }
2054
2055 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002056 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002057 return BAD_VALUE;
2058 }
2059
Ruben Brunkc78ac262015-08-13 17:58:46 -07002060 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002061}
2062
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002063status_t Camera3Device::tearDown(int streamId) {
2064 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002065 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002066 Mutex::Autolock il(mInterfaceLock);
2067 Mutex::Autolock l(mLock);
2068
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002069 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2070 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002071 CLOGE("Stream %d does not exist", streamId);
2072 return BAD_VALUE;
2073 }
2074
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002075 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2076 CLOGE("Stream %d is a target of a in-progress request", streamId);
2077 return BAD_VALUE;
2078 }
2079
2080 return stream->tearDown();
2081}
2082
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002083status_t Camera3Device::addBufferListenerForStream(int streamId,
2084 wp<Camera3StreamBufferListener> listener) {
2085 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002086 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002087 Mutex::Autolock il(mInterfaceLock);
2088 Mutex::Autolock l(mLock);
2089
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002090 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2091 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002092 CLOGE("Stream %d does not exist", streamId);
2093 return BAD_VALUE;
2094 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002095 stream->addBufferListener(listener);
2096
2097 return OK;
2098}
2099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002101 * Methods called by subclasses
2102 */
2103
2104void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002105 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002106 std::vector<int> streamIds;
2107 std::vector<hardware::CameraStreamStats> streamStats;
2108
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 {
2110 // Need mLock to safely update state and synchronize to current
2111 // state of methods in flight.
2112 Mutex::Autolock l(mLock);
2113 // We can get various system-idle notices from the status tracker
2114 // while starting up. Only care about them if we've actually sent
2115 // in some requests recently.
2116 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2117 return;
2118 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002119 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2120 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002121 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122
2123 // Skip notifying listener if we're doing some user-transparent
2124 // state changes
2125 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002126
2127 // Populate stream statistics in case of Idle
2128 if (idle) {
2129 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2130 auto stream = mOutputStreams[i];
2131 if (stream.get() == nullptr) continue;
2132 streamIds.push_back(stream->getId());
2133 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2134 int64_t usage = 0LL;
2135 if (camera3Stream != nullptr) {
2136 usage = camera3Stream->getUsage();
2137 }
2138 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2139 stream->getFormat(), stream->getDataSpace(), usage,
2140 stream->getMaxHalBuffers(),
2141 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2142 }
2143 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002145
2146 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002147 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002148 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002149 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002150 }
2151 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002152 // Get session stats from the builder, and notify the listener.
2153 int64_t requestCount, resultErrorCount;
2154 bool deviceError;
2155 std::map<int, StreamStats> streamStatsMap;
2156 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2157 &deviceError, &streamStatsMap);
2158 for (size_t i = 0; i < streamIds.size(); i++) {
2159 int streamId = streamIds[i];
2160 auto stats = streamStatsMap.find(streamId);
2161 if (stats != streamStatsMap.end()) {
2162 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2163 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2164 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002165 streamStats[i].mHistogramType =
2166 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2167 streamStats[i].mHistogramBins.assign(
2168 stats->second.mCaptureLatencyBins.begin(),
2169 stats->second.mCaptureLatencyBins.end());
2170 streamStats[i].mHistogramCounts.assign(
2171 stats->second.mCaptureLatencyHistogram.begin(),
2172 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002173 }
2174 }
2175 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002176 }
2177}
2178
Shuzhen Wang758c2152017-01-10 18:26:18 -08002179status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002180 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002181 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002182 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2183 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002184
2185 if (surfaceIds == nullptr) {
2186 return BAD_VALUE;
2187 }
2188
Zhijun He5d677d12016-05-29 16:52:39 -07002189 Mutex::Autolock il(mInterfaceLock);
2190 Mutex::Autolock l(mLock);
2191
Shuzhen Wang758c2152017-01-10 18:26:18 -08002192 if (consumers.size() == 0) {
2193 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002194 return BAD_VALUE;
2195 }
2196
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002197 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2198 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002199 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002200 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002201 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002202
2203 // isConsumerConfigurationDeferred will be off after setConsumers
2204 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002205 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002206 if (res != OK) {
2207 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2208 return res;
2209 }
2210
Emilian Peev40ead602017-09-26 15:46:36 +01002211 for (auto &consumer : consumers) {
2212 int id = stream->getSurfaceId(consumer);
2213 if (id < 0) {
2214 CLOGE("Invalid surface id!");
2215 return BAD_VALUE;
2216 }
2217 surfaceIds->push_back(id);
2218 }
2219
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002220 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002221 if (!stream->isConfiguring()) {
2222 CLOGE("Stream %d was already fully configured.", streamId);
2223 return INVALID_OPERATION;
2224 }
Zhijun He5d677d12016-05-29 16:52:39 -07002225
Shuzhen Wang0129d522016-10-30 22:43:41 -07002226 res = stream->finishConfiguration();
2227 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002228 // If finishConfiguration fails due to abandoned surface, do not set
2229 // device to error state.
2230 bool isSurfaceAbandoned =
2231 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2232 if (!isSurfaceAbandoned) {
2233 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2234 stream->getId(), strerror(-res), res);
2235 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002236 return res;
2237 }
Zhijun He5d677d12016-05-29 16:52:39 -07002238 }
2239
2240 return OK;
2241}
2242
Emilian Peev40ead602017-09-26 15:46:36 +01002243status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2244 const std::vector<OutputStreamInfo> &outputInfo,
2245 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2246 Mutex::Autolock il(mInterfaceLock);
2247 Mutex::Autolock l(mLock);
2248
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002249 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2250 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002251 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002252 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002253 }
2254
2255 for (const auto &it : removedSurfaceIds) {
2256 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2257 CLOGE("Shared surface still part of a pending request!");
2258 return -EBUSY;
2259 }
2260 }
2261
Emilian Peev40ead602017-09-26 15:46:36 +01002262 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2263 if (res != OK) {
2264 CLOGE("Stream %d failed to update stream (error %d %s) ",
2265 streamId, res, strerror(-res));
2266 if (res == UNKNOWN_ERROR) {
2267 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2268 __FUNCTION__);
2269 }
2270 return res;
2271 }
2272
2273 return res;
2274}
2275
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002276status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2277 Mutex::Autolock il(mInterfaceLock);
2278 Mutex::Autolock l(mLock);
2279
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002280 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2281 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002282 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2283 return BAD_VALUE;
2284 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002285
2286 if (dropping) {
2287 mSessionStatsBuilder.stopCounter(streamId);
2288 } else {
2289 mSessionStatsBuilder.startCounter(streamId);
2290 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002291 return stream->dropBuffers(dropping);
2292}
2293
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002294/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295 * Camera3Device private methods
2296 */
2297
2298sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002299 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002302 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002303 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304
2305 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002306 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002307 if (inputStreams.count > 0) {
2308 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002309 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002310 CLOGE("Request references unknown input stream %d",
2311 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 return NULL;
2313 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002314
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002315 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002316 SET_ERR_L("%s: input stream %d is not configured!",
2317 __FUNCTION__, mInputStream->getId());
2318 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002320 // Check if stream prepare is blocking requests.
2321 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002322 CLOGE("Request references an input stream that's being prepared!");
2323 return NULL;
2324 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325
2326 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002327 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002328 }
2329
2330 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002331 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002332 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002333 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002334 return NULL;
2335 }
2336
2337 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002338 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2339 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002340 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002341 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002342 return NULL;
2343 }
Zhijun He5d677d12016-05-29 16:52:39 -07002344 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002345 auto iter = surfaceMap.find(streams.data.i32[i]);
2346 if (iter != surfaceMap.end()) {
2347 const std::vector<size_t>& surfaces = iter->second;
2348 for (const auto& surface : surfaces) {
2349 if (stream->isConsumerConfigurationDeferred(surface)) {
2350 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2351 "due to deferred consumer", stream->getId(), surface);
2352 return NULL;
2353 }
2354 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002355 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002356 }
2357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002358 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002359 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2360 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002361 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002362 // Check if stream prepare is blocking requests.
2363 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002364 CLOGE("Request references an output stream that's being prepared!");
2365 return NULL;
2366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002367
2368 newRequest->mOutputStreams.push(stream);
2369 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002370 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002371 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002372
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002373 auto rotateAndCropEntry =
2374 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2375 if (rotateAndCropEntry.count > 0 &&
2376 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2377 newRequest->mRotateAndCropAuto = true;
2378 } else {
2379 newRequest->mRotateAndCropAuto = false;
2380 }
2381
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002382 auto zoomRatioEntry =
2383 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2384 if (zoomRatioEntry.count > 0 &&
2385 zoomRatioEntry.data.f[0] == 1.0f) {
2386 newRequest->mZoomRatioIs1x = true;
2387 } else {
2388 newRequest->mZoomRatioIs1x = false;
2389 }
2390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002391 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002392}
2393
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002394void Camera3Device::cancelStreamsConfigurationLocked() {
2395 int res = OK;
2396 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2397 res = mInputStream->cancelConfiguration();
2398 if (res != OK) {
2399 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2400 mInputStream->getId(), strerror(-res), res);
2401 }
2402 }
2403
2404 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002405 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002406 if (outputStream->isConfiguring()) {
2407 res = outputStream->cancelConfiguration();
2408 if (res != OK) {
2409 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2410 outputStream->getId(), strerror(-res), res);
2411 }
2412 }
2413 }
2414
2415 // Return state to that at start of call, so that future configures
2416 // properly clean things up
2417 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2418 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002419
2420 res = mPreparerThread->resume();
2421 if (res != OK) {
2422 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2423 }
2424}
2425
Emilian Peev0d0191e2020-04-21 17:01:18 -07002426bool Camera3Device::checkAbandonedStreamsLocked() {
2427 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2428 return true;
2429 }
2430
2431 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2432 auto stream = mOutputStreams[i];
2433 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2434 return true;
2435 }
2436 }
2437
2438 return false;
2439}
2440
Emilian Peev3bead5f2020-05-28 17:29:08 -07002441bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002442 ATRACE_CALL();
2443 bool ret = false;
2444
Shuzhen Wang316781a2020-08-18 18:11:01 -07002445 nsecs_t startTime = systemTime();
2446
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002447 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002448 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2449
2450 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002451 if (checkAbandonedStreamsLocked()) {
2452 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2453 __FUNCTION__);
2454 return true;
2455 }
2456
Emilian Peev3bead5f2020-05-28 17:29:08 -07002457 status_t rc = NO_ERROR;
2458 bool markClientActive = false;
2459 if (mStatus == STATUS_ACTIVE) {
2460 markClientActive = true;
2461 mPauseStateNotify = true;
2462 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2463
2464 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2465 }
2466
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002467 if (rc == NO_ERROR) {
2468 mNeedConfig = true;
2469 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2470 if (rc == NO_ERROR) {
2471 ret = true;
2472 mPauseStateNotify = false;
2473 //Moving to active state while holding 'mLock' is important.
2474 //There could be pending calls to 'create-/deleteStream' which
2475 //will trigger another stream configuration while the already
2476 //present streams end up with outstanding buffers that will
2477 //not get drained.
2478 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002479 } else if (rc == DEAD_OBJECT) {
2480 // DEAD_OBJECT can be returned if either the consumer surface is
2481 // abandoned, or the HAL has died.
2482 // - If the HAL has died, configureStreamsLocked call will set
2483 // device to error state,
2484 // - If surface is abandoned, we should not set device to error
2485 // state.
2486 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002487 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002488 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002489 }
2490 } else {
2491 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2492 }
2493
Shuzhen Wang316781a2020-08-18 18:11:01 -07002494 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2495 ns2ms(systemTime() - startTime));
2496
Emilian Peev3bead5f2020-05-28 17:29:08 -07002497 if (markClientActive) {
2498 mStatusTracker->markComponentActive(clientStatusId);
2499 }
2500
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002501 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002502}
2503
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002504status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002505 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506 ATRACE_CALL();
2507 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002508
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002509 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002510 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 return INVALID_OPERATION;
2512 }
2513
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002514 if (operatingMode < 0) {
2515 CLOGE("Invalid operating mode: %d", operatingMode);
2516 return BAD_VALUE;
2517 }
2518
2519 bool isConstrainedHighSpeed =
2520 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2521 operatingMode;
2522
2523 if (mOperatingMode != operatingMode) {
2524 mNeedConfig = true;
2525 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2526 mOperatingMode = operatingMode;
2527 }
2528
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002529 // In case called from configureStreams, abort queued input buffers not belonging to
2530 // any pending requests.
2531 if (mInputStream != NULL && notifyRequestThread) {
2532 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002533 camera_stream_buffer_t inputBuffer;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002534 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2535 /*respectHalLimit*/ false);
2536 if (res != OK) {
2537 // Exhausted acquiring all input buffers.
2538 break;
2539 }
2540
Emilian Peevf4816702020-04-03 15:44:51 -07002541 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002542 res = mInputStream->returnInputBuffer(inputBuffer);
2543 if (res != OK) {
2544 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2545 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2546 }
2547 }
2548 }
2549
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002550 if (!mNeedConfig) {
2551 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2552 return OK;
2553 }
2554
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002555 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002556 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002557 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2558 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002559 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002560 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002561 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002562 }
2563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002565 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002567 mPreparerThread->pause();
2568
Emilian Peevf4816702020-04-03 15:44:51 -07002569 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002570 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002571 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2572
Emilian Peevf4816702020-04-03 15:44:51 -07002573 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002574 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002575 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002576
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002577
2578 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002579 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002580 inputStream = mInputStream->startConfiguration();
2581 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002582 CLOGE("Can't start input stream configuration");
2583 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002584 return INVALID_OPERATION;
2585 }
2586 streams.add(inputStream);
2587 }
2588
2589 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002590
2591 // Don't configure bidi streams twice, nor add them twice to the list
2592 if (mOutputStreams[i].get() ==
2593 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2594
2595 config.num_streams--;
2596 continue;
2597 }
2598
Emilian Peevf4816702020-04-03 15:44:51 -07002599 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002600 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002601 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002602 CLOGE("Can't start output stream configuration");
2603 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002604 return INVALID_OPERATION;
2605 }
2606 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002607
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002608 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002609 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2610 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002611 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2612 bufferSizes[k] = static_cast<uint32_t>(
2613 getJpegBufferSize(outputStream->width, outputStream->height));
2614 } else if (outputStream->data_space ==
2615 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2616 bufferSizes[k] = outputStream->width * outputStream->height;
2617 } else {
2618 ALOGW("%s: Blob dataSpace %d not supported",
2619 __FUNCTION__, outputStream->data_space);
2620 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002621 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 }
2623
2624 config.streams = streams.editArray();
2625
2626 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002627 // max_buffers, usage, and priv fields, as well as data_space and format
2628 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002629
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002630 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002631 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002632 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002634 if (res == BAD_VALUE) {
2635 // HAL rejected this set of streams as unsupported, clean up config
2636 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002637 CLOGE("Set of requested inputs/outputs not supported by HAL");
2638 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002639 return BAD_VALUE;
2640 } else if (res != OK) {
2641 // Some other kind of error from configure_streams - this is not
2642 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002643 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2644 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645 return res;
2646 }
2647
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002648 // Finish all stream configuration immediately.
2649 // TODO: Try to relax this later back to lazy completion, which should be
2650 // faster
2651
Igor Murashkin073f8572013-05-02 14:59:28 -07002652 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002653 bool streamReConfigured = false;
2654 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002655 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002656 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002657 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002658 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002659 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2660 return DEAD_OBJECT;
2661 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002662 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002663 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002664 if (streamReConfigured) {
2665 mInterface->onStreamReConfigured(mInputStream->getId());
2666 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002667 }
2668
2669 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002670 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002671 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002672 bool streamReConfigured = false;
2673 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002674 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002675 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002676 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002677 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002678 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2679 return DEAD_OBJECT;
2680 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002681 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002682 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002683 if (streamReConfigured) {
2684 mInterface->onStreamReConfigured(outputStream->getId());
2685 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002686 }
2687 }
2688
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002689 // Request thread needs to know to avoid using repeat-last-settings protocol
2690 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002691 if (notifyRequestThread) {
2692 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2693 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694
Zhijun He90f7c372016-08-16 16:19:43 -07002695 char value[PROPERTY_VALUE_MAX];
2696 property_get("camera.fifo.disable", value, "0");
2697 int32_t disableFifo = atoi(value);
2698 if (disableFifo != 1) {
2699 // Boost priority of request thread to SCHED_FIFO.
2700 pid_t requestThreadTid = mRequestThread->getTid();
2701 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002702 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002703 if (res != OK) {
2704 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2705 strerror(-res), res);
2706 } else {
2707 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2708 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002709 }
2710
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002711 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002712 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2713 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2714 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2715 sessionParams.unlock(newSessionParams);
2716 mSessionParams.unlock(currentSessionParams);
2717 if (updateSessionParams) {
2718 mSessionParams = sessionParams;
2719 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002720
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002721 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002722
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002723 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002724 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002725
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002726 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002727
Zhijun He0a210512014-07-24 13:45:15 -07002728 // tear down the deleted streams after configure streams.
2729 mDeletedStreams.clear();
2730
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002731 auto rc = mPreparerThread->resume();
2732 if (rc != OK) {
2733 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2734 return rc;
2735 }
2736
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002737 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002738 mRequestBufferSM.onStreamsConfigured();
2739 }
2740
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002741 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002742}
2743
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002744status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002745 ATRACE_CALL();
2746 status_t res;
2747
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002748 if (mFakeStreamId != NO_STREAM) {
2749 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002750 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002751 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002752 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002753 return INVALID_OPERATION;
2754 }
2755
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002756 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002757
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002758 sp<Camera3OutputStreamInterface> fakeStream =
2759 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002760
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002761 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002762 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002763 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002764 return res;
2765 }
2766
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002767 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002768 mNextStreamId++;
2769
2770 return OK;
2771}
2772
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002773status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002774 ATRACE_CALL();
2775 status_t res;
2776
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002777 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002778 if (mOutputStreams.size() == 1) return OK;
2779
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002780 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002781
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002782 // Ok, have a fake stream and there's at least one other output stream,
2783 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002784
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002785 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002786 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002787 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002788 return INVALID_OPERATION;
2789 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002790 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002791
2792 // Free up the stream endpoint so that it can be used by some other stream
2793 res = deletedStream->disconnect();
2794 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002795 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002796 // fall through since we want to still list the stream as deleted.
2797 }
2798 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002799 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002800
2801 return res;
2802}
2803
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002804void Camera3Device::setErrorState(const char *fmt, ...) {
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 va_list args;
2808 va_start(args, fmt);
2809
2810 setErrorStateLockedV(fmt, args);
2811
2812 va_end(args);
2813}
2814
2815void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002816 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002817 Mutex::Autolock l(mLock);
2818 setErrorStateLockedV(fmt, args);
2819}
2820
2821void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2822 va_list args;
2823 va_start(args, fmt);
2824
2825 setErrorStateLockedV(fmt, args);
2826
2827 va_end(args);
2828}
2829
2830void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002831 // Print out all error messages to log
2832 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002833 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002834
2835 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002836 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002837
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002838 mErrorCause = errorCause;
2839
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002840 if (mRequestThread != nullptr) {
2841 mRequestThread->setPaused(true);
2842 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002843 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002844
2845 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002846 sp<NotificationListener> listener = mListener.promote();
2847 if (listener != NULL) {
2848 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002849 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002850 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002851 }
2852
2853 // Save stack trace. View by dumping it later.
2854 CameraTraces::saveTrace();
2855 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002856}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002857
2858/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002859 * In-flight request management
2860 */
2861
Jianing Weicb0652e2014-03-12 18:29:36 -07002862status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002863 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002864 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002865 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002866 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002867 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002868 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002869 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002870
2871 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002872 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002873 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002874 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002875 if (res < 0) return res;
2876
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002877 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002878 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2879 // avoid a deadlock during reprocess requests.
2880 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002881 if (mStatusTracker != nullptr) {
2882 mStatusTracker->markComponentActive(mInFlightStatusId);
2883 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002884 }
2885
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002886 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002887 return OK;
2888}
2889
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002890void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002891 // Indicate idle inFlightMap to the status tracker
2892 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002893 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002894 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2895 // avoid a deadlock during reprocess requests.
2896 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002897 if (mStatusTracker != nullptr) {
2898 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2899 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002900 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002901 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002902}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002903
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002904void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002905 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002906 // something has likely gone wrong. This might still be legit only if application send in
2907 // a long burst of long exposure requests.
2908 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2909 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2910 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2911 mInFlightMap.size(), mExpectedInflightDuration);
2912 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2913 kInFlightWarnLimitHighSpeed) {
2914 CLOGW("In-flight list too large for high speed configuration: %zu,"
2915 "total inflight duration %" PRIu64,
2916 mInFlightMap.size(), mExpectedInflightDuration);
2917 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002918 }
2919}
2920
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002921void Camera3Device::onInflightMapFlushedLocked() {
2922 mExpectedInflightDuration = 0;
2923}
2924
2925void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002926 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002927 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2928 mInFlightMap.removeItemsAt(idx, 1);
2929
2930 onInflightEntryRemovedLocked(duration);
2931}
2932
2933
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002934void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002935 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002936 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002937 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002938 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002939 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002940 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002941
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002942 FlushInflightReqStates states {
2943 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002944 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002945
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002946 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002947}
2948
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002949CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002950 ALOGV("%s", __FUNCTION__);
2951
Igor Murashkin1e479c02013-09-06 16:55:14 -07002952 CameraMetadata retVal;
2953
2954 if (mRequestThread != NULL) {
2955 retVal = mRequestThread->getLatestRequest();
2956 }
2957
Igor Murashkin1e479c02013-09-06 16:55:14 -07002958 return retVal;
2959}
2960
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002961void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002962 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2963 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2964
2965 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2966 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002967}
2968
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002969/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002970 * HalInterface inner class methods
2971 */
2972
Yifan Hongf79b5542017-04-11 14:44:25 -07002973Camera3Device::HalInterface::HalInterface(
2974 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002975 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002976 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002977 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002978 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002979 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002980 mIsReconfigurationQuerySupported(true),
2981 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002982 // Check with hardware service manager if we can downcast these interfaces
2983 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002984 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2985 if (castResult_3_6.isOk()) {
2986 mHidlSession_3_6 = castResult_3_6;
2987 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002988 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2989 if (castResult_3_5.isOk()) {
2990 mHidlSession_3_5 = castResult_3_5;
2991 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002992 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2993 if (castResult_3_4.isOk()) {
2994 mHidlSession_3_4 = castResult_3_4;
2995 }
2996 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2997 if (castResult_3_3.isOk()) {
2998 mHidlSession_3_3 = castResult_3_3;
2999 }
3000}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003001
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003002Camera3Device::HalInterface::HalInterface() :
3003 mUseHalBufManager(false),
3004 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003005
3006Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003007 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003008 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003009 mUseHalBufManager(other.mUseHalBufManager),
3010 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003011
3012bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003013 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003014}
3015
3016void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003017 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003018 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003019 mHidlSession_3_4.clear();
3020 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003021 mHidlSession.clear();
3022}
3023
3024status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003025 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003026 /*out*/ camera_metadata_t **requestTemplate) {
3027 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3028 if (!valid()) return INVALID_OPERATION;
3029 status_t res = OK;
3030
Emilian Peev31abd0a2017-05-11 18:37:46 +01003031 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003032
3033 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003034 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003035 status = s;
3036 if (status == common::V1_0::Status::OK) {
3037 const camera_metadata *r =
3038 reinterpret_cast<const camera_metadata_t*>(request.data());
3039 size_t expectedSize = request.size();
3040 int ret = validate_camera_metadata_structure(r, &expectedSize);
3041 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3042 *requestTemplate = clone_camera_metadata(r);
3043 if (*requestTemplate == nullptr) {
3044 ALOGE("%s: Unable to clone camera metadata received from HAL",
3045 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003046 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003047 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003048 } else {
3049 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3050 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003051 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003052 }
3053 };
3054 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003055 RequestTemplate id;
3056 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003057 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003058 id = RequestTemplate::PREVIEW;
3059 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003060 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003061 id = RequestTemplate::STILL_CAPTURE;
3062 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003063 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003064 id = RequestTemplate::VIDEO_RECORD;
3065 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003066 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003067 id = RequestTemplate::VIDEO_SNAPSHOT;
3068 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003069 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003070 id = RequestTemplate::ZERO_SHUTTER_LAG;
3071 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003072 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003073 id = RequestTemplate::MANUAL;
3074 break;
3075 default:
3076 // Unknown template ID, or this HAL is too old to support it
3077 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003078 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003079 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003080
Emilian Peev31abd0a2017-05-11 18:37:46 +01003081 if (!err.isOk()) {
3082 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3083 res = DEAD_OBJECT;
3084 } else {
3085 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003086 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003087
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088 return res;
3089}
3090
Emilian Peev4ec17882019-01-24 17:16:58 -08003091bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3092 CameraMetadata& newSessionParams) {
3093 // We do reconfiguration by default;
3094 bool ret = true;
3095 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3096 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3097 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3098 oldSessionParams.getAndLock());
3099 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3100 newSessionParams.getAndLock());
3101 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3102 get_camera_metadata_size(oldSessioMeta));
3103 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3104 get_camera_metadata_size(newSessioMeta));
3105 hardware::camera::common::V1_0::Status callStatus;
3106 bool required;
3107 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3108 bool requiredFlag) {
3109 callStatus = s;
3110 required = requiredFlag;
3111 };
3112 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3113 oldSessionParams.unlock(oldSessioMeta);
3114 newSessionParams.unlock(newSessioMeta);
3115 if (err.isOk()) {
3116 switch (callStatus) {
3117 case hardware::camera::common::V1_0::Status::OK:
3118 ret = required;
3119 break;
3120 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3121 mIsReconfigurationQuerySupported = false;
3122 ret = true;
3123 break;
3124 default:
3125 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3126 ret = true;
3127 }
3128 } else {
3129 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3130 ret = true;
3131 }
3132 }
3133
3134 return ret;
3135}
3136
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003137status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003138 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003139 ATRACE_NAME("CameraHal::configureStreams");
3140 if (!valid()) return INVALID_OPERATION;
3141 status_t res = OK;
3142
Emilian Peev31abd0a2017-05-11 18:37:46 +01003143 // Convert stream config to HIDL
3144 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003145 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3146 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3147 requestedConfiguration3_2.streams.resize(config->num_streams);
3148 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003149 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003150 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3151 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003152 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003153
Emilian Peev31abd0a2017-05-11 18:37:46 +01003154 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3155 cam3stream->setBufferFreedListener(this);
3156 int streamId = cam3stream->getId();
3157 StreamType streamType;
3158 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003159 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003160 streamType = StreamType::OUTPUT;
3161 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003162 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003163 streamType = StreamType::INPUT;
3164 break;
3165 default:
3166 ALOGE("%s: Stream %d: Unsupported stream type %d",
3167 __FUNCTION__, streamId, config->streams[i]->stream_type);
3168 return BAD_VALUE;
3169 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003170 dst3_2.id = streamId;
3171 dst3_2.streamType = streamType;
3172 dst3_2.width = src->width;
3173 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003174 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003175 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003176 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3177 // to HAL are original, not the overriden ones.
3178 if (mHidlSession_3_5 != nullptr) {
3179 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3180 cam3stream->getOriginalFormat() : src->format);
3181 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3182 cam3stream->getOriginalDataSpace() : src->data_space);
3183 } else {
3184 dst3_2.format = mapToPixelFormat(src->format);
3185 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3186 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003187 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003188 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003189 if (src->physical_camera_id != nullptr) {
3190 dst3_4.physicalCameraId = src->physical_camera_id;
3191 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003192
3193 activeStreams.insert(streamId);
3194 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003195 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003196 }
3197 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003198 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003199
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003200 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003202 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003203 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003204 if (res != OK) {
3205 return res;
3206 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003207 requestedConfiguration3_2.operationMode = operationMode;
3208 requestedConfiguration3_4.operationMode = operationMode;
3209 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003210 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3211 get_camera_metadata_size(sessionParams));
3212
Emilian Peev31abd0a2017-05-11 18:37:46 +01003213 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003214 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003215 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003216 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003217 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003218
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003219 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003220 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3221 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003222 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003223 };
3224
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003225 auto configStream36Cb = [&status, &finalConfiguration3_6]
3226 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3227 finalConfiguration3_6 = halConfiguration;
3228 status = s;
3229 };
3230
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003231 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3232 (hardware::Return<void>& err) -> status_t {
3233 if (!err.isOk()) {
3234 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3235 return DEAD_OBJECT;
3236 }
3237 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3238 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3239 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3240 }
3241 return OK;
3242 };
3243
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003244 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3245 (hardware::Return<void>& err) -> status_t {
3246 if (!err.isOk()) {
3247 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3248 return DEAD_OBJECT;
3249 }
3250 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3251 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3252 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3253 }
3254 return OK;
3255 };
3256
Shuzhen Wang92653952019-05-07 15:11:43 -07003257 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003258 if (mHidlSession_3_6 != nullptr) {
3259 ALOGV("%s: v3.6 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_6->configureStreams_3_6(
3264 requestedConfiguration3_5, configStream36Cb);
3265 res = postprocConfigStream36(err);
3266 if (res != OK) {
3267 return res;
3268 }
3269 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003270 ALOGV("%s: v3.5 device found", __FUNCTION__);
3271 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3272 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3273 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3274 auto err = mHidlSession_3_5->configureStreams_3_5(
3275 requestedConfiguration3_5, configStream34Cb);
3276 res = postprocConfigStream34(err);
3277 if (res != OK) {
3278 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003279 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003280 } else if (mHidlSession_3_4 != nullptr) {
3281 // We do; use v3.4 for the call
3282 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003283 auto err = mHidlSession_3_4->configureStreams_3_4(
3284 requestedConfiguration3_4, configStream34Cb);
3285 res = postprocConfigStream34(err);
3286 if (res != OK) {
3287 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003288 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003289 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003290 // We do; use v3.3 for the call
3291 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003292 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003293 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003294 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 finalConfiguration = halConfiguration;
3296 status = s;
3297 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003298 if (!err.isOk()) {
3299 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3300 return DEAD_OBJECT;
3301 }
3302 } else {
3303 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3304 ALOGV("%s: v3.2 device found", __FUNCTION__);
3305 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003306 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003307 [&status, &finalConfiguration_3_2]
3308 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3309 finalConfiguration_3_2 = halConfiguration;
3310 status = s;
3311 });
3312 if (!err.isOk()) {
3313 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3314 return DEAD_OBJECT;
3315 }
3316 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3317 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3318 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3319 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003320 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003321 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322 }
3323
3324 if (status != common::V1_0::Status::OK ) {
3325 return CameraProviderManager::mapToStatusT(status);
3326 }
3327
3328 // And convert output stream configuration from HIDL
3329
3330 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003331 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003332 int streamId = Camera3Stream::cast(dst)->getId();
3333
3334 // Start scan at i, with the assumption that the stream order matches
3335 size_t realIdx = i;
3336 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003337 size_t halStreamCount = finalConfiguration.streams.size();
3338 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003339 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003340 found = true;
3341 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003342 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003343 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003344 }
3345 if (!found) {
3346 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3347 __FUNCTION__, streamId);
3348 return INVALID_OPERATION;
3349 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003350 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003351 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003352
Emilian Peev710c1422017-08-30 11:19:38 +01003353 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003354 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3355 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3356
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003357 if (mHidlSession_3_6 != nullptr) {
3358 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3359 }
3360
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003361 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003362 dstStream->setFormatOverride(false);
3363 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003364 if (dst->format != overrideFormat) {
3365 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3366 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003367 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003368 if (dst->data_space != overrideDataSpace) {
3369 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3370 streamId, dst->format);
3371 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003372 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003373 bool needFormatOverride =
3374 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3375 bool needDataspaceOverride =
3376 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003377 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003378 dstStream->setFormatOverride(needFormatOverride);
3379 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003380 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003381 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003382 }
3383
Emilian Peevf4816702020-04-03 15:44:51 -07003384 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003385 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003387 __FUNCTION__, streamId);
3388 return INVALID_OPERATION;
3389 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003390 dstStream->setUsage(
3391 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003392 } else {
3393 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003394 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003395 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3396 __FUNCTION__, streamId);
3397 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003398 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003399 dstStream->setUsage(
3400 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003401 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003402 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003403 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003404
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003405 return res;
3406}
3407
Emilian Peevf4816702020-04-03 15:44:51 -07003408status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003409 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003410 /*out*/std::vector<native_handle_t*>* handlesCreated,
3411 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003412 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003413 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3414 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3415 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003416 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003417 }
3418
3419 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003420
3421 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003422
3423 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003424 if (request->input_buffer != nullptr) {
3425 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3426 buffer_handle_t buf = *(request->input_buffer->buffer);
3427 auto pair = getBufferId(buf, streamId);
3428 bool isNewBuffer = pair.first;
3429 uint64_t bufferId = pair.second;
3430 captureRequest->inputBuffer.streamId = streamId;
3431 captureRequest->inputBuffer.bufferId = bufferId;
3432 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3433 captureRequest->inputBuffer.status = BufferStatus::OK;
3434 native_handle_t *acquireFence = nullptr;
3435 if (request->input_buffer->acquire_fence != -1) {
3436 acquireFence = native_handle_create(1,0);
3437 acquireFence->data[0] = request->input_buffer->acquire_fence;
3438 handlesCreated->push_back(acquireFence);
3439 }
3440 captureRequest->inputBuffer.acquireFence = acquireFence;
3441 captureRequest->inputBuffer.releaseFence = nullptr;
3442
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003443 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003444 request->input_buffer->buffer);
3445 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003446 } else {
3447 captureRequest->inputBuffer.streamId = -1;
3448 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3449 }
3450
3451 captureRequest->outputBuffers.resize(request->num_output_buffers);
3452 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003453 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003454 StreamBuffer &dst = captureRequest->outputBuffers[i];
3455 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003456 if (src->buffer != nullptr) {
3457 buffer_handle_t buf = *(src->buffer);
3458 auto pair = getBufferId(buf, streamId);
3459 bool isNewBuffer = pair.first;
3460 dst.bufferId = pair.second;
3461 dst.buffer = isNewBuffer ? buf : nullptr;
3462 native_handle_t *acquireFence = nullptr;
3463 if (src->acquire_fence != -1) {
3464 acquireFence = native_handle_create(1,0);
3465 acquireFence->data[0] = src->acquire_fence;
3466 handlesCreated->push_back(acquireFence);
3467 }
3468 dst.acquireFence = acquireFence;
3469 } else if (mUseHalBufManager) {
3470 // HAL buffer management path
3471 dst.bufferId = BUFFER_ID_NO_BUFFER;
3472 dst.buffer = nullptr;
3473 dst.acquireFence = nullptr;
3474 } else {
3475 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3476 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003477 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003478 dst.streamId = streamId;
3479 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003480 dst.releaseFence = nullptr;
3481
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003482 // Output buffers are empty when using HAL buffer manager
3483 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003484 mBufferRecords.pushInflightBuffer(
3485 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003486 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003487 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003488 }
3489 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003490 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003491}
3492
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003493void Camera3Device::HalInterface::cleanupNativeHandles(
3494 std::vector<native_handle_t*> *handles, bool closeFd) {
3495 if (handles == nullptr) {
3496 return;
3497 }
3498 if (closeFd) {
3499 for (auto& handle : *handles) {
3500 native_handle_close(handle);
3501 }
3502 }
3503 for (auto& handle : *handles) {
3504 native_handle_delete(handle);
3505 }
3506 handles->clear();
3507 return;
3508}
3509
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003510status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003511 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003512 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3513 if (!valid()) return INVALID_OPERATION;
3514
Emilian Peevaebbe412018-01-15 13:53:24 +00003515 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3516 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3517 if (castResult_3_4.isOk()) {
3518 hidlSession_3_4 = castResult_3_4;
3519 }
3520
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003521 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003522 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003523 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003524 if (hidlSession_3_4 != nullptr) {
3525 captureRequests_3_4.resize(batchSize);
3526 } else {
3527 captureRequests.resize(batchSize);
3528 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003529 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003530 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003531
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003532 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003533 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003534 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003535 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003536 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003537 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003538 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3539 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003540 }
3541 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003542 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003543 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003544 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003545 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003546 }
3547
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003548 std::vector<device::V3_2::BufferCache> cachesToRemove;
3549 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003550 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003551 for (auto& pair : mFreedBuffers) {
3552 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003553 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003554 cachesToRemove.push_back({pair.first, pair.second});
3555 }
3556 }
3557 mFreedBuffers.clear();
3558 }
3559
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003560 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3561 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003562
3563 // Write metadata to FMQ.
3564 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003565 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003566 device::V3_2::CaptureRequest* captureRequest;
3567 if (hidlSession_3_4 != nullptr) {
3568 captureRequest = &captureRequests_3_4[i].v3_2;
3569 } else {
3570 captureRequest = &captureRequests[i];
3571 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003572
3573 if (request->settings != nullptr) {
3574 size_t settingsSize = get_camera_metadata_size(request->settings);
3575 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3576 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3577 captureRequest->settings.resize(0);
3578 captureRequest->fmqSettingsSize = settingsSize;
3579 } else {
3580 if (mRequestMetadataQueue != nullptr) {
3581 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3582 }
3583 captureRequest->settings.setToExternal(
3584 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3585 get_camera_metadata_size(request->settings));
3586 captureRequest->fmqSettingsSize = 0u;
3587 }
3588 } else {
3589 // A null request settings maps to a size-0 CameraMetadata
3590 captureRequest->settings.resize(0);
3591 captureRequest->fmqSettingsSize = 0u;
3592 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003593
3594 if (hidlSession_3_4 != nullptr) {
3595 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3596 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003597 if (request->physcam_settings != nullptr) {
3598 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3599 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3600 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3601 settingsSize)) {
3602 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3603 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3604 settingsSize;
3605 } else {
3606 if (mRequestMetadataQueue != nullptr) {
3607 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3608 }
3609 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3610 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3611 request->physcam_settings[j])),
3612 get_camera_metadata_size(request->physcam_settings[j]));
3613 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003614 }
Emilian Peev00420d22018-02-05 21:33:13 +00003615 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003616 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003617 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003618 }
3619 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3620 request->physcam_id[j];
3621 }
3622 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003623 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003624
3625 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003626 auto resultCallback =
3627 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3628 status = s;
3629 *numRequestProcessed = n;
3630 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003631 if (hidlSession_3_4 != nullptr) {
3632 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003633 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003634 } else {
3635 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003636 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003637 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003638 if (!err.isOk()) {
3639 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003640 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003641 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003642
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003643 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3644 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3645 __FUNCTION__, *numRequestProcessed, batchSize);
3646 status = common::V1_0::Status::INTERNAL_ERROR;
3647 }
3648
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003649 res = CameraProviderManager::mapToStatusT(status);
3650 if (res == OK) {
3651 if (mHidlSession->isRemote()) {
3652 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3653 // sent to camera HAL processes)
3654 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3655 } else {
3656 // In passthrough mode the FDs are now owned by HAL
3657 cleanupNativeHandles(&handlesCreated);
3658 }
3659 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003660 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003661 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003662 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003663 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003664}
3665
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003666status_t Camera3Device::HalInterface::flush() {
3667 ATRACE_NAME("CameraHal::flush");
3668 if (!valid()) return INVALID_OPERATION;
3669 status_t res = OK;
3670
Emilian Peev31abd0a2017-05-11 18:37:46 +01003671 auto err = mHidlSession->flush();
3672 if (!err.isOk()) {
3673 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3674 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003675 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003676 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003677 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003678
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003679 return res;
3680}
3681
Emilian Peev31abd0a2017-05-11 18:37:46 +01003682status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003683 ATRACE_NAME("CameraHal::dump");
3684 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003685
Emilian Peev31abd0a2017-05-11 18:37:46 +01003686 // Handled by CameraProviderManager::dump
3687
3688 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003689}
3690
3691status_t Camera3Device::HalInterface::close() {
3692 ATRACE_NAME("CameraHal::close()");
3693 if (!valid()) return INVALID_OPERATION;
3694 status_t res = OK;
3695
Emilian Peev31abd0a2017-05-11 18:37:46 +01003696 auto err = mHidlSession->close();
3697 // Interface will be dead shortly anyway, so don't log errors
3698 if (!err.isOk()) {
3699 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003700 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003701
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003702 return res;
3703}
3704
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003705void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3706 ATRACE_NAME("CameraHal::signalPipelineDrain");
3707 if (!valid() || mHidlSession_3_5 == nullptr) {
3708 ALOGE("%s called on invalid camera!", __FUNCTION__);
3709 return;
3710 }
3711
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003712 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003713 if (!err.isOk()) {
3714 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3715 return;
3716 }
3717}
3718
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003719status_t Camera3Device::HalInterface::switchToOffline(
3720 const std::vector<int32_t>& streamsToKeep,
3721 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003722 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3723 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003724 ATRACE_NAME("CameraHal::switchToOffline");
3725 if (!valid() || mHidlSession_3_6 == nullptr) {
3726 ALOGE("%s called on invalid camera!", __FUNCTION__);
3727 return INVALID_OPERATION;
3728 }
3729
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003730 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3731 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003732 return INVALID_OPERATION;
3733 }
3734
3735 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003736 auto resultCallback =
3737 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3738 status = s;
3739 *offlineSessionInfo = info;
3740 *offlineSession = session;
3741 };
3742 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3743
3744 if (!err.isOk()) {
3745 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3746 return DEAD_OBJECT;
3747 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003748
3749 status_t ret = CameraProviderManager::mapToStatusT(status);
3750 if (ret != OK) {
3751 return ret;
3752 }
3753
3754 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3755 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3756 // returns from switchToOffline.
3757
3758
3759 // Validate buffer caches
3760 std::vector<int32_t> streams;
3761 streams.reserve(offlineSessionInfo->offlineStreams.size());
3762 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3763 int32_t id = offlineStream.id;
3764 streams.push_back(id);
3765 // Verify buffer caches
3766 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3767 offlineStream.circulatingBufferIds.end());
3768 if (!verifyBufferIds(id, bufIds)) {
3769 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3770 return UNKNOWN_ERROR;
3771 }
3772 }
3773
3774 // Move buffer records
3775 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3776 bufferRecords->takeInflightBufferMap(mBufferRecords);
3777 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3778 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003779}
3780
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003781void Camera3Device::HalInterface::getInflightBufferKeys(
3782 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003783 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003784 return;
3785}
3786
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003787void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3788 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003789 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003790 return;
3791}
3792
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003793bool Camera3Device::HalInterface::verifyBufferIds(
3794 int32_t streamId, std::vector<uint64_t>& bufIds) {
3795 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003796}
3797
3798status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003799 int32_t frameNumber, int32_t streamId,
3800 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003801 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003802}
3803
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003804status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003805 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003806 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003807}
3808
3809// Find and pop a buffer_handle_t based on bufferId
3810status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003811 uint64_t bufferId,
3812 /*out*/ buffer_handle_t** buffer,
3813 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003814 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003815}
3816
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003817std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3818 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003819 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003820}
3821
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003822void Camera3Device::HalInterface::onBufferFreed(
3823 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003824 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3825 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3826 if (bufferId != BUFFER_ID_NO_BUFFER) {
3827 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003828 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003829}
3830
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003831void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003832 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3833 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3834 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003835 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3836 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003837}
3838
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003839/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003840 * RequestThread inner class methods
3841 */
3842
3843Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003844 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003845 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3846 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003847 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003848 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003849 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003850 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003851 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003852 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003853 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003854 mReconfigured(false),
3855 mDoPause(false),
3856 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003857 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003858 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003859 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003860 mCurrentAfTriggerId(0),
3861 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003862 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003863 mRepeatingLastFrameNumber(
3864 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003865 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003866 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003867 mRequestLatency(kRequestLatencyBinSize),
3868 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003869 mLatestSessionParams(sessionParamKeys.size()),
3870 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003871 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003872}
3873
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003874Camera3Device::RequestThread::~RequestThread() {}
3875
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003876void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003877 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003878 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003879 Mutex::Autolock l(mRequestLock);
3880 mListener = listener;
3881}
3882
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003883void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3884 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003885 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003886 Mutex::Autolock l(mRequestLock);
3887 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003888 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003889 // Prepare video stream for high speed recording.
3890 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003891 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003892}
3893
Jianing Wei90e59c92014-03-12 18:29:36 -07003894status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003895 List<sp<CaptureRequest> > &requests,
3896 /*out*/
3897 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003898 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003899 Mutex::Autolock l(mRequestLock);
3900 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3901 ++it) {
3902 mRequestQueue.push_back(*it);
3903 }
3904
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003905 if (lastFrameNumber != NULL) {
3906 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3907 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3908 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3909 *lastFrameNumber);
3910 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003911
Jianing Wei90e59c92014-03-12 18:29:36 -07003912 unpauseForNewRequests();
3913
3914 return OK;
3915}
3916
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003917
3918status_t Camera3Device::RequestThread::queueTrigger(
3919 RequestTrigger trigger[],
3920 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003921 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003922 Mutex::Autolock l(mTriggerMutex);
3923 status_t ret;
3924
3925 for (size_t i = 0; i < count; ++i) {
3926 ret = queueTriggerLocked(trigger[i]);
3927
3928 if (ret != OK) {
3929 return ret;
3930 }
3931 }
3932
3933 return OK;
3934}
3935
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003936const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3937 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003938 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003939 if (d != nullptr) return d->mId;
3940 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003941}
3942
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003943status_t Camera3Device::RequestThread::queueTriggerLocked(
3944 RequestTrigger trigger) {
3945
3946 uint32_t tag = trigger.metadataTag;
3947 ssize_t index = mTriggerMap.indexOfKey(tag);
3948
3949 switch (trigger.getTagType()) {
3950 case TYPE_BYTE:
3951 // fall-through
3952 case TYPE_INT32:
3953 break;
3954 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003955 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3956 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003957 return INVALID_OPERATION;
3958 }
3959
3960 /**
3961 * Collect only the latest trigger, since we only have 1 field
3962 * in the request settings per trigger tag, and can't send more than 1
3963 * trigger per request.
3964 */
3965 if (index != NAME_NOT_FOUND) {
3966 mTriggerMap.editValueAt(index) = trigger;
3967 } else {
3968 mTriggerMap.add(tag, trigger);
3969 }
3970
3971 return OK;
3972}
3973
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003974status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003975 const RequestList &requests,
3976 /*out*/
3977 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003978 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003979 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003980 if (lastFrameNumber != NULL) {
3981 *lastFrameNumber = mRepeatingLastFrameNumber;
3982 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003983 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003984 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003985 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3986 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003987
3988 unpauseForNewRequests();
3989
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003990 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003991 return OK;
3992}
3993
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003994bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003995 if (mRepeatingRequests.empty()) {
3996 return false;
3997 }
3998 int32_t requestId = requestIn->mResultExtras.requestId;
3999 const RequestList &repeatRequests = mRepeatingRequests;
4000 // All repeating requests are guaranteed to have same id so only check first quest
4001 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4002 return (firstRequest->mResultExtras.requestId == requestId);
4003}
4004
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004005status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004006 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004007 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004008 return clearRepeatingRequestsLocked(lastFrameNumber);
4009
4010}
4011
4012status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004013 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004014 if (lastFrameNumber != NULL) {
4015 *lastFrameNumber = mRepeatingLastFrameNumber;
4016 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004017 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004018 return OK;
4019}
4020
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004021status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004022 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004023 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004024 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004025 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004026
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004027 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004028
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004029 // Send errors for all requests pending in the request queue, including
4030 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004031 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004032 if (listener != NULL) {
4033 for (RequestList::iterator it = mRequestQueue.begin();
4034 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004035 // Abort the input buffers for reprocess requests.
4036 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004037 camera_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004038 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4039 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004040 if (res != OK) {
4041 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4042 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4043 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004044 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004045 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4046 if (res != OK) {
4047 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4048 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4049 }
4050 }
4051 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004052 // Set the frame number this request would have had, if it
4053 // had been submitted; this frame number will not be reused.
4054 // The requestId and burstId fields were set when the request was
4055 // submitted originally (in convertMetadataListToRequestListLocked)
4056 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004057 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004058 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004059 }
4060 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004061 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004062
4063 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004064 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004065 if (lastFrameNumber != NULL) {
4066 *lastFrameNumber = mRepeatingLastFrameNumber;
4067 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004068 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004069 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004070 return OK;
4071}
4072
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004073status_t Camera3Device::RequestThread::flush() {
4074 ATRACE_CALL();
4075 Mutex::Autolock l(mFlushLock);
4076
Emilian Peev08dd2452017-04-06 16:55:14 +01004077 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004078}
4079
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004080void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004081 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004082 Mutex::Autolock l(mPauseLock);
4083 mDoPause = paused;
4084 mDoPauseSignal.signal();
4085}
4086
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004087status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4088 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004089 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004090 Mutex::Autolock l(mLatestRequestMutex);
4091 status_t res;
4092 while (mLatestRequestId != requestId) {
4093 nsecs_t startTime = systemTime();
4094
4095 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4096 if (res != OK) return res;
4097
4098 timeout -= (systemTime() - startTime);
4099 }
4100
4101 return OK;
4102}
4103
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004104void Camera3Device::RequestThread::requestExit() {
4105 // Call parent to set up shutdown
4106 Thread::requestExit();
4107 // The exit from any possible waits
4108 mDoPauseSignal.signal();
4109 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004110
4111 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4112 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004113}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004114
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004115void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004116 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004117 bool surfaceAbandoned = false;
4118 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004119 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004120 {
4121 Mutex::Autolock l(mRequestLock);
4122 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4123 // repeating requests.
4124 for (const auto& request : mRepeatingRequests) {
4125 for (const auto& s : request->mOutputStreams) {
4126 if (s->isAbandoned()) {
4127 surfaceAbandoned = true;
4128 clearRepeatingRequestsLocked(&lastFrameNumber);
4129 break;
4130 }
4131 }
4132 if (surfaceAbandoned) {
4133 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004134 }
4135 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004136 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004137 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004138
4139 if (listener != NULL && surfaceAbandoned) {
4140 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004141 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004142}
4143
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004144bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004145 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004146 status_t res;
4147 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004148 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004149 uint32_t numRequestProcessed = 0;
4150 for (size_t i = 0; i < batchSize; i++) {
4151 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004152 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004153 }
4154
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004155 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4156
4157 bool triggerRemoveFailed = false;
4158 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4159 for (size_t i = 0; i < numRequestProcessed; i++) {
4160 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4161 nextRequest.submitted = true;
4162
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004163 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004164
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004165 if (!triggerRemoveFailed) {
4166 // Remove any previously queued triggers (after unlock)
4167 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4168 if (removeTriggerRes != OK) {
4169 triggerRemoveFailed = true;
4170 triggerFailedRequest = nextRequest;
4171 }
4172 }
4173 }
4174
4175 if (triggerRemoveFailed) {
4176 SET_ERR("RequestThread: Unable to remove triggers "
4177 "(capture request %d, HAL device: %s (%d)",
4178 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4179 cleanUpFailedRequests(/*sendRequestError*/ false);
4180 return false;
4181 }
4182
4183 if (res != OK) {
4184 // Should only get a failure here for malformed requests or device-level
4185 // errors, so consider all errors fatal. Bad metadata failures should
4186 // come through notify.
4187 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4188 mNextRequests[numRequestProcessed].halRequest.frame_number,
4189 strerror(-res), res);
4190 cleanUpFailedRequests(/*sendRequestError*/ false);
4191 return false;
4192 }
4193 return true;
4194}
4195
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004196nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4197 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4198 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4199 find_camera_metadata_ro_entry(request,
4200 ANDROID_CONTROL_AE_MODE,
4201 &e);
4202 if (e.count == 0) return maxExpectedDuration;
4203
4204 switch (e.data.u8[0]) {
4205 case ANDROID_CONTROL_AE_MODE_OFF:
4206 find_camera_metadata_ro_entry(request,
4207 ANDROID_SENSOR_EXPOSURE_TIME,
4208 &e);
4209 if (e.count > 0) {
4210 maxExpectedDuration = e.data.i64[0];
4211 }
4212 find_camera_metadata_ro_entry(request,
4213 ANDROID_SENSOR_FRAME_DURATION,
4214 &e);
4215 if (e.count > 0) {
4216 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4217 }
4218 break;
4219 default:
4220 find_camera_metadata_ro_entry(request,
4221 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4222 &e);
4223 if (e.count > 1) {
4224 maxExpectedDuration = 1e9 / e.data.u8[0];
4225 }
4226 break;
4227 }
4228
4229 return maxExpectedDuration;
4230}
4231
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004232bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4233 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4234 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4235 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4236 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4237 return true;
4238 }
4239
4240 return false;
4241}
4242
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004243void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4244 // Update the latest request sent to HAL
4245 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4246 Mutex::Autolock al(mLatestRequestMutex);
4247
4248 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4249 mLatestRequest.acquire(cloned);
4250
4251 mLatestPhysicalRequest.clear();
4252 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4253 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4254 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4255 CameraMetadata(cloned));
4256 }
4257
4258 sp<Camera3Device> parent = mParent.promote();
4259 if (parent != NULL) {
4260 parent->monitorMetadata(TagMonitor::REQUEST,
4261 nextRequest.halRequest.frame_number,
4262 0, mLatestRequest, mLatestPhysicalRequest);
4263 }
4264 }
4265
4266 if (nextRequest.halRequest.settings != NULL) {
4267 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4268 nextRequest.halRequest.settings);
4269 }
4270
4271 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4272}
4273
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004274bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4275 ATRACE_CALL();
4276 bool updatesDetected = false;
4277
Emilian Peev4ec17882019-01-24 17:16:58 -08004278 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004279 for (auto tag : mSessionParamKeys) {
4280 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004281 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004282
4283 if (entry.count > 0) {
4284 bool isDifferent = false;
4285 if (lastEntry.count > 0) {
4286 // Have a last value, compare to see if changed
4287 if (lastEntry.type == entry.type &&
4288 lastEntry.count == entry.count) {
4289 // Same type and count, compare values
4290 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4291 size_t entryBytes = bytesPerValue * lastEntry.count;
4292 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4293 if (cmp != 0) {
4294 isDifferent = true;
4295 }
4296 } else {
4297 // Count or type has changed
4298 isDifferent = true;
4299 }
4300 } else {
4301 // No last entry, so always consider to be different
4302 isDifferent = true;
4303 }
4304
4305 if (isDifferent) {
4306 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004307 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4308 updatesDetected = true;
4309 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004310 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004311 }
4312 } else if (lastEntry.count > 0) {
4313 // Value has been removed
4314 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004315 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004316 updatesDetected = true;
4317 }
4318 }
4319
Emilian Peev4ec17882019-01-24 17:16:58 -08004320 bool reconfigureRequired;
4321 if (updatesDetected) {
4322 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4323 updatedParams);
4324 mLatestSessionParams = updatedParams;
4325 } else {
4326 reconfigureRequired = false;
4327 }
4328
4329 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004330}
4331
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004332bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004333 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004334 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004335 // Any function called from threadLoop() must not hold mInterfaceLock since
4336 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4337 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338
4339 // Handle paused state.
4340 if (waitIfPaused()) {
4341 return true;
4342 }
4343
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004344 // Wait for the next batch of requests.
4345 waitForNextRequestBatch();
4346 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004347 return true;
4348 }
4349
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004350 // Get the latest request ID, if any
4351 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004352 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004353 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004354 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004355 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004356 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004357 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4358 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004359 }
4360
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004361 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4362 // or a single request from streaming or burst. In either case the first element
4363 // should contain the latest camera settings that we need to check for any session
4364 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004365 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004366 res = OK;
4367
4368 //Input stream buffers are already acquired at this point so an input stream
4369 //will not be able to move to idle state unless we force it.
4370 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4371 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4372 if (res != OK) {
4373 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4374 cleanUpFailedRequests(/*sendRequestError*/ false);
4375 return false;
4376 }
4377 }
4378
4379 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004380 sp<Camera3Device> parent = mParent.promote();
4381 if (parent != nullptr) {
4382 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004383 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004384 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004385
4386 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4387 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4388 if (res != OK) {
4389 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4390 cleanUpFailedRequests(/*sendRequestError*/ false);
4391 return false;
4392 }
4393 }
4394 }
4395 }
4396
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004397 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004398 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004399 if (res == TIMED_OUT) {
4400 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004401 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004402 // Check if any stream is abandoned.
4403 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004404 return true;
4405 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004406 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004407 return false;
4408 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004409
Zhijun Hecc27e112013-10-03 16:12:43 -07004410 // Inform waitUntilRequestProcessed thread of a new request ID
4411 {
4412 Mutex::Autolock al(mLatestRequestMutex);
4413
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004414 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004415 mLatestRequestSignal.signal();
4416 }
4417
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004418 // Submit a batch of requests to HAL.
4419 // Use flush lock only when submitting multilple requests in a batch.
4420 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4421 // which may take a long time to finish so synchronizing flush() and
4422 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4423 // For now, only synchronize for high speed recording and we should figure something out for
4424 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004425 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004426
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004427 if (useFlushLock) {
4428 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004429 }
4430
Zhijun Hef0645c12016-08-02 00:58:11 -07004431 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004432 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004433
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004434 sp<Camera3Device> parent = mParent.promote();
4435 if (parent != nullptr) {
4436 parent->mRequestBufferSM.onSubmittingRequest();
4437 }
4438
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004439 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004440 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004441 submitRequestSuccess = sendRequestsBatch();
4442
Shuzhen Wang686f6442017-06-20 16:16:04 -07004443 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4444 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004445
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004446 if (useFlushLock) {
4447 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004449
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004450 // Unset as current request
4451 {
4452 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004453 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004454 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004455 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004456
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004457 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004458}
4459
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004460status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004461 ATRACE_CALL();
4462
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004463 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004464 for (size_t i = 0; i < mNextRequests.size(); i++) {
4465 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004466 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004467 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4468 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004469
4470 // Prepare a request to HAL
4471 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4472
4473 // Insert any queued triggers (before metadata is locked)
4474 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004475 if (res < 0) {
4476 SET_ERR("RequestThread: Unable to insert triggers "
4477 "(capture request %d, HAL device: %s (%d)",
4478 halRequest->frame_number, strerror(-res), res);
4479 return INVALID_OPERATION;
4480 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004481
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004482 int triggerCount = res;
4483 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4484 mPrevTriggers = triggerCount;
4485
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004486 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4487
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004488 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004489 bool newRequest =
4490 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004491 // Request settings are all the same within one batch, so only treat the first
4492 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004493 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004494 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004495 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004496 /**
4497 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004498 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004499 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004500 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004501 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004502 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004503 "(capture request %d, HAL device: %s (%d)",
4504 halRequest->frame_number, strerror(-res), res);
4505 return INVALID_OPERATION;
4506 }
4507
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004508 {
4509 // Correct metadata regions for distortion correction if enabled
4510 sp<Camera3Device> parent = mParent.promote();
4511 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004512 List<PhysicalCameraSettings>::iterator it;
4513 for (it = captureRequest->mSettingsList.begin();
4514 it != captureRequest->mSettingsList.end(); it++) {
4515 if (parent->mDistortionMappers.find(it->cameraId) ==
4516 parent->mDistortionMappers.end()) {
4517 continue;
4518 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004519
4520 if (!captureRequest->mDistortionCorrectionUpdated) {
4521 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4522 &(it->metadata));
4523 if (res != OK) {
4524 SET_ERR("RequestThread: Unable to correct capture requests "
4525 "for lens distortion for request %d: %s (%d)",
4526 halRequest->frame_number, strerror(-res), res);
4527 return INVALID_OPERATION;
4528 }
4529 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004530 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004531 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004532
4533 for (it = captureRequest->mSettingsList.begin();
4534 it != captureRequest->mSettingsList.end(); it++) {
4535 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4536 parent->mZoomRatioMappers.end()) {
4537 continue;
4538 }
4539
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004540 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004541 cameraIdsWithZoom.insert(it->cameraId);
4542 }
4543
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004544 if (!captureRequest->mZoomRatioUpdated) {
4545 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4546 &(it->metadata));
4547 if (res != OK) {
4548 SET_ERR("RequestThread: Unable to correct capture requests "
4549 "for zoom ratio for request %d: %s (%d)",
4550 halRequest->frame_number, strerror(-res), res);
4551 return INVALID_OPERATION;
4552 }
4553 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004554 }
4555 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004556 if (captureRequest->mRotateAndCropAuto &&
4557 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004558 for (it = captureRequest->mSettingsList.begin();
4559 it != captureRequest->mSettingsList.end(); it++) {
4560 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4561 if (mapper != parent->mRotateAndCropMappers.end()) {
4562 res = mapper->second.updateCaptureRequest(&(it->metadata));
4563 if (res != OK) {
4564 SET_ERR("RequestThread: Unable to correct capture requests "
4565 "for rotate-and-crop for request %d: %s (%d)",
4566 halRequest->frame_number, strerror(-res), res);
4567 return INVALID_OPERATION;
4568 }
4569 }
4570 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004571 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004572 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004573 }
4574 }
4575
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004576 /**
4577 * The request should be presorted so accesses in HAL
4578 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4579 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004580 captureRequest->mSettingsList.begin()->metadata.sort();
4581 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004582 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004583 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004584 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4585
4586 IF_ALOGV() {
4587 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4588 find_camera_metadata_ro_entry(
4589 halRequest->settings,
4590 ANDROID_CONTROL_AF_TRIGGER,
4591 &e
4592 );
4593 if (e.count > 0) {
4594 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4595 __FUNCTION__,
4596 halRequest->frame_number,
4597 e.data.u8[0]);
4598 }
4599 }
4600 } else {
4601 // leave request.settings NULL to indicate 'reuse latest given'
4602 ALOGVV("%s: Request settings are REUSED",
4603 __FUNCTION__);
4604 }
4605
Emilian Peevaebbe412018-01-15 13:53:24 +00004606 if (captureRequest->mSettingsList.size() > 1) {
4607 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4608 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004609 if (newRequest) {
4610 halRequest->physcam_settings =
4611 new const camera_metadata* [halRequest->num_physcam_settings];
4612 } else {
4613 halRequest->physcam_settings = nullptr;
4614 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004615 auto it = ++captureRequest->mSettingsList.begin();
4616 size_t i = 0;
4617 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4618 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004619 if (newRequest) {
4620 it->metadata.sort();
4621 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4622 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004623 }
4624 }
4625
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004626 uint32_t totalNumBuffers = 0;
4627
4628 // Fill in buffers
4629 if (captureRequest->mInputStream != NULL) {
4630 halRequest->input_buffer = &captureRequest->mInputBuffer;
4631 totalNumBuffers += 1;
4632 } else {
4633 halRequest->input_buffer = NULL;
4634 }
4635
Emilian Peevf4816702020-04-03 15:44:51 -07004636 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004637 captureRequest->mOutputStreams.size());
4638 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004639 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004640
4641 sp<Camera3Device> parent = mParent.promote();
4642 if (parent == NULL) {
4643 // Should not happen, and nowhere to send errors to, so just log it
4644 CLOGE("RequestThread: Parent is gone");
4645 return INVALID_OPERATION;
4646 }
4647 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4648
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004649 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004650 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004651 sp<Camera3OutputStreamInterface> outputStream =
4652 captureRequest->mOutputStreams.editItemAt(j);
4653 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004654
4655 // Prepare video buffers for high speed recording on the first video request.
4656 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4657 // Only try to prepare video stream on the first video request.
4658 mPrepareVideoStream = false;
4659
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004660 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4661 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004662 while (res == NOT_ENOUGH_DATA) {
4663 res = outputStream->prepareNextBuffer();
4664 }
4665 if (res != OK) {
4666 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4667 __FUNCTION__, strerror(-res), res);
4668 outputStream->cancelPrepare();
4669 }
4670 }
4671
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004672 std::vector<size_t> uniqueSurfaceIds;
4673 res = outputStream->getUniqueSurfaceIds(
4674 captureRequest->mOutputSurfaces[streamId],
4675 &uniqueSurfaceIds);
4676 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4677 if (res != OK && res != INVALID_OPERATION) {
4678 ALOGE("%s: failed to query stream %d unique surface IDs",
4679 __FUNCTION__, streamId);
4680 return res;
4681 }
4682 if (res == OK) {
4683 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4684 }
4685
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004686 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004687 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004688 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004689 return TIMED_OUT;
4690 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004691 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004692 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004693 buffer.stream = outputStream->asHalStream();
4694 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004695 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004696 buffer.acquire_fence = -1;
4697 buffer.release_fence = -1;
Emilian Peevf0348ae2021-01-13 13:39:45 -08004698 // Mark the output stream as unpreparable to block clients from calling
4699 // 'prepare' after this request reaches CameraHal and before the respective
4700 // buffers are requested.
4701 outputStream->markUnpreparable();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004702 } else {
4703 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4704 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004705 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004706 if (res != OK) {
4707 // Can't get output buffer from gralloc queue - this could be due to
4708 // abandoned queue or other consumer misbehavior, so not a fatal
4709 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004710 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004711 " %s (%d)", strerror(-res), res);
4712
4713 return TIMED_OUT;
4714 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004715 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004716
4717 {
4718 sp<Camera3Device> parent = mParent.promote();
4719 if (parent != nullptr) {
4720 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4721 for (const auto& settings : captureRequest->mSettingsList) {
4722 if ((streamCameraId.isEmpty() &&
4723 parent->getId() == settings.cameraId.c_str()) ||
4724 streamCameraId == settings.cameraId.c_str()) {
4725 outputStream->fireBufferRequestForFrameNumber(
4726 captureRequest->mResultExtras.frameNumber,
4727 settings.metadata);
4728 }
4729 }
4730 }
4731 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004732
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004733 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4734
4735 if (!physicalCameraId.isEmpty()) {
4736 // Physical stream isn't supported for input request.
4737 if (halRequest->input_buffer) {
4738 CLOGE("Physical stream is not supported for input request");
4739 return INVALID_OPERATION;
4740 }
4741 requestedPhysicalCameras.insert(physicalCameraId);
4742 }
4743 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004744 }
4745 totalNumBuffers += halRequest->num_output_buffers;
4746
4747 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004748 // If this request list is for constrained high speed recording (not
4749 // preview), and the current request is not the last one in the batch,
4750 // do not send callback to the app.
4751 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004752 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004753 hasCallback = false;
4754 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004755 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004756 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004757 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4758 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4759 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4760 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4761 isStillCapture = true;
4762 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4763 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004764
4765 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4766 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4767 isZslCapture = true;
4768 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004769 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 res = parent->registerInFlight(halRequest->frame_number,
4771 totalNumBuffers, captureRequest->mResultExtras,
4772 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004773 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004774 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004775 requestedPhysicalCameras, isStillCapture, isZslCapture,
4776 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004777 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004778 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4780 ", burstId = %" PRId32 ".",
4781 __FUNCTION__,
4782 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4783 captureRequest->mResultExtras.burstId);
4784 if (res != OK) {
4785 SET_ERR("RequestThread: Unable to register new in-flight request:"
4786 " %s (%d)", strerror(-res), res);
4787 return INVALID_OPERATION;
4788 }
4789 }
4790
4791 return OK;
4792}
4793
Igor Murashkin1e479c02013-09-06 16:55:14 -07004794CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004795 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004796 Mutex::Autolock al(mLatestRequestMutex);
4797
4798 ALOGV("RequestThread::%s", __FUNCTION__);
4799
4800 return mLatestRequest;
4801}
4802
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004803bool Camera3Device::RequestThread::isStreamPending(
4804 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004805 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004806 Mutex::Autolock l(mRequestLock);
4807
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004808 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004809 if (!nextRequest.submitted) {
4810 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4811 if (stream == s) return true;
4812 }
4813 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004814 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004815 }
4816
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004817 for (const auto& request : mRequestQueue) {
4818 for (const auto& s : request->mOutputStreams) {
4819 if (stream == s) return true;
4820 }
4821 if (stream == request->mInputStream) return true;
4822 }
4823
4824 for (const auto& request : mRepeatingRequests) {
4825 for (const auto& s : request->mOutputStreams) {
4826 if (stream == s) return true;
4827 }
4828 if (stream == request->mInputStream) return true;
4829 }
4830
4831 return false;
4832}
Jianing Weicb0652e2014-03-12 18:29:36 -07004833
Emilian Peev40ead602017-09-26 15:46:36 +01004834bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4835 ATRACE_CALL();
4836 Mutex::Autolock l(mRequestLock);
4837
4838 for (const auto& nextRequest : mNextRequests) {
4839 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4840 if (s.first == streamId) {
4841 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4842 if (it != s.second.end()) {
4843 return true;
4844 }
4845 }
4846 }
4847 }
4848
4849 for (const auto& request : mRequestQueue) {
4850 for (const auto& s : request->mOutputSurfaces) {
4851 if (s.first == streamId) {
4852 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4853 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004854 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004855 }
4856 }
4857 }
4858 }
4859
4860 for (const auto& request : mRepeatingRequests) {
4861 for (const auto& s : request->mOutputSurfaces) {
4862 if (s.first == streamId) {
4863 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4864 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004865 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004866 }
4867 }
4868 }
4869 }
4870
4871 return false;
4872}
4873
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004874void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4875 if (!mUseHalBufManager) {
4876 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4877 return;
4878 }
4879
4880 Mutex::Autolock pl(mPauseLock);
4881 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004882 mInterface->signalPipelineDrain(streamIds);
4883 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004884 }
4885 // If request thread is still busy, wait until paused then notify HAL
4886 mNotifyPipelineDrain = true;
4887 mStreamIdsToBeDrained = streamIds;
4888}
4889
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004890void Camera3Device::RequestThread::resetPipelineDrain() {
4891 Mutex::Autolock pl(mPauseLock);
4892 mNotifyPipelineDrain = false;
4893 mStreamIdsToBeDrained.clear();
4894}
4895
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004896void Camera3Device::RequestThread::clearPreviousRequest() {
4897 Mutex::Autolock l(mRequestLock);
4898 mPrevRequest.clear();
4899}
4900
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004901status_t Camera3Device::RequestThread::switchToOffline(
4902 const std::vector<int32_t>& streamsToKeep,
4903 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004904 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4905 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004906 Mutex::Autolock l(mRequestLock);
4907 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4908
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004909 // Wait until request thread is fully stopped
4910 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4911
4912 // We could also check for mRepeatingRequests.empty(), but the API interface
4913 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4914 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004915 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4916 while (!queueEmpty) {
4917 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4918 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004919 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004920 return res;
4921 } else if (res != OK) {
4922 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4923 __FUNCTION__, strerror(-res), res);
4924 return res;
4925 }
4926 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4927 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004928
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004929 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004930 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004931}
4932
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004933status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4934 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4935 ATRACE_CALL();
4936 Mutex::Autolock l(mTriggerMutex);
4937 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4938 return BAD_VALUE;
4939 }
4940 mRotateAndCropOverride = rotateAndCropValue;
4941 return OK;
4942}
4943
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004944nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004945 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004946 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004947 return mExpectedInflightDuration > kMinInflightDuration ?
4948 mExpectedInflightDuration : kMinInflightDuration;
4949}
4950
Emilian Peevaebbe412018-01-15 13:53:24 +00004951void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004952 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004953 if ((request == nullptr) || (halRequest == nullptr)) {
4954 ALOGE("%s: Invalid request!", __FUNCTION__);
4955 return;
4956 }
4957
4958 if (halRequest->num_physcam_settings > 0) {
4959 if (halRequest->physcam_id != nullptr) {
4960 delete [] halRequest->physcam_id;
4961 halRequest->physcam_id = nullptr;
4962 }
4963 if (halRequest->physcam_settings != nullptr) {
4964 auto it = ++(request->mSettingsList.begin());
4965 size_t i = 0;
4966 for (; it != request->mSettingsList.end(); it++, i++) {
4967 it->metadata.unlock(halRequest->physcam_settings[i]);
4968 }
4969 delete [] halRequest->physcam_settings;
4970 halRequest->physcam_settings = nullptr;
4971 }
4972 }
4973}
4974
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004975void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4976 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004977 return;
4978 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004979
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004980 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004981 // Skip the ones that have been submitted successfully.
4982 if (nextRequest.submitted) {
4983 continue;
4984 }
4985
4986 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004987 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4988 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004989
4990 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004991 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004992 }
4993
Emilian Peevaebbe412018-01-15 13:53:24 +00004994 cleanupPhysicalSettings(captureRequest, halRequest);
4995
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004996 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004997 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004998 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4999 }
5000
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005001 // No output buffer can be returned when using HAL buffer manager
5002 if (!mUseHalBufManager) {
5003 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5004 //Buffers that failed processing could still have
5005 //valid acquire fence.
5006 int acquireFence = (*outputBuffers)[i].acquire_fence;
5007 if (0 <= acquireFence) {
5008 close(acquireFence);
5009 outputBuffers->editItemAt(i).acquire_fence = -1;
5010 }
Emilian Peevf4816702020-04-03 15:44:51 -07005011 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005012 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5013 /*timestampIncreasing*/true, std::vector<size_t> (),
5014 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005015 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005016 }
5017
5018 if (sendRequestError) {
5019 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005020 sp<NotificationListener> listener = mListener.promote();
5021 if (listener != NULL) {
5022 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005023 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005024 captureRequest->mResultExtras);
5025 }
5026 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005027
5028 // Remove yet-to-be submitted inflight request from inflightMap
5029 {
5030 sp<Camera3Device> parent = mParent.promote();
5031 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005032 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005033 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5034 if (idx >= 0) {
5035 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5036 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5037 parent->removeInFlightMapEntryLocked(idx);
5038 }
5039 }
5040 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005041 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005042
5043 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005044 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005045}
5046
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005047void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005048 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005049 // Optimized a bit for the simple steady-state case (single repeating
5050 // request), to avoid putting that request in the queue temporarily.
5051 Mutex::Autolock l(mRequestLock);
5052
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005053 assert(mNextRequests.empty());
5054
5055 NextRequest nextRequest;
5056 nextRequest.captureRequest = waitForNextRequestLocked();
5057 if (nextRequest.captureRequest == nullptr) {
5058 return;
5059 }
5060
Emilian Peevf4816702020-04-03 15:44:51 -07005061 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005062 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005063 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005064
5065 // Wait for additional requests
5066 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5067
5068 for (size_t i = 1; i < batchSize; i++) {
5069 NextRequest additionalRequest;
5070 additionalRequest.captureRequest = waitForNextRequestLocked();
5071 if (additionalRequest.captureRequest == nullptr) {
5072 break;
5073 }
5074
Emilian Peevf4816702020-04-03 15:44:51 -07005075 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005076 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005077 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078 }
5079
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005080 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005081 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005082 mNextRequests.size(), batchSize);
5083 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005084 }
5085
5086 return;
5087}
5088
5089sp<Camera3Device::CaptureRequest>
5090 Camera3Device::RequestThread::waitForNextRequestLocked() {
5091 status_t res;
5092 sp<CaptureRequest> nextRequest;
5093
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005094 while (mRequestQueue.empty()) {
5095 if (!mRepeatingRequests.empty()) {
5096 // Always atomically enqueue all requests in a repeating request
5097 // list. Guarantees a complete in-sequence set of captures to
5098 // application.
5099 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005100 if (mFirstRepeating) {
5101 mFirstRepeating = false;
5102 } else {
5103 for (auto& request : requests) {
5104 // For repeating requests, override timestamp request using
5105 // the time a request is inserted into the request queue,
5106 // because the original repeating request will have an old
5107 // fixed timestamp.
5108 request->mRequestTimeNs = systemTime();
5109 }
5110 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005111 RequestList::const_iterator firstRequest =
5112 requests.begin();
5113 nextRequest = *firstRequest;
5114 mRequestQueue.insert(mRequestQueue.end(),
5115 ++firstRequest,
5116 requests.end());
5117 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005118
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005119 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005120
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005121 break;
5122 }
5123
5124 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005126 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5127 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005128 Mutex::Autolock pl(mPauseLock);
5129 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005130 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005131 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005132 if (mNotifyPipelineDrain) {
5133 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5134 mNotifyPipelineDrain = false;
5135 mStreamIdsToBeDrained.clear();
5136 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005137 // Let the tracker know
5138 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5139 if (statusTracker != 0) {
5140 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5141 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005142 sp<Camera3Device> parent = mParent.promote();
5143 if (parent != nullptr) {
5144 parent->mRequestBufferSM.onRequestThreadPaused();
5145 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005146 }
5147 // Stop waiting for now and let thread management happen
5148 return NULL;
5149 }
5150 }
5151
5152 if (nextRequest == NULL) {
5153 // Don't have a repeating request already in hand, so queue
5154 // must have an entry now.
5155 RequestList::iterator firstRequest =
5156 mRequestQueue.begin();
5157 nextRequest = *firstRequest;
5158 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005159 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5160 sp<NotificationListener> listener = mListener.promote();
5161 if (listener != NULL) {
5162 listener->notifyRequestQueueEmpty();
5163 }
5164 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005165 }
5166
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005167 // In case we've been unpaused by setPaused clearing mDoPause, need to
5168 // update internal pause state (capture/setRepeatingRequest unpause
5169 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005170 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005171 if (mPaused) {
5172 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5173 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5174 if (statusTracker != 0) {
5175 statusTracker->markComponentActive(mStatusId);
5176 }
5177 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005178 mPaused = false;
5179
5180 // Check if we've reconfigured since last time, and reset the preview
5181 // request if so. Can't use 'NULL request == repeat' across configure calls.
5182 if (mReconfigured) {
5183 mPrevRequest.clear();
5184 mReconfigured = false;
5185 }
5186
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005187 if (nextRequest != NULL) {
5188 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005189 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5190 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005191
5192 // Since RequestThread::clear() removes buffers from the input stream,
5193 // get the right buffer here before unlocking mRequestLock
5194 if (nextRequest->mInputStream != NULL) {
5195 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5196 if (res != OK) {
5197 // Can't get input buffer from gralloc queue - this could be due to
5198 // disconnected queue or other producer misbehavior, so not a fatal
5199 // error
5200 ALOGE("%s: Can't get input buffer, skipping request:"
5201 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005202
5203 sp<NotificationListener> listener = mListener.promote();
5204 if (listener != NULL) {
5205 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005206 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005207 nextRequest->mResultExtras);
5208 }
5209 return NULL;
5210 }
5211 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005212 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005213
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005214 return nextRequest;
5215}
5216
5217bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005218 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005219 status_t res;
5220 Mutex::Autolock l(mPauseLock);
5221 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005222 if (mPaused == false) {
5223 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005224 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005225 if (mNotifyPipelineDrain) {
5226 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5227 mNotifyPipelineDrain = false;
5228 mStreamIdsToBeDrained.clear();
5229 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005230 // Let the tracker know
5231 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5232 if (statusTracker != 0) {
5233 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5234 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005235 sp<Camera3Device> parent = mParent.promote();
5236 if (parent != nullptr) {
5237 parent->mRequestBufferSM.onRequestThreadPaused();
5238 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005239 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005240
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005241 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005242 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005243 return true;
5244 }
5245 }
5246 // We don't set mPaused to false here, because waitForNextRequest needs
5247 // to further manage the paused state in case of starvation.
5248 return false;
5249}
5250
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005251void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005252 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005253 // With work to do, mark thread as unpaused.
5254 // If paused by request (setPaused), don't resume, to avoid
5255 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005256 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005257 Mutex::Autolock p(mPauseLock);
5258 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005259 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5260 if (mPaused) {
5261 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5262 if (statusTracker != 0) {
5263 statusTracker->markComponentActive(mStatusId);
5264 }
5265 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005266 mPaused = false;
5267 }
5268}
5269
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005270void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5271 sp<Camera3Device> parent = mParent.promote();
5272 if (parent != NULL) {
5273 va_list args;
5274 va_start(args, fmt);
5275
5276 parent->setErrorStateV(fmt, args);
5277
5278 va_end(args);
5279 }
5280}
5281
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005282status_t Camera3Device::RequestThread::insertTriggers(
5283 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005284 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005285 Mutex::Autolock al(mTriggerMutex);
5286
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005287 sp<Camera3Device> parent = mParent.promote();
5288 if (parent == NULL) {
5289 CLOGE("RequestThread: Parent is gone");
5290 return DEAD_OBJECT;
5291 }
5292
Emilian Peevaebbe412018-01-15 13:53:24 +00005293 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005294 size_t count = mTriggerMap.size();
5295
5296 for (size_t i = 0; i < count; ++i) {
5297 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005298 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005299
5300 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5301 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5302 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005303 if (isAeTrigger) {
5304 request->mResultExtras.precaptureTriggerId = triggerId;
5305 mCurrentPreCaptureTriggerId = triggerId;
5306 } else {
5307 request->mResultExtras.afTriggerId = triggerId;
5308 mCurrentAfTriggerId = triggerId;
5309 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005310 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005311 }
5312
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005313 camera_metadata_entry entry = metadata.find(tag);
5314
5315 if (entry.count > 0) {
5316 /**
5317 * Already has an entry for this trigger in the request.
5318 * Rewrite it with our requested trigger value.
5319 */
5320 RequestTrigger oldTrigger = trigger;
5321
5322 oldTrigger.entryValue = entry.data.u8[0];
5323
5324 mTriggerReplacedMap.add(tag, oldTrigger);
5325 } else {
5326 /**
5327 * More typical, no trigger entry, so we just add it
5328 */
5329 mTriggerRemovedMap.add(tag, trigger);
5330 }
5331
5332 status_t res;
5333
5334 switch (trigger.getTagType()) {
5335 case TYPE_BYTE: {
5336 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5337 res = metadata.update(tag,
5338 &entryValue,
5339 /*count*/1);
5340 break;
5341 }
5342 case TYPE_INT32:
5343 res = metadata.update(tag,
5344 &trigger.entryValue,
5345 /*count*/1);
5346 break;
5347 default:
5348 ALOGE("%s: Type not supported: 0x%x",
5349 __FUNCTION__,
5350 trigger.getTagType());
5351 return INVALID_OPERATION;
5352 }
5353
5354 if (res != OK) {
5355 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5356 ", value %d", __FUNCTION__, trigger.getTagName(),
5357 trigger.entryValue);
5358 return res;
5359 }
5360
5361 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5362 trigger.getTagName(),
5363 trigger.entryValue);
5364 }
5365
5366 mTriggerMap.clear();
5367
5368 return count;
5369}
5370
5371status_t Camera3Device::RequestThread::removeTriggers(
5372 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005373 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005374 Mutex::Autolock al(mTriggerMutex);
5375
Emilian Peevaebbe412018-01-15 13:53:24 +00005376 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005377
5378 /**
5379 * Replace all old entries with their old values.
5380 */
5381 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5382 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5383
5384 status_t res;
5385
5386 uint32_t tag = trigger.metadataTag;
5387 switch (trigger.getTagType()) {
5388 case TYPE_BYTE: {
5389 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5390 res = metadata.update(tag,
5391 &entryValue,
5392 /*count*/1);
5393 break;
5394 }
5395 case TYPE_INT32:
5396 res = metadata.update(tag,
5397 &trigger.entryValue,
5398 /*count*/1);
5399 break;
5400 default:
5401 ALOGE("%s: Type not supported: 0x%x",
5402 __FUNCTION__,
5403 trigger.getTagType());
5404 return INVALID_OPERATION;
5405 }
5406
5407 if (res != OK) {
5408 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5409 ", trigger value %d", __FUNCTION__,
5410 trigger.getTagName(), trigger.entryValue);
5411 return res;
5412 }
5413 }
5414 mTriggerReplacedMap.clear();
5415
5416 /**
5417 * Remove all new entries.
5418 */
5419 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5420 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5421 status_t res = metadata.erase(trigger.metadataTag);
5422
5423 if (res != OK) {
5424 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5425 ", trigger value %d", __FUNCTION__,
5426 trigger.getTagName(), trigger.entryValue);
5427 return res;
5428 }
5429 }
5430 mTriggerRemovedMap.clear();
5431
5432 return OK;
5433}
5434
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005435status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005436 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005437 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005438 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005439 status_t res;
5440
Emilian Peevaebbe412018-01-15 13:53:24 +00005441 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005442
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005443 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005444 // exists
5445 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5446 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5447 if (afTrigger.count > 0 &&
5448 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5449 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005450 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005451 if (res != OK) return res;
5452 }
5453
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005454 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005455 // if none already exists
5456 camera_metadata_entry pcTrigger =
5457 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5458 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5459 if (pcTrigger.count > 0 &&
5460 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5461 pcId.count == 0) {
5462 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005463 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005464 if (res != OK) return res;
5465 }
5466
5467 return OK;
5468}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005469
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005470bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5471 const sp<CaptureRequest> &request) {
5472 ATRACE_CALL();
5473
5474 if (request->mRotateAndCropAuto) {
5475 Mutex::Autolock l(mTriggerMutex);
5476 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5477
5478 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5479 if (rotateAndCropEntry.count > 0) {
5480 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5481 return false;
5482 } else {
5483 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5484 return true;
5485 }
5486 } else {
5487 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5488 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5489 &rotateAndCrop_u8, 1);
5490 return true;
5491 }
5492 }
5493 return false;
5494}
5495
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005496/**
5497 * PreparerThread inner class methods
5498 */
5499
5500Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005501 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005502 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005503}
5504
5505Camera3Device::PreparerThread::~PreparerThread() {
5506 Thread::requestExitAndWait();
5507 if (mCurrentStream != nullptr) {
5508 mCurrentStream->cancelPrepare();
5509 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5510 mCurrentStream.clear();
5511 }
5512 clear();
5513}
5514
Ruben Brunkc78ac262015-08-13 17:58:46 -07005515status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005516 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005517 status_t res;
5518
5519 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005520 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005521
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005522 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005523 if (res == OK) {
5524 // No preparation needed, fire listener right off
5525 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005526 if (listener != NULL) {
5527 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005528 }
5529 return OK;
5530 } else if (res != NOT_ENOUGH_DATA) {
5531 return res;
5532 }
5533
5534 // Need to prepare, start up thread if necessary
5535 if (!mActive) {
5536 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5537 // isn't running
5538 Thread::requestExitAndWait();
5539 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5540 if (res != OK) {
5541 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005542 if (listener != NULL) {
5543 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005544 }
5545 return res;
5546 }
5547 mCancelNow = false;
5548 mActive = true;
5549 ALOGV("%s: Preparer stream started", __FUNCTION__);
5550 }
5551
5552 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005553 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005554 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5555
5556 return OK;
5557}
5558
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005559void Camera3Device::PreparerThread::pause() {
5560 ATRACE_CALL();
5561
5562 Mutex::Autolock l(mLock);
5563
5564 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5565 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5566 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5567 int currentMaxCount = mCurrentMaxCount;
5568 mPendingStreams.clear();
5569 mCancelNow = true;
5570 while (mActive) {
5571 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5572 if (res == TIMED_OUT) {
5573 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5574 return;
5575 } else if (res != OK) {
5576 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5577 return;
5578 }
5579 }
5580
5581 //Check whether the prepare thread was able to complete the current
5582 //stream. In case work is still pending emplace it along with the rest
5583 //of the streams in the pending list.
5584 if (currentStream != nullptr) {
5585 if (!mCurrentPrepareComplete) {
5586 pendingStreams.emplace(currentMaxCount, currentStream);
5587 }
5588 }
5589
5590 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5591 for (const auto& it : mPendingStreams) {
5592 it.second->cancelPrepare();
5593 }
5594}
5595
5596status_t Camera3Device::PreparerThread::resume() {
5597 ATRACE_CALL();
5598 status_t res;
5599
5600 Mutex::Autolock l(mLock);
5601 sp<NotificationListener> listener = mListener.promote();
5602
5603 if (mActive) {
5604 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5605 return NO_INIT;
5606 }
5607
5608 auto it = mPendingStreams.begin();
5609 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005610 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005611 if (res == OK) {
5612 if (listener != NULL) {
5613 listener->notifyPrepared(it->second->getId());
5614 }
5615 it = mPendingStreams.erase(it);
5616 } else if (res != NOT_ENOUGH_DATA) {
5617 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5618 res, strerror(-res));
5619 it = mPendingStreams.erase(it);
5620 } else {
5621 it++;
5622 }
5623 }
5624
5625 if (mPendingStreams.empty()) {
5626 return OK;
5627 }
5628
5629 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5630 if (res != OK) {
5631 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5632 __FUNCTION__, res, strerror(-res));
5633 return res;
5634 }
5635 mCancelNow = false;
5636 mActive = true;
5637 ALOGV("%s: Preparer stream started", __FUNCTION__);
5638
5639 return OK;
5640}
5641
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005642status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005643 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005644 Mutex::Autolock l(mLock);
5645
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005646 for (const auto& it : mPendingStreams) {
5647 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005648 }
5649 mPendingStreams.clear();
5650 mCancelNow = true;
5651
5652 return OK;
5653}
5654
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005655void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005656 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005657 Mutex::Autolock l(mLock);
5658 mListener = listener;
5659}
5660
5661bool Camera3Device::PreparerThread::threadLoop() {
5662 status_t res;
5663 {
5664 Mutex::Autolock l(mLock);
5665 if (mCurrentStream == nullptr) {
5666 // End thread if done with work
5667 if (mPendingStreams.empty()) {
5668 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5669 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5670 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5671 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005672 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005673 return false;
5674 }
5675
5676 // Get next stream to prepare
5677 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005678 mCurrentStream = it->second;
5679 mCurrentMaxCount = it->first;
5680 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005681 mPendingStreams.erase(it);
5682 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5683 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5684 } else if (mCancelNow) {
5685 mCurrentStream->cancelPrepare();
5686 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5687 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5688 mCurrentStream.clear();
5689 mCancelNow = false;
5690 return true;
5691 }
5692 }
5693
5694 res = mCurrentStream->prepareNextBuffer();
5695 if (res == NOT_ENOUGH_DATA) return true;
5696 if (res != OK) {
5697 // Something bad happened; try to recover by cancelling prepare and
5698 // signalling listener anyway
5699 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5700 mCurrentStream->getId(), res, strerror(-res));
5701 mCurrentStream->cancelPrepare();
5702 }
5703
5704 // This stream has finished, notify listener
5705 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005706 sp<NotificationListener> listener = mListener.promote();
5707 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005708 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5709 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005710 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005711 }
5712
5713 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5714 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005715 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005716
5717 return true;
5718}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005719
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005720status_t Camera3Device::RequestBufferStateMachine::initialize(
5721 sp<camera3::StatusTracker> statusTracker) {
5722 if (statusTracker == nullptr) {
5723 ALOGE("%s: statusTracker is null", __FUNCTION__);
5724 return BAD_VALUE;
5725 }
5726
5727 std::lock_guard<std::mutex> lock(mLock);
5728 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005729 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005730 return OK;
5731}
5732
5733bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5734 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005735 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005736 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005737 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005738 return true;
5739 }
5740 return false;
5741}
5742
5743void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5744 std::lock_guard<std::mutex> lock(mLock);
5745 if (!mRequestBufferOngoing) {
5746 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5747 return;
5748 }
5749 mRequestBufferOngoing = false;
5750 if (mStatus == RB_STATUS_PENDING_STOP) {
5751 checkSwitchToStopLocked();
5752 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005753 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005754}
5755
5756void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5757 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005758 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005759 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005760 return;
5761}
5762
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005763void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005764 std::lock_guard<std::mutex> lock(mLock);
5765 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005766 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5767 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005768 mInflightMapEmpty = false;
5769 if (mStatus == RB_STATUS_STOPPED) {
5770 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005771 }
5772 return;
5773}
5774
5775void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5776 std::lock_guard<std::mutex> lock(mLock);
5777 mRequestThreadPaused = true;
5778 if (mStatus == RB_STATUS_PENDING_STOP) {
5779 checkSwitchToStopLocked();
5780 }
5781 return;
5782}
5783
5784void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5785 std::lock_guard<std::mutex> lock(mLock);
5786 mInflightMapEmpty = true;
5787 if (mStatus == RB_STATUS_PENDING_STOP) {
5788 checkSwitchToStopLocked();
5789 }
5790 return;
5791}
5792
5793void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5794 std::lock_guard<std::mutex> lock(mLock);
5795 if (!checkSwitchToStopLocked()) {
5796 mStatus = RB_STATUS_PENDING_STOP;
5797 }
5798 return;
5799}
5800
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005801bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5802 std::lock_guard<std::mutex> lock(mLock);
5803 if (mRequestBufferOngoing) {
5804 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5805 __FUNCTION__);
5806 return false;
5807 }
5808 mSwitchedToOffline = true;
5809 mInflightMapEmpty = true;
5810 mRequestThreadPaused = true;
5811 mStatus = RB_STATUS_STOPPED;
5812 return true;
5813}
5814
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005815void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5816 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5817 if (statusTracker != nullptr) {
5818 if (active) {
5819 statusTracker->markComponentActive(mRequestBufferStatusId);
5820 } else {
5821 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5822 }
5823 }
5824}
5825
5826bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5827 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5828 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005829 return true;
5830 }
5831 return false;
5832}
5833
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005834bool Camera3Device::startRequestBuffer() {
5835 return mRequestBufferSM.startRequestBuffer();
5836}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005837
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005838void Camera3Device::endRequestBuffer() {
5839 mRequestBufferSM.endRequestBuffer();
5840}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005841
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005842nsecs_t Camera3Device::getWaitDuration() {
5843 return kBaseGetBufferWait + getExpectedInFlightDuration();
5844}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005845
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005846void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5847 mInterface->getInflightBufferKeys(out);
5848}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005849
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005850void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5851 mInterface->getInflightRequestBufferKeys(out);
5852}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005853
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005854std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5855 std::vector<sp<Camera3StreamInterface>> ret;
5856 bool hasInputStream = mInputStream != nullptr;
5857 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5858 if (hasInputStream) {
5859 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005860 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005861 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5862 ret.push_back(mOutputStreams[i]);
5863 }
5864 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5865 ret.push_back(mDeletedStreams[i]);
5866 }
5867 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005868}
5869
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005870status_t Camera3Device::switchToOffline(
5871 const std::vector<int32_t>& streamsToKeep,
5872 /*out*/ sp<CameraOfflineSessionBase>* session) {
5873 ATRACE_CALL();
5874 if (session == nullptr) {
5875 ALOGE("%s: session must not be null", __FUNCTION__);
5876 return BAD_VALUE;
5877 }
5878
5879 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005880
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005881 bool hasInputStream = mInputStream != nullptr;
5882 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5883 bool inputStreamSupportsOffline = hasInputStream ?
5884 mInputStream->getOfflineProcessingSupport() : false;
5885 auto outputStreamIds = mOutputStreams.getStreamIds();
5886 auto streamIds = outputStreamIds;
5887 if (hasInputStream) {
5888 streamIds.push_back(mInputStream->getId());
5889 }
5890
5891 // Check all streams in streamsToKeep supports offline mode
5892 for (auto id : streamsToKeep) {
5893 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5894 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5895 return BAD_VALUE;
5896 } else if (id == inputStreamId) {
5897 if (!inputStreamSupportsOffline) {
5898 ALOGE("%s: input stream %d cannot be switched to offline",
5899 __FUNCTION__, id);
5900 return BAD_VALUE;
5901 }
5902 } else {
5903 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5904 if (!stream->getOfflineProcessingSupport()) {
5905 ALOGE("%s: output stream %d cannot be switched to offline",
5906 __FUNCTION__, id);
5907 return BAD_VALUE;
5908 }
5909 }
5910 }
5911
5912 // TODO: block surface sharing and surface group streams until we can support them
5913
5914 // Stop repeating request, wait until all remaining requests are submitted, then call into
5915 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005916 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5917 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005918 camera3::BufferRecords bufferRecords;
5919 status_t ret = mRequestThread->switchToOffline(
5920 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005921
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005922 if (ret != OK) {
5923 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5924 return ret;
5925 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005926
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005927 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5928 if (!succ) {
5929 SET_ERR("HAL must not be calling requestStreamBuffers call");
5930 // TODO: block ALL callbacks from HAL till app configured new streams?
5931 return UNKNOWN_ERROR;
5932 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005933
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005934 // Verify offlineSessionInfo
5935 std::vector<int32_t> offlineStreamIds;
5936 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5937 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5938 // verify stream IDs
5939 int32_t id = offlineStream.id;
5940 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5941 SET_ERR("stream ID %d not found!", id);
5942 return UNKNOWN_ERROR;
5943 }
5944
5945 // When not using HAL buf manager, only allow streams requested by app to be preserved
5946 if (!mUseHalBufManager) {
5947 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5948 SET_ERR("stream ID %d must not be switched to offline!", id);
5949 return UNKNOWN_ERROR;
5950 }
5951 }
5952
5953 offlineStreamIds.push_back(id);
5954 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5955 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5956 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5957 // Verify number of outstanding buffers
5958 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5959 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5960 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5961 return UNKNOWN_ERROR;
5962 }
5963 }
5964
5965 // Verify all streams to be deleted don't have any outstanding buffers
5966 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5967 inputStreamId) == offlineStreamIds.end()) {
5968 if (mInputStream->hasOutstandingBuffers()) {
5969 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5970 inputStreamId, mInputStream->getOutstandingBuffersCount());
5971 return UNKNOWN_ERROR;
5972 }
5973 }
5974
5975 for (const auto& outStreamId : outputStreamIds) {
5976 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5977 outStreamId) == offlineStreamIds.end()) {
5978 auto outStream = mOutputStreams.get(outStreamId);
5979 if (outStream->hasOutstandingBuffers()) {
5980 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5981 outStreamId, outStream->getOutstandingBuffersCount());
5982 return UNKNOWN_ERROR;
5983 }
5984 }
5985 }
5986
5987 InFlightRequestMap offlineReqs;
5988 // Verify inflight requests and their pending buffers
5989 {
5990 std::lock_guard<std::mutex> l(mInFlightLock);
5991 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5992 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5993 if (idx == NAME_NOT_FOUND) {
5994 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5995 return UNKNOWN_ERROR;
5996 }
5997
5998 const auto& inflightReq = mInFlightMap.valueAt(idx);
5999 // TODO: check specific stream IDs
6000 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
6001 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
6002 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
6003 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
6004 return UNKNOWN_ERROR;
6005 }
6006 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6007 }
6008 }
6009
6010 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006011 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006012 camera3::StreamSet offlineStreamSet;
6013 sp<camera3::Camera3Stream> inputStream;
6014 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6015 int32_t id = offlineStream.id;
6016 if (mInputStream != nullptr && id == mInputStream->getId()) {
6017 inputStream = mInputStream;
6018 } else {
6019 offlineStreamSet.add(id, mOutputStreams.get(id));
6020 }
6021 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006022
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006023 // TODO: check if we need to lock before copying states
6024 // though technically no other thread should be talking to Camera3Device at this point
6025 Camera3OfflineStates offlineStates(
6026 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006027 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6028 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6029 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6030 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6031 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6032 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6033 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006034
6035 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6036 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6037
6038 // Delete all streams that has been transferred to offline session
6039 Mutex::Autolock l(mLock);
6040 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6041 int32_t id = offlineStream.id;
6042 if (mInputStream != nullptr && id == mInputStream->getId()) {
6043 mInputStream.clear();
6044 } else {
6045 mOutputStreams.remove(id);
6046 }
6047 }
6048
6049 // disconnect all other streams and switch to UNCONFIGURED state
6050 if (mInputStream != nullptr) {
6051 ret = mInputStream->disconnect();
6052 if (ret != OK) {
6053 SET_ERR_L("disconnect input stream failed!");
6054 return UNKNOWN_ERROR;
6055 }
6056 }
6057
6058 for (auto streamId : mOutputStreams.getStreamIds()) {
6059 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6060 ret = stream->disconnect();
6061 if (ret != OK) {
6062 SET_ERR_L("disconnect output stream %d failed!", streamId);
6063 return UNKNOWN_ERROR;
6064 }
6065 }
6066
6067 mInputStream.clear();
6068 mOutputStreams.clear();
6069 mNeedConfig = true;
6070 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6071 mOperatingMode = NO_MODE;
6072 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006073 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006074
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006075 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006076 // TO be done by CameraDeviceClient/Camera3OfflineSession
6077 // register the offline client to camera service
6078 // Setup result passthing threads etc
6079 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6080 // TODO: check how many onIdle callback will be sent
6081 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006082}
6083
Emilian Peevcc0b7952020-01-07 13:54:47 -08006084void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6085 ATRACE_CALL();
6086
6087 if (offlineStreamIds == nullptr) {
6088 return;
6089 }
6090
6091 Mutex::Autolock il(mInterfaceLock);
6092
6093 auto streamIds = mOutputStreams.getStreamIds();
6094 bool hasInputStream = mInputStream != nullptr;
6095 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6096 offlineStreamIds->push_back(mInputStream->getId());
6097 }
6098
6099 for (const auto & streamId : streamIds) {
6100 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6101 // Streams that use the camera buffer manager are currently not supported in
6102 // offline mode
6103 if (stream->getOfflineProcessingSupport() &&
6104 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6105 offlineStreamIds->push_back(streamId);
6106 }
6107 }
6108}
6109
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006110status_t Camera3Device::setRotateAndCropAutoBehavior(
6111 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6112 ATRACE_CALL();
6113 Mutex::Autolock il(mInterfaceLock);
6114 Mutex::Autolock l(mLock);
6115 if (mRequestThread == nullptr) {
6116 return INVALID_OPERATION;
6117 }
6118 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6119}
6120
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006121}; // namespace android