blob: e80404b9770b5a9f8f4445979f1d4516178de3c7 [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();
916 break;
917 }
918 }
919 }
920
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 return OK;
922}
923
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800924status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000929 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800931 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932}
933
Emilian Peevaebbe412018-01-15 13:53:24 +0000934void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 std::list<const SurfaceMap>& surfaceMaps,
936 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 PhysicalCameraSettingsList requestList;
938 requestList.push_back({std::string(getId().string()), request});
939 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940
941 SurfaceMap surfaceMap;
942 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
943 // With no surface list passed in, stream and surface will have 1-to-1
944 // mapping. So the surface index is 0 for each stream in the surfaceMap.
945 for (size_t i = 0; i < streams.count; i++) {
946 surfaceMap[streams.data.i32[i]].push_back(0);
947 }
948 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800949}
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000952 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953 const std::list<const SurfaceMap> &surfaceMaps,
954 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700955 /*out*/
956 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700957 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700958 nsecs_t requestTimeNs = systemTime();
959
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 Mutex::Autolock il(mInterfaceLock);
961 Mutex::Autolock l(mLock);
962
963 status_t res = checkStatusOkToCaptureLocked();
964 if (res != OK) {
965 // error logged by previous call
966 return res;
967 }
968
969 RequestList requestList;
970
Shuzhen Wang0129d522016-10-30 22:43:41 -0700971 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700972 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700973 if (res != OK) {
974 // error logged by previous call
975 return res;
976 }
977
978 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700979 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700981 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700982 }
983
984 if (res == OK) {
985 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
986 if (res != OK) {
987 SET_ERR_L("Can't transition to active in %f seconds!",
988 kActiveTimeout/1e9);
989 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 } else {
993 CLOGE("Cannot queue request. Impossible.");
994 return BAD_VALUE;
995 }
996
997 return res;
998}
999
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001000hardware::Return<void> Camera3Device::requestStreamBuffers(
1001 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1002 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001003 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001005 *this, *mInterface, *this};
1006 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001007 return hardware::Void();
1008}
1009
1010hardware::Return<void> Camera3Device::returnStreamBuffers(
1011 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001012 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001013 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001014 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001015 return hardware::Void();
1016}
1017
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001018hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001019 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001020 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001021 // Ideally we should grab mLock, but that can lead to deadlock, and
1022 // it's not super important to get up to date value of mStatus for this
1023 // warning print, hence skipping the lock here
1024 if (mStatus == STATUS_ERROR) {
1025 // Per API contract, HAL should act as closed after device error
1026 // But mStatus can be set to error by framework as well, so just log
1027 // a warning here.
1028 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001029 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001030
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 sp<NotificationListener> listener;
1032 {
1033 std::lock_guard<std::mutex> l(mOutputLock);
1034 listener = mListener.promote();
1035 }
1036
Yifan Honga640c5a2017-04-12 16:30:31 -07001037 if (mProcessCaptureResultLock.tryLock() != OK) {
1038 // This should never happen; it indicates a wrong client implementation
1039 // that doesn't follow the contract. But, we can be tolerant here.
1040 ALOGE("%s: callback overlapped! waiting 1s...",
1041 __FUNCTION__);
1042 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1043 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1044 __FUNCTION__);
1045 // really don't know what to do, so bail out.
1046 return hardware::Void();
1047 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 CaptureOutputStates states {
1050 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001051 mInFlightLock, mLastCompletedRegularFrameNumber,
1052 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1053 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001054 mNextShutterFrameNumber,
1055 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1056 mNextResultFrameNumber,
1057 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1058 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1059 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001060 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001061 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1062 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001063 };
1064
Yifan Honga640c5a2017-04-12 16:30:31 -07001065 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 }
1068 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return hardware::Void();
1070}
1071
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001072// Only one processCaptureResult should be called at a time, so
1073// the locks won't block. The locks are present here simply to enforce this.
1074hardware::Return<void> Camera3Device::processCaptureResult(
1075 const hardware::hidl_vec<
1076 hardware::camera::device::V3_2::CaptureResult>& results) {
1077 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1078
1079 // Ideally we should grab mLock, but that can lead to deadlock, and
1080 // it's not super important to get up to date value of mStatus for this
1081 // warning print, hence skipping the lock here
1082 if (mStatus == STATUS_ERROR) {
1083 // Per API contract, HAL should act as closed after device error
1084 // But mStatus can be set to error by framework as well, so just log
1085 // a warning here.
1086 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1087 }
1088
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001089 sp<NotificationListener> listener;
1090 {
1091 std::lock_guard<std::mutex> l(mOutputLock);
1092 listener = mListener.promote();
1093 }
1094
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001095 if (mProcessCaptureResultLock.tryLock() != OK) {
1096 // This should never happen; it indicates a wrong client implementation
1097 // that doesn't follow the contract. But, we can be tolerant here.
1098 ALOGE("%s: callback overlapped! waiting 1s...",
1099 __FUNCTION__);
1100 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1101 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1102 __FUNCTION__);
1103 // really don't know what to do, so bail out.
1104 return hardware::Void();
1105 }
1106 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001107
1108 CaptureOutputStates states {
1109 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001110 mInFlightLock, mLastCompletedRegularFrameNumber,
1111 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1112 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 mNextShutterFrameNumber,
1114 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1115 mNextResultFrameNumber,
1116 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1117 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1118 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001119 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001120 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1121 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001122 };
1123
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001124 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001125 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001126 }
1127 mProcessCaptureResultLock.unlock();
1128 return hardware::Void();
1129}
1130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001131hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001132 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133 // Ideally we should grab mLock, but that can lead to deadlock, and
1134 // it's not super important to get up to date value of mStatus for this
1135 // warning print, hence skipping the lock here
1136 if (mStatus == STATUS_ERROR) {
1137 // Per API contract, HAL should act as closed after device error
1138 // But mStatus can be set to error by framework as well, so just log
1139 // a warning here.
1140 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001141 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 sp<NotificationListener> listener;
1144 {
1145 std::lock_guard<std::mutex> l(mOutputLock);
1146 listener = mListener.promote();
1147 }
1148
1149 CaptureOutputStates states {
1150 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001151 mInFlightLock, mLastCompletedRegularFrameNumber,
1152 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1153 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 mNextShutterFrameNumber,
1155 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1156 mNextResultFrameNumber,
1157 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1158 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1159 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001160 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001161 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1162 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001163 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001165 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001166 }
1167 return hardware::Void();
1168}
1169
Emilian Peevaebbe412018-01-15 13:53:24 +00001170status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001172 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001173 ATRACE_CALL();
1174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001176}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Jianing Weicb0652e2014-03-12 18:29:36 -07001178status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1179 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001185
Emilian Peevaebbe412018-01-15 13:53:24 +00001186 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001187 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188}
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190status_t Camera3Device::setStreamingRequestList(
1191 const List<const PhysicalCameraSettingsList> &requestsList,
1192 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001193 ATRACE_CALL();
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001196}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197
1198sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 status_t res;
1201
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001203 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1204 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 res = filterParamsAndConfigureLocked(request.begin()->metadata,
Emilian Peevf4816702020-04-03 15:44:51 -07001206 CAMERA_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001207 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001209 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001211 } else if (mStatus == STATUS_UNCONFIGURED) {
1212 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 CLOGE("No streams configured");
1214 return NULL;
1215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 }
1217
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
Jianing Weicb0652e2014-03-12 18:29:36 -07001222status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 switch (mStatus) {
1228 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 case STATUS_UNCONFIGURED:
1235 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 case STATUS_ACTIVE:
1237 // OK
1238 break;
1239 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001240 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 return INVALID_OPERATION;
1242 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001243 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001244
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001245 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
1248status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001252 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255status_t Camera3Device::createInputStream(
1256 uint32_t width, uint32_t height, int format, int *id) {
1257 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001259 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001260 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1262 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001263
1264 status_t res;
1265 bool wasActive = false;
1266
1267 switch (mStatus) {
1268 case STATUS_ERROR:
1269 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1270 return INVALID_OPERATION;
1271 case STATUS_UNINITIALIZED:
1272 ALOGE("%s: Device not initialized", __FUNCTION__);
1273 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 case STATUS_UNCONFIGURED:
1275 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 // OK
1277 break;
1278 case STATUS_ACTIVE:
1279 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001280 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283 return res;
1284 }
1285 wasActive = true;
1286 break;
1287 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 return INVALID_OPERATION;
1290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 if (mInputStream != 0) {
1294 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 }
1297
1298 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1299 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301
1302 mInputStream = newStream;
1303
1304 *id = mNextStreamId++;
1305
1306 // Continue captures if active at start
1307 if (wasActive) {
1308 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001309 // Reuse current operating mode and session parameters for new stream config
1310 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 if (res != OK) {
1312 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1313 __FUNCTION__, mNextStreamId, strerror(-res), res);
1314 return res;
1315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317 }
1318
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001319 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320 return OK;
1321}
1322
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001323status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001324 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001325 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001326 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001327 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001328 ATRACE_CALL();
1329
1330 if (consumer == nullptr) {
1331 ALOGE("%s: consumer must not be null", __FUNCTION__);
1332 return BAD_VALUE;
1333 }
1334
1335 std::vector<sp<Surface>> consumers;
1336 consumers.push_back(consumer);
1337
1338 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1340 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341}
1342
1343status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1344 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -07001345 android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001346 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001347 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001348 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001349
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001351 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001353 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001354 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1355 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1356 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001358 status_t res;
1359 bool wasActive = false;
1360
1361 switch (mStatus) {
1362 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001363 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return INVALID_OPERATION;
1365 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001368 case STATUS_UNCONFIGURED:
1369 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 // OK
1371 break;
1372 case STATUS_ACTIVE:
1373 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001374 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001376 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 return res;
1378 }
1379 wasActive = true;
1380 break;
1381 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001382 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 return INVALID_OPERATION;
1384 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001385 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386
1387 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001388
Shuzhen Wang0129d522016-10-30 22:43:41 -07001389 if (consumers.size() == 0 && !hasDeferredConsumer) {
1390 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1391 return BAD_VALUE;
1392 }
Zhijun He5d677d12016-05-29 16:52:39 -07001393
Shuzhen Wang0129d522016-10-30 22:43:41 -07001394 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001395 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1396 return BAD_VALUE;
1397 }
1398
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001400 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001401 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001402 blobBufferSize = getPointCloudBufferSize();
1403 if (blobBufferSize <= 0) {
1404 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1405 return BAD_VALUE;
1406 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001407 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1408 blobBufferSize = width * height;
1409 } else {
1410 blobBufferSize = getJpegBufferSize(width, height);
1411 if (blobBufferSize <= 0) {
1412 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1413 return BAD_VALUE;
1414 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001415 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001416 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001417 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001418 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001419 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1420 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1421 if (rawOpaqueBufferSize <= 0) {
1422 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1423 return BAD_VALUE;
1424 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001426 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001427 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001428 } else if (isShared) {
1429 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1430 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001431 mTimestampOffset, physicalCameraId, streamSetId,
1432 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001433 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001434 newStream = new Camera3OutputStream(mNextStreamId,
1435 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001436 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001439 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001440 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 }
Emilian Peev40ead602017-09-26 15:46:36 +01001442
1443 size_t consumerCount = consumers.size();
1444 for (size_t i = 0; i < consumerCount; i++) {
1445 int id = newStream->getSurfaceId(consumers[i]);
1446 if (id < 0) {
1447 SET_ERR_L("Invalid surface id");
1448 return BAD_VALUE;
1449 }
1450 if (surfaceIds != nullptr) {
1451 surfaceIds->push_back(id);
1452 }
1453 }
1454
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001455 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456
Emilian Peev08dd2452017-04-06 16:55:14 +01001457 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001458
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001459 newStream->setImageDumpMask(mImageDumpMask);
1460
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461 res = mOutputStreams.add(mNextStreamId, newStream);
1462 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001463 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001464 return res;
1465 }
1466
Shuzhen Wang316781a2020-08-18 18:11:01 -07001467 mSessionStatsBuilder.addStream(mNextStreamId);
1468
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001470 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471
1472 // Continue captures if active at start
1473 if (wasActive) {
1474 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001475 // Reuse current operating mode and session parameters for new stream config
1476 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001478 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1479 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 return res;
1481 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001484 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486}
1487
Emilian Peev710c1422017-08-30 11:19:38 +01001488status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001489 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001490 if (nullptr == streamInfo) {
1491 return BAD_VALUE;
1492 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001495
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 switch (mStatus) {
1497 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001501 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001503 case STATUS_UNCONFIGURED:
1504 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 case STATUS_ACTIVE:
1506 // OK
1507 break;
1508 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001509 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return INVALID_OPERATION;
1511 }
1512
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001513 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1514 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001515 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001516 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 }
1518
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001519 streamInfo->width = stream->getWidth();
1520 streamInfo->height = stream->getHeight();
1521 streamInfo->format = stream->getFormat();
1522 streamInfo->dataSpace = stream->getDataSpace();
1523 streamInfo->formatOverridden = stream->isFormatOverridden();
1524 streamInfo->originalFormat = stream->getOriginalFormat();
1525 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1526 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001528}
1529
1530status_t Camera3Device::setStreamTransform(int id,
1531 int transform) {
1532 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 switch (mStatus) {
1537 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001541 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 case STATUS_UNCONFIGURED:
1544 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 case STATUS_ACTIVE:
1546 // OK
1547 break;
1548 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 }
1552
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001553 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1554 if (stream == nullptr) {
1555 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return BAD_VALUE;
1557 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001558 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001559}
1560
1561status_t Camera3Device::deleteStream(int id) {
1562 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 Mutex::Autolock l(mLock);
1565 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001566
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001567 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001568
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 // CameraDevice semantics require device to already be idle before
1570 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001571 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001572 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001573 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 }
1575
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001576 if (mStatus == STATUS_ERROR) {
1577 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1578 __FUNCTION__, mId.string());
1579 return -EBUSY;
1580 }
1581
Igor Murashkin2fba5842013-04-22 14:03:54 -07001582 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001583 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 if (mInputStream != NULL && id == mInputStream->getId()) {
1585 deletedStream = mInputStream;
1586 mInputStream.clear();
1587 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001588 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001589 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001590 return BAD_VALUE;
1591 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07001592 mSessionStatsBuilder.removeStream(id);
Zhijun He5f446352014-01-22 09:49:33 -08001593 }
1594
1595 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001596 if (stream != nullptr) {
1597 deletedStream = stream;
1598 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001599 }
1600
1601 // Free up the stream endpoint so that it can be used by some other stream
1602 res = deletedStream->disconnect();
1603 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001604 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001605 // fall through since we want to still list the stream as deleted.
1606 }
1607 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001608 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609
1610 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001611}
1612
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001613status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001614 ATRACE_CALL();
1615 ALOGV("%s: E", __FUNCTION__);
1616
1617 Mutex::Autolock il(mInterfaceLock);
1618 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001619
Emilian Peev811d2952018-05-25 11:08:40 +01001620 // In case the client doesn't include any session parameter, try a
1621 // speculative configuration using the values from the last cached
1622 // default request.
1623 if (sessionParams.isEmpty() &&
Emilian Peevf4816702020-04-03 15:44:51 -07001624 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA_TEMPLATE_COUNT)) &&
Emilian Peev811d2952018-05-25 11:08:40 +01001625 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1626 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1627 mLastTemplateId);
1628 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1629 operatingMode);
1630 }
1631
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001632 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1633}
1634
1635status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1636 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001637 //Filter out any incoming session parameters
1638 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001639 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1640 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001641 CameraMetadata filteredParams(availableSessionKeys.count);
1642 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1643 filteredParams.getAndLock());
1644 set_camera_metadata_vendor_id(meta, mVendorTagId);
1645 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001646 if (availableSessionKeys.count > 0) {
1647 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1648 camera_metadata_ro_entry entry = params.find(
1649 availableSessionKeys.data.i32[i]);
1650 if (entry.count > 0) {
1651 filteredParams.update(entry);
1652 }
1653 }
1654 }
1655
1656 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001657}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001659status_t Camera3Device::getInputBufferProducer(
1660 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001661 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001662 Mutex::Autolock il(mInterfaceLock);
1663 Mutex::Autolock l(mLock);
1664
1665 if (producer == NULL) {
1666 return BAD_VALUE;
1667 } else if (mInputStream == NULL) {
1668 return INVALID_OPERATION;
1669 }
1670
1671 return mInputStream->getInputBufferProducer(producer);
1672}
1673
Emilian Peevf4816702020-04-03 15:44:51 -07001674status_t Camera3Device::createDefaultRequest(camera_request_template_t templateId,
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675 CameraMetadata *request) {
1676 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001677 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001678
Emilian Peevf4816702020-04-03 15:44:51 -07001679 if (templateId <= 0 || templateId >= CAMERA_TEMPLATE_COUNT) {
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001680 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001681 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001682 return BAD_VALUE;
1683 }
1684
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001685 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001686
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001687 {
1688 Mutex::Autolock l(mLock);
1689 switch (mStatus) {
1690 case STATUS_ERROR:
1691 CLOGE("Device has encountered a serious error");
1692 return INVALID_OPERATION;
1693 case STATUS_UNINITIALIZED:
1694 CLOGE("Device is not initialized!");
1695 return INVALID_OPERATION;
1696 case STATUS_UNCONFIGURED:
1697 case STATUS_CONFIGURED:
1698 case STATUS_ACTIVE:
1699 // OK
1700 break;
1701 default:
1702 SET_ERR_L("Unexpected status: %d", mStatus);
1703 return INVALID_OPERATION;
1704 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001705
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001706 if (!mRequestTemplateCache[templateId].isEmpty()) {
1707 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001708 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001709 return OK;
1710 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001711 }
1712
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001713 camera_metadata_t *rawRequest;
1714 status_t res = mInterface->constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07001715 (camera_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001716
1717 {
1718 Mutex::Autolock l(mLock);
1719 if (res == BAD_VALUE) {
1720 ALOGI("%s: template %d is not supported on this camera device",
1721 __FUNCTION__, templateId);
1722 return res;
1723 } else if (res != OK) {
1724 CLOGE("Unable to construct request template %d: %s (%d)",
1725 templateId, strerror(-res), res);
1726 return res;
1727 }
1728
1729 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1730 mRequestTemplateCache[templateId].acquire(rawRequest);
1731
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001732 // Override the template request with zoomRatioMapper
1733 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1734 &mRequestTemplateCache[templateId]);
1735 if (res != OK) {
1736 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1737 templateId, strerror(-res), res);
1738 return res;
1739 }
1740
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001741 // Fill in JPEG_QUALITY if not available
1742 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1743 static const uint8_t kDefaultJpegQuality = 95;
1744 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1745 &kDefaultJpegQuality, 1);
1746 }
1747
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001748 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001749 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001750 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001751 return OK;
1752}
1753
1754status_t Camera3Device::waitUntilDrained() {
1755 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001757 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001759
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001760 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001761}
1762
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001763status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 switch (mStatus) {
1765 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001766 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 ALOGV("%s: Already idle", __FUNCTION__);
1768 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001769 case STATUS_CONFIGURED:
1770 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771 case STATUS_ERROR:
1772 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 break;
1775 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001776 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 return INVALID_OPERATION;
1778 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001779 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1780 maxExpectedDuration);
1781 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001782 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001783 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001784 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1785 res);
1786 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787 return res;
1788}
1789
Ruben Brunk183f0562015-08-12 12:55:02 -07001790
1791void Camera3Device::internalUpdateStatusLocked(Status status) {
1792 mStatus = status;
1793 mRecentStatusUpdates.add(mStatus);
1794 mStatusChanged.broadcast();
1795}
1796
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001797// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001798status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001799 if (mRequestThread.get() != nullptr) {
1800 mRequestThread->setPaused(true);
1801 } else {
1802 return NO_INIT;
1803 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001804
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001805 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1806 maxExpectedDuration);
1807 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 if (res != OK) {
1809 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001810 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811 }
1812
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813 return res;
1814}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001816// Resume after internalPauseAndWaitLocked
1817status_t Camera3Device::internalResumeLocked() {
1818 status_t res;
1819
1820 mRequestThread->setPaused(false);
1821
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001822 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1823 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1825 if (res != OK) {
1826 SET_ERR_L("Can't transition to active in %f seconds!",
1827 kActiveTimeout/1e9);
1828 }
1829 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001831}
1832
Ruben Brunk183f0562015-08-12 12:55:02 -07001833status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001834 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001835
1836 size_t startIndex = 0;
1837 if (mStatusWaiters == 0) {
1838 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1839 // this status list
1840 mRecentStatusUpdates.clear();
1841 } else {
1842 // If other threads are waiting on updates to this status list, set the position of the
1843 // first element that this list will check rather than clearing the list.
1844 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001845 }
1846
Ruben Brunk183f0562015-08-12 12:55:02 -07001847 mStatusWaiters++;
1848
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001849 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001850 if (!active && mUseHalBufManager) {
1851 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001852 if (mStatus == STATUS_ACTIVE) {
1853 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001854 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001855 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001856 mRequestBufferSM.onWaitUntilIdle();
1857 }
1858
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001859 bool stateSeen = false;
1860 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001861 if (active == (mStatus == STATUS_ACTIVE)) {
1862 // Desired state is current
1863 break;
1864 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865
1866 res = mStatusChanged.waitRelative(mLock, timeout);
1867 if (res != OK) break;
1868
Ruben Brunk183f0562015-08-12 12:55:02 -07001869 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1870 // transitions.
1871 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1872 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1873 __FUNCTION__);
1874
1875 // Encountered desired state since we began waiting
1876 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1878 stateSeen = true;
1879 break;
1880 }
1881 }
1882 } while (!stateSeen);
1883
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001884 if (signalPipelineDrain) {
1885 mRequestThread->resetPipelineDrain();
1886 }
1887
Ruben Brunk183f0562015-08-12 12:55:02 -07001888 mStatusWaiters--;
1889
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001890 return res;
1891}
1892
1893
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001894status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001896 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001897
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001898 if (listener != NULL && mListener != NULL) {
1899 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1900 }
1901 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001902 mRequestThread->setNotificationListener(listener);
1903 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001904
1905 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001906}
1907
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001908bool Camera3Device::willNotify3A() {
1909 return false;
1910}
1911
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001912status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001913 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001914 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001915
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001916 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001917 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1918 if (st == std::cv_status::timeout) {
1919 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001920 }
1921 }
1922 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923}
1924
Jianing Weicb0652e2014-03-12 18:29:36 -07001925status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001927 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001928
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001929 if (mResultQueue.empty()) {
1930 return NOT_ENOUGH_DATA;
1931 }
1932
Jianing Weicb0652e2014-03-12 18:29:36 -07001933 if (frame == NULL) {
1934 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1935 return BAD_VALUE;
1936 }
1937
1938 CaptureResult &result = *(mResultQueue.begin());
1939 frame->mResultExtras = result.mResultExtras;
1940 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001941 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001942 mResultQueue.erase(mResultQueue.begin());
1943
1944 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001945}
1946
1947status_t Camera3Device::triggerAutofocus(uint32_t id) {
1948 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001951 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1952 // Mix-in this trigger into the next request and only the next request.
1953 RequestTrigger trigger[] = {
1954 {
1955 ANDROID_CONTROL_AF_TRIGGER,
1956 ANDROID_CONTROL_AF_TRIGGER_START
1957 },
1958 {
1959 ANDROID_CONTROL_AF_TRIGGER_ID,
1960 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001961 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001962 };
1963
1964 return mRequestThread->queueTrigger(trigger,
1965 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001966}
1967
1968status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1969 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001970 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001972 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1973 // Mix-in this trigger into the next request and only the next request.
1974 RequestTrigger trigger[] = {
1975 {
1976 ANDROID_CONTROL_AF_TRIGGER,
1977 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1978 },
1979 {
1980 ANDROID_CONTROL_AF_TRIGGER_ID,
1981 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001982 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001983 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001985 return mRequestThread->queueTrigger(trigger,
1986 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987}
1988
1989status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1990 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001991 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001993 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1994 // Mix-in this trigger into the next request and only the next request.
1995 RequestTrigger trigger[] = {
1996 {
1997 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1998 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1999 },
2000 {
2001 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2002 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002003 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002004 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002005
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002006 return mRequestThread->queueTrigger(trigger,
2007 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002008}
2009
Jianing Weicb0652e2014-03-12 18:29:36 -07002010status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002011 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002012 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002013 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002014
Zhijun He7ef20392014-04-21 16:04:17 -07002015 {
2016 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002017
2018 // b/116514106 "disconnect()" can get called twice for the same device. The
2019 // camera device will not be initialized during the second run.
2020 if (mStatus == STATUS_UNINITIALIZED) {
2021 return OK;
2022 }
2023
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002024 mRequestThread->clear(/*out*/frameNumber);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002025
2026 // Stop session and stream counter
2027 mSessionStatsBuilder.stopCounter();
Zhijun He7ef20392014-04-21 16:04:17 -07002028 }
2029
Emilian Peev08dd2452017-04-06 16:55:14 +01002030 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002031}
2032
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002033status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002034 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2035}
2036
2037status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002038 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002039 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002040 Mutex::Autolock il(mInterfaceLock);
2041 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002042
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002043 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2044 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002045 CLOGE("Stream %d does not exist", streamId);
2046 return BAD_VALUE;
2047 }
2048
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002049 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002050 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002051 return BAD_VALUE;
2052 }
2053
2054 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002055 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002056 return BAD_VALUE;
2057 }
2058
Ruben Brunkc78ac262015-08-13 17:58:46 -07002059 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002060}
2061
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002062status_t Camera3Device::tearDown(int streamId) {
2063 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002064 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002065 Mutex::Autolock il(mInterfaceLock);
2066 Mutex::Autolock l(mLock);
2067
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002068 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2069 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002070 CLOGE("Stream %d does not exist", streamId);
2071 return BAD_VALUE;
2072 }
2073
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002074 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2075 CLOGE("Stream %d is a target of a in-progress request", streamId);
2076 return BAD_VALUE;
2077 }
2078
2079 return stream->tearDown();
2080}
2081
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002082status_t Camera3Device::addBufferListenerForStream(int streamId,
2083 wp<Camera3StreamBufferListener> listener) {
2084 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002085 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002086 Mutex::Autolock il(mInterfaceLock);
2087 Mutex::Autolock l(mLock);
2088
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002089 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2090 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002091 CLOGE("Stream %d does not exist", streamId);
2092 return BAD_VALUE;
2093 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002094 stream->addBufferListener(listener);
2095
2096 return OK;
2097}
2098
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002099/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002100 * Methods called by subclasses
2101 */
2102
2103void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002104 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -07002105 std::vector<int> streamIds;
2106 std::vector<hardware::CameraStreamStats> streamStats;
2107
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002108 {
2109 // Need mLock to safely update state and synchronize to current
2110 // state of methods in flight.
2111 Mutex::Autolock l(mLock);
2112 // We can get various system-idle notices from the status tracker
2113 // while starting up. Only care about them if we've actually sent
2114 // in some requests recently.
2115 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2116 return;
2117 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002118 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2119 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002120 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002121
2122 // Skip notifying listener if we're doing some user-transparent
2123 // state changes
2124 if (mPauseStateNotify) return;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002125
2126 // Populate stream statistics in case of Idle
2127 if (idle) {
2128 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2129 auto stream = mOutputStreams[i];
2130 if (stream.get() == nullptr) continue;
2131 streamIds.push_back(stream->getId());
2132 Camera3Stream* camera3Stream = Camera3Stream::cast(stream->asHalStream());
2133 int64_t usage = 0LL;
2134 if (camera3Stream != nullptr) {
2135 usage = camera3Stream->getUsage();
2136 }
2137 streamStats.emplace_back(stream->getWidth(), stream->getHeight(),
2138 stream->getFormat(), stream->getDataSpace(), usage,
2139 stream->getMaxHalBuffers(),
2140 stream->getMaxTotalBuffers() - stream->getMaxHalBuffers());
2141 }
2142 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002143 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002144
2145 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002146 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002147 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002148 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002149 }
2150 if (idle && listener != NULL) {
Shuzhen Wang316781a2020-08-18 18:11:01 -07002151 // Get session stats from the builder, and notify the listener.
2152 int64_t requestCount, resultErrorCount;
2153 bool deviceError;
2154 std::map<int, StreamStats> streamStatsMap;
2155 mSessionStatsBuilder.buildAndReset(&requestCount, &resultErrorCount,
2156 &deviceError, &streamStatsMap);
2157 for (size_t i = 0; i < streamIds.size(); i++) {
2158 int streamId = streamIds[i];
2159 auto stats = streamStatsMap.find(streamId);
2160 if (stats != streamStatsMap.end()) {
2161 streamStats[i].mRequestCount = stats->second.mRequestedFrameCount;
2162 streamStats[i].mErrorCount = stats->second.mDroppedFrameCount;
2163 streamStats[i].mStartLatencyMs = stats->second.mStartLatencyMs;
Shuzhen Wangdb8f2782020-10-30 08:43:37 -07002164 streamStats[i].mHistogramType =
2165 hardware::CameraStreamStats::HISTOGRAM_TYPE_CAPTURE_LATENCY;
2166 streamStats[i].mHistogramBins.assign(
2167 stats->second.mCaptureLatencyBins.begin(),
2168 stats->second.mCaptureLatencyBins.end());
2169 streamStats[i].mHistogramCounts.assign(
2170 stats->second.mCaptureLatencyHistogram.begin(),
2171 stats->second.mCaptureLatencyHistogram.end());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002172 }
2173 }
2174 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002175 }
2176}
2177
Shuzhen Wang758c2152017-01-10 18:26:18 -08002178status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002179 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002180 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002181 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2182 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002183
2184 if (surfaceIds == nullptr) {
2185 return BAD_VALUE;
2186 }
2187
Zhijun He5d677d12016-05-29 16:52:39 -07002188 Mutex::Autolock il(mInterfaceLock);
2189 Mutex::Autolock l(mLock);
2190
Shuzhen Wang758c2152017-01-10 18:26:18 -08002191 if (consumers.size() == 0) {
2192 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002193 return BAD_VALUE;
2194 }
2195
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002196 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2197 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002198 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002199 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002200 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002201
2202 // isConsumerConfigurationDeferred will be off after setConsumers
2203 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002204 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002205 if (res != OK) {
2206 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2207 return res;
2208 }
2209
Emilian Peev40ead602017-09-26 15:46:36 +01002210 for (auto &consumer : consumers) {
2211 int id = stream->getSurfaceId(consumer);
2212 if (id < 0) {
2213 CLOGE("Invalid surface id!");
2214 return BAD_VALUE;
2215 }
2216 surfaceIds->push_back(id);
2217 }
2218
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002219 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002220 if (!stream->isConfiguring()) {
2221 CLOGE("Stream %d was already fully configured.", streamId);
2222 return INVALID_OPERATION;
2223 }
Zhijun He5d677d12016-05-29 16:52:39 -07002224
Shuzhen Wang0129d522016-10-30 22:43:41 -07002225 res = stream->finishConfiguration();
2226 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002227 // If finishConfiguration fails due to abandoned surface, do not set
2228 // device to error state.
2229 bool isSurfaceAbandoned =
2230 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2231 if (!isSurfaceAbandoned) {
2232 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2233 stream->getId(), strerror(-res), res);
2234 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002235 return res;
2236 }
Zhijun He5d677d12016-05-29 16:52:39 -07002237 }
2238
2239 return OK;
2240}
2241
Emilian Peev40ead602017-09-26 15:46:36 +01002242status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2243 const std::vector<OutputStreamInfo> &outputInfo,
2244 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2245 Mutex::Autolock il(mInterfaceLock);
2246 Mutex::Autolock l(mLock);
2247
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002248 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2249 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002250 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002251 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002252 }
2253
2254 for (const auto &it : removedSurfaceIds) {
2255 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2256 CLOGE("Shared surface still part of a pending request!");
2257 return -EBUSY;
2258 }
2259 }
2260
Emilian Peev40ead602017-09-26 15:46:36 +01002261 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2262 if (res != OK) {
2263 CLOGE("Stream %d failed to update stream (error %d %s) ",
2264 streamId, res, strerror(-res));
2265 if (res == UNKNOWN_ERROR) {
2266 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2267 __FUNCTION__);
2268 }
2269 return res;
2270 }
2271
2272 return res;
2273}
2274
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002275status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2276 Mutex::Autolock il(mInterfaceLock);
2277 Mutex::Autolock l(mLock);
2278
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002279 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2280 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002281 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2282 return BAD_VALUE;
2283 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002284
2285 if (dropping) {
2286 mSessionStatsBuilder.stopCounter(streamId);
2287 } else {
2288 mSessionStatsBuilder.startCounter(streamId);
2289 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002290 return stream->dropBuffers(dropping);
2291}
2292
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002293/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294 * Camera3Device private methods
2295 */
2296
2297sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002298 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002301 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002302 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002303
2304 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002305 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 if (inputStreams.count > 0) {
2307 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002308 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002309 CLOGE("Request references unknown input stream %d",
2310 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311 return NULL;
2312 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002313
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002314 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002315 SET_ERR_L("%s: input stream %d is not configured!",
2316 __FUNCTION__, mInputStream->getId());
2317 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002319 // Check if stream prepare is blocking requests.
2320 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002321 CLOGE("Request references an input stream that's being prepared!");
2322 return NULL;
2323 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002324
2325 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002326 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002327 }
2328
2329 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002330 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002332 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333 return NULL;
2334 }
2335
2336 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002337 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2338 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002339 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002340 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002341 return NULL;
2342 }
Zhijun He5d677d12016-05-29 16:52:39 -07002343 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002344 auto iter = surfaceMap.find(streams.data.i32[i]);
2345 if (iter != surfaceMap.end()) {
2346 const std::vector<size_t>& surfaces = iter->second;
2347 for (const auto& surface : surfaces) {
2348 if (stream->isConsumerConfigurationDeferred(surface)) {
2349 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2350 "due to deferred consumer", stream->getId(), surface);
2351 return NULL;
2352 }
2353 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002354 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002355 }
2356
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002357 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002358 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2359 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002360 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002361 // Check if stream prepare is blocking requests.
2362 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002363 CLOGE("Request references an output stream that's being prepared!");
2364 return NULL;
2365 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002366
2367 newRequest->mOutputStreams.push(stream);
2368 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002369 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002370 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002371
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002372 auto rotateAndCropEntry =
2373 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2374 if (rotateAndCropEntry.count > 0 &&
2375 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2376 newRequest->mRotateAndCropAuto = true;
2377 } else {
2378 newRequest->mRotateAndCropAuto = false;
2379 }
2380
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002381 auto zoomRatioEntry =
2382 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2383 if (zoomRatioEntry.count > 0 &&
2384 zoomRatioEntry.data.f[0] == 1.0f) {
2385 newRequest->mZoomRatioIs1x = true;
2386 } else {
2387 newRequest->mZoomRatioIs1x = false;
2388 }
2389
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002390 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002391}
2392
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002393void Camera3Device::cancelStreamsConfigurationLocked() {
2394 int res = OK;
2395 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2396 res = mInputStream->cancelConfiguration();
2397 if (res != OK) {
2398 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2399 mInputStream->getId(), strerror(-res), res);
2400 }
2401 }
2402
2403 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002404 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002405 if (outputStream->isConfiguring()) {
2406 res = outputStream->cancelConfiguration();
2407 if (res != OK) {
2408 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2409 outputStream->getId(), strerror(-res), res);
2410 }
2411 }
2412 }
2413
2414 // Return state to that at start of call, so that future configures
2415 // properly clean things up
2416 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2417 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002418
2419 res = mPreparerThread->resume();
2420 if (res != OK) {
2421 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2422 }
2423}
2424
Emilian Peev0d0191e2020-04-21 17:01:18 -07002425bool Camera3Device::checkAbandonedStreamsLocked() {
2426 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2427 return true;
2428 }
2429
2430 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2431 auto stream = mOutputStreams[i];
2432 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2433 return true;
2434 }
2435 }
2436
2437 return false;
2438}
2439
Emilian Peev3bead5f2020-05-28 17:29:08 -07002440bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002441 ATRACE_CALL();
2442 bool ret = false;
2443
Shuzhen Wang316781a2020-08-18 18:11:01 -07002444 nsecs_t startTime = systemTime();
2445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002446 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002447 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2448
2449 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002450 if (checkAbandonedStreamsLocked()) {
2451 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2452 __FUNCTION__);
2453 return true;
2454 }
2455
Emilian Peev3bead5f2020-05-28 17:29:08 -07002456 status_t rc = NO_ERROR;
2457 bool markClientActive = false;
2458 if (mStatus == STATUS_ACTIVE) {
2459 markClientActive = true;
2460 mPauseStateNotify = true;
2461 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2462
2463 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2464 }
2465
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002466 if (rc == NO_ERROR) {
2467 mNeedConfig = true;
2468 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2469 if (rc == NO_ERROR) {
2470 ret = true;
2471 mPauseStateNotify = false;
2472 //Moving to active state while holding 'mLock' is important.
2473 //There could be pending calls to 'create-/deleteStream' which
2474 //will trigger another stream configuration while the already
2475 //present streams end up with outstanding buffers that will
2476 //not get drained.
2477 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002478 } else if (rc == DEAD_OBJECT) {
2479 // DEAD_OBJECT can be returned if either the consumer surface is
2480 // abandoned, or the HAL has died.
2481 // - If the HAL has died, configureStreamsLocked call will set
2482 // device to error state,
2483 // - If surface is abandoned, we should not set device to error
2484 // state.
2485 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002486 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002487 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002488 }
2489 } else {
2490 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2491 }
2492
Shuzhen Wang316781a2020-08-18 18:11:01 -07002493 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2494 ns2ms(systemTime() - startTime));
2495
Emilian Peev3bead5f2020-05-28 17:29:08 -07002496 if (markClientActive) {
2497 mStatusTracker->markComponentActive(clientStatusId);
2498 }
2499
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002500 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002501}
2502
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002503status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002504 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002505 ATRACE_CALL();
2506 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002507
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002508 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002509 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002510 return INVALID_OPERATION;
2511 }
2512
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002513 if (operatingMode < 0) {
2514 CLOGE("Invalid operating mode: %d", operatingMode);
2515 return BAD_VALUE;
2516 }
2517
2518 bool isConstrainedHighSpeed =
2519 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2520 operatingMode;
2521
2522 if (mOperatingMode != operatingMode) {
2523 mNeedConfig = true;
2524 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2525 mOperatingMode = operatingMode;
2526 }
2527
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002528 // In case called from configureStreams, abort queued input buffers not belonging to
2529 // any pending requests.
2530 if (mInputStream != NULL && notifyRequestThread) {
2531 while (true) {
Emilian Peevf4816702020-04-03 15:44:51 -07002532 camera_stream_buffer_t inputBuffer;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002533 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2534 /*respectHalLimit*/ false);
2535 if (res != OK) {
2536 // Exhausted acquiring all input buffers.
2537 break;
2538 }
2539
Emilian Peevf4816702020-04-03 15:44:51 -07002540 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002541 res = mInputStream->returnInputBuffer(inputBuffer);
2542 if (res != OK) {
2543 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2544 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2545 }
2546 }
2547 }
2548
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002549 if (!mNeedConfig) {
2550 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2551 return OK;
2552 }
2553
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002554 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002555 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002556 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2557 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002558 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002559 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002560 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002561 }
2562
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002563 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002564 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002565
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002566 mPreparerThread->pause();
2567
Emilian Peevf4816702020-04-03 15:44:51 -07002568 camera_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002569 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002570 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2571
Emilian Peevf4816702020-04-03 15:44:51 -07002572 Vector<camera3::camera_stream_t*> streams;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002573 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002574 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002575
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576
2577 if (mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07002578 camera3::camera_stream_t *inputStream;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 inputStream = mInputStream->startConfiguration();
2580 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002581 CLOGE("Can't start input stream configuration");
2582 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002583 return INVALID_OPERATION;
2584 }
2585 streams.add(inputStream);
2586 }
2587
2588 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002589
2590 // Don't configure bidi streams twice, nor add them twice to the list
2591 if (mOutputStreams[i].get() ==
2592 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2593
2594 config.num_streams--;
2595 continue;
2596 }
2597
Emilian Peevf4816702020-04-03 15:44:51 -07002598 camera3::camera_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002599 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002601 CLOGE("Can't start output stream configuration");
2602 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002603 return INVALID_OPERATION;
2604 }
2605 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002606
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002607 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002608 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2609 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002610 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2611 bufferSizes[k] = static_cast<uint32_t>(
2612 getJpegBufferSize(outputStream->width, outputStream->height));
2613 } else if (outputStream->data_space ==
2614 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2615 bufferSizes[k] = outputStream->width * outputStream->height;
2616 } else {
2617 ALOGW("%s: Blob dataSpace %d not supported",
2618 __FUNCTION__, outputStream->data_space);
2619 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002620 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002621 }
2622
2623 config.streams = streams.editArray();
2624
2625 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002626 // max_buffers, usage, and priv fields, as well as data_space and format
2627 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002628
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002629 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002630 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002631 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002633 if (res == BAD_VALUE) {
2634 // HAL rejected this set of streams as unsupported, clean up config
2635 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002636 CLOGE("Set of requested inputs/outputs not supported by HAL");
2637 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002638 return BAD_VALUE;
2639 } else if (res != OK) {
2640 // Some other kind of error from configure_streams - this is not
2641 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002642 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2643 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644 return res;
2645 }
2646
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002647 // Finish all stream configuration immediately.
2648 // TODO: Try to relax this later back to lazy completion, which should be
2649 // faster
2650
Igor Murashkin073f8572013-05-02 14:59:28 -07002651 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002652 bool streamReConfigured = false;
2653 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002654 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002655 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002656 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002657 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002658 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2659 return DEAD_OBJECT;
2660 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002661 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002662 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002663 if (streamReConfigured) {
2664 mInterface->onStreamReConfigured(mInputStream->getId());
2665 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002666 }
2667
2668 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002669 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002670 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002671 bool streamReConfigured = false;
2672 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002673 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002674 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002675 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002676 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002677 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2678 return DEAD_OBJECT;
2679 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002680 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002681 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002682 if (streamReConfigured) {
2683 mInterface->onStreamReConfigured(outputStream->getId());
2684 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002685 }
2686 }
2687
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688 // Request thread needs to know to avoid using repeat-last-settings protocol
2689 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002690 if (notifyRequestThread) {
2691 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2692 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002693
Zhijun He90f7c372016-08-16 16:19:43 -07002694 char value[PROPERTY_VALUE_MAX];
2695 property_get("camera.fifo.disable", value, "0");
2696 int32_t disableFifo = atoi(value);
2697 if (disableFifo != 1) {
2698 // Boost priority of request thread to SCHED_FIFO.
2699 pid_t requestThreadTid = mRequestThread->getTid();
2700 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002701 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002702 if (res != OK) {
2703 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2704 strerror(-res), res);
2705 } else {
2706 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2707 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002708 }
2709
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002710 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002711 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2712 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2713 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2714 sessionParams.unlock(newSessionParams);
2715 mSessionParams.unlock(currentSessionParams);
2716 if (updateSessionParams) {
2717 mSessionParams = sessionParams;
2718 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002719
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002720 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002721
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002722 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002723 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002724
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002725 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002726
Zhijun He0a210512014-07-24 13:45:15 -07002727 // tear down the deleted streams after configure streams.
2728 mDeletedStreams.clear();
2729
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002730 auto rc = mPreparerThread->resume();
2731 if (rc != OK) {
2732 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2733 return rc;
2734 }
2735
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002736 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002737 mRequestBufferSM.onStreamsConfigured();
2738 }
2739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002741}
2742
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002743status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002744 ATRACE_CALL();
2745 status_t res;
2746
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002747 if (mFakeStreamId != NO_STREAM) {
2748 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002749 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002750 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002751 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002752 return INVALID_OPERATION;
2753 }
2754
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002755 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002756
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002757 sp<Camera3OutputStreamInterface> fakeStream =
2758 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002759
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002760 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002761 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002762 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002763 return res;
2764 }
2765
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002766 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002767 mNextStreamId++;
2768
2769 return OK;
2770}
2771
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002772status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002773 ATRACE_CALL();
2774 status_t res;
2775
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002776 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002777 if (mOutputStreams.size() == 1) return OK;
2778
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002779 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002780
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002781 // Ok, have a fake stream and there's at least one other output stream,
2782 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002783
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002784 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002785 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002786 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002787 return INVALID_OPERATION;
2788 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002789 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002790
2791 // Free up the stream endpoint so that it can be used by some other stream
2792 res = deletedStream->disconnect();
2793 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002794 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002795 // fall through since we want to still list the stream as deleted.
2796 }
2797 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002798 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002799
2800 return res;
2801}
2802
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002803void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002804 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002805 Mutex::Autolock l(mLock);
2806 va_list args;
2807 va_start(args, fmt);
2808
2809 setErrorStateLockedV(fmt, args);
2810
2811 va_end(args);
2812}
2813
2814void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002815 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002816 Mutex::Autolock l(mLock);
2817 setErrorStateLockedV(fmt, args);
2818}
2819
2820void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2821 va_list args;
2822 va_start(args, fmt);
2823
2824 setErrorStateLockedV(fmt, args);
2825
2826 va_end(args);
2827}
2828
2829void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002830 // Print out all error messages to log
2831 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002832 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002833
2834 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002835 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002836
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002837 mErrorCause = errorCause;
2838
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002839 if (mRequestThread != nullptr) {
2840 mRequestThread->setPaused(true);
2841 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002842 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002843
2844 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002845 sp<NotificationListener> listener = mListener.promote();
2846 if (listener != NULL) {
2847 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002848 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002849 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002850 }
2851
2852 // Save stack trace. View by dumping it later.
2853 CameraTraces::saveTrace();
2854 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002855}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002856
2857/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002858 * In-flight request management
2859 */
2860
Jianing Weicb0652e2014-03-12 18:29:36 -07002861status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002862 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002863 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002864 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002865 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002866 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002867 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002868 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002869
2870 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002871 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002872 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002873 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002874 if (res < 0) return res;
2875
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002876 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002877 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2878 // avoid a deadlock during reprocess requests.
2879 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002880 if (mStatusTracker != nullptr) {
2881 mStatusTracker->markComponentActive(mInFlightStatusId);
2882 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002883 }
2884
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002885 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002886 return OK;
2887}
2888
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002889void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002890 // Indicate idle inFlightMap to the status tracker
2891 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002892 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002893 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2894 // avoid a deadlock during reprocess requests.
2895 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002896 if (mStatusTracker != nullptr) {
2897 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2898 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002899 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002900 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002901}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002902
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002903void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002904 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002905 // something has likely gone wrong. This might still be legit only if application send in
2906 // a long burst of long exposure requests.
2907 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2908 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2909 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2910 mInFlightMap.size(), mExpectedInflightDuration);
2911 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2912 kInFlightWarnLimitHighSpeed) {
2913 CLOGW("In-flight list too large for high speed configuration: %zu,"
2914 "total inflight duration %" PRIu64,
2915 mInFlightMap.size(), mExpectedInflightDuration);
2916 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002917 }
2918}
2919
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002920void Camera3Device::onInflightMapFlushedLocked() {
2921 mExpectedInflightDuration = 0;
2922}
2923
2924void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002925 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002926 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2927 mInFlightMap.removeItemsAt(idx, 1);
2928
2929 onInflightEntryRemovedLocked(duration);
2930}
2931
2932
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002933void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002934 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002935 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002936 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002937 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002938 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002939 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002940
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002941 FlushInflightReqStates states {
2942 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002943 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002944
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002945 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002946}
2947
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002948CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002949 ALOGV("%s", __FUNCTION__);
2950
Igor Murashkin1e479c02013-09-06 16:55:14 -07002951 CameraMetadata retVal;
2952
2953 if (mRequestThread != NULL) {
2954 retVal = mRequestThread->getLatestRequest();
2955 }
2956
Igor Murashkin1e479c02013-09-06 16:55:14 -07002957 return retVal;
2958}
2959
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002960void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002961 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2962 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2963
2964 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2965 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002966}
2967
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002968/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002969 * HalInterface inner class methods
2970 */
2971
Yifan Hongf79b5542017-04-11 14:44:25 -07002972Camera3Device::HalInterface::HalInterface(
2973 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002974 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002975 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002976 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002977 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002978 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002979 mIsReconfigurationQuerySupported(true),
2980 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002981 // Check with hardware service manager if we can downcast these interfaces
2982 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002983 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2984 if (castResult_3_6.isOk()) {
2985 mHidlSession_3_6 = castResult_3_6;
2986 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002987 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2988 if (castResult_3_5.isOk()) {
2989 mHidlSession_3_5 = castResult_3_5;
2990 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002991 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2992 if (castResult_3_4.isOk()) {
2993 mHidlSession_3_4 = castResult_3_4;
2994 }
2995 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2996 if (castResult_3_3.isOk()) {
2997 mHidlSession_3_3 = castResult_3_3;
2998 }
2999}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003000
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003001Camera3Device::HalInterface::HalInterface() :
3002 mUseHalBufManager(false),
3003 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003004
3005Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003006 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003007 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003008 mUseHalBufManager(other.mUseHalBufManager),
3009 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003010
3011bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003012 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003013}
3014
3015void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003016 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003017 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003018 mHidlSession_3_4.clear();
3019 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003020 mHidlSession.clear();
3021}
3022
3023status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
Emilian Peevf4816702020-04-03 15:44:51 -07003024 camera_request_template_t templateId,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003025 /*out*/ camera_metadata_t **requestTemplate) {
3026 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3027 if (!valid()) return INVALID_OPERATION;
3028 status_t res = OK;
3029
Emilian Peev31abd0a2017-05-11 18:37:46 +01003030 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003031
3032 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003033 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003034 status = s;
3035 if (status == common::V1_0::Status::OK) {
3036 const camera_metadata *r =
3037 reinterpret_cast<const camera_metadata_t*>(request.data());
3038 size_t expectedSize = request.size();
3039 int ret = validate_camera_metadata_structure(r, &expectedSize);
3040 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3041 *requestTemplate = clone_camera_metadata(r);
3042 if (*requestTemplate == nullptr) {
3043 ALOGE("%s: Unable to clone camera metadata received from HAL",
3044 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003045 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003046 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003047 } else {
3048 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3049 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003050 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003051 }
3052 };
3053 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003054 RequestTemplate id;
3055 switch (templateId) {
Emilian Peevf4816702020-04-03 15:44:51 -07003056 case CAMERA_TEMPLATE_PREVIEW:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003057 id = RequestTemplate::PREVIEW;
3058 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003059 case CAMERA_TEMPLATE_STILL_CAPTURE:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003060 id = RequestTemplate::STILL_CAPTURE;
3061 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003062 case CAMERA_TEMPLATE_VIDEO_RECORD:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003063 id = RequestTemplate::VIDEO_RECORD;
3064 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003065 case CAMERA_TEMPLATE_VIDEO_SNAPSHOT:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003066 id = RequestTemplate::VIDEO_SNAPSHOT;
3067 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003068 case CAMERA_TEMPLATE_ZERO_SHUTTER_LAG:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003069 id = RequestTemplate::ZERO_SHUTTER_LAG;
3070 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003071 case CAMERA_TEMPLATE_MANUAL:
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003072 id = RequestTemplate::MANUAL;
3073 break;
3074 default:
3075 // Unknown template ID, or this HAL is too old to support it
3076 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003077 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003078 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003079
Emilian Peev31abd0a2017-05-11 18:37:46 +01003080 if (!err.isOk()) {
3081 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3082 res = DEAD_OBJECT;
3083 } else {
3084 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003085 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003086
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003087 return res;
3088}
3089
Emilian Peev4ec17882019-01-24 17:16:58 -08003090bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3091 CameraMetadata& newSessionParams) {
3092 // We do reconfiguration by default;
3093 bool ret = true;
3094 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3095 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3096 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3097 oldSessionParams.getAndLock());
3098 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3099 newSessionParams.getAndLock());
3100 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3101 get_camera_metadata_size(oldSessioMeta));
3102 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3103 get_camera_metadata_size(newSessioMeta));
3104 hardware::camera::common::V1_0::Status callStatus;
3105 bool required;
3106 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3107 bool requiredFlag) {
3108 callStatus = s;
3109 required = requiredFlag;
3110 };
3111 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3112 oldSessionParams.unlock(oldSessioMeta);
3113 newSessionParams.unlock(newSessioMeta);
3114 if (err.isOk()) {
3115 switch (callStatus) {
3116 case hardware::camera::common::V1_0::Status::OK:
3117 ret = required;
3118 break;
3119 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3120 mIsReconfigurationQuerySupported = false;
3121 ret = true;
3122 break;
3123 default:
3124 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3125 ret = true;
3126 }
3127 } else {
3128 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3129 ret = true;
3130 }
3131 }
3132
3133 return ret;
3134}
3135
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003136status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peevf4816702020-04-03 15:44:51 -07003137 camera_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003138 ATRACE_NAME("CameraHal::configureStreams");
3139 if (!valid()) return INVALID_OPERATION;
3140 status_t res = OK;
3141
Emilian Peev31abd0a2017-05-11 18:37:46 +01003142 // Convert stream config to HIDL
3143 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003144 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3145 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3146 requestedConfiguration3_2.streams.resize(config->num_streams);
3147 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003148 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003149 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3150 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peevf4816702020-04-03 15:44:51 -07003151 camera3::camera_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003152
Emilian Peev31abd0a2017-05-11 18:37:46 +01003153 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3154 cam3stream->setBufferFreedListener(this);
3155 int streamId = cam3stream->getId();
3156 StreamType streamType;
3157 switch (src->stream_type) {
Emilian Peevf4816702020-04-03 15:44:51 -07003158 case CAMERA_STREAM_OUTPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003159 streamType = StreamType::OUTPUT;
3160 break;
Emilian Peevf4816702020-04-03 15:44:51 -07003161 case CAMERA_STREAM_INPUT:
Emilian Peev31abd0a2017-05-11 18:37:46 +01003162 streamType = StreamType::INPUT;
3163 break;
3164 default:
3165 ALOGE("%s: Stream %d: Unsupported stream type %d",
3166 __FUNCTION__, streamId, config->streams[i]->stream_type);
3167 return BAD_VALUE;
3168 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003169 dst3_2.id = streamId;
3170 dst3_2.streamType = streamType;
3171 dst3_2.width = src->width;
3172 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003173 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Emilian Peevf4816702020-04-03 15:44:51 -07003174 dst3_2.rotation = mapToStreamRotation((camera_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003175 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3176 // to HAL are original, not the overriden ones.
3177 if (mHidlSession_3_5 != nullptr) {
3178 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3179 cam3stream->getOriginalFormat() : src->format);
3180 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3181 cam3stream->getOriginalDataSpace() : src->data_space);
3182 } else {
3183 dst3_2.format = mapToPixelFormat(src->format);
3184 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3185 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003186 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003187 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003188 if (src->physical_camera_id != nullptr) {
3189 dst3_4.physicalCameraId = src->physical_camera_id;
3190 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003191
3192 activeStreams.insert(streamId);
3193 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003194 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003195 }
3196 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003197 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003198
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003199 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003200 res = mapToStreamConfigurationMode(
Emilian Peevf4816702020-04-03 15:44:51 -07003201 (camera_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003202 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003203 if (res != OK) {
3204 return res;
3205 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003206 requestedConfiguration3_2.operationMode = operationMode;
3207 requestedConfiguration3_4.operationMode = operationMode;
3208 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003209 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3210 get_camera_metadata_size(sessionParams));
3211
Emilian Peev31abd0a2017-05-11 18:37:46 +01003212 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003213 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003214 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003215 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003216 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003217
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003218 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003219 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3220 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003221 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003222 };
3223
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003224 auto configStream36Cb = [&status, &finalConfiguration3_6]
3225 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3226 finalConfiguration3_6 = halConfiguration;
3227 status = s;
3228 };
3229
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003230 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3231 (hardware::Return<void>& err) -> status_t {
3232 if (!err.isOk()) {
3233 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3234 return DEAD_OBJECT;
3235 }
3236 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3237 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3238 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3239 }
3240 return OK;
3241 };
3242
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003243 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3244 (hardware::Return<void>& err) -> status_t {
3245 if (!err.isOk()) {
3246 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3247 return DEAD_OBJECT;
3248 }
3249 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3250 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3251 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3252 }
3253 return OK;
3254 };
3255
Shuzhen Wang92653952019-05-07 15:11:43 -07003256 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003257 if (mHidlSession_3_6 != nullptr) {
3258 ALOGV("%s: v3.6 device found", __FUNCTION__);
3259 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3260 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3261 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3262 auto err = mHidlSession_3_6->configureStreams_3_6(
3263 requestedConfiguration3_5, configStream36Cb);
3264 res = postprocConfigStream36(err);
3265 if (res != OK) {
3266 return res;
3267 }
3268 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003269 ALOGV("%s: v3.5 device found", __FUNCTION__);
3270 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3271 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3272 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3273 auto err = mHidlSession_3_5->configureStreams_3_5(
3274 requestedConfiguration3_5, configStream34Cb);
3275 res = postprocConfigStream34(err);
3276 if (res != OK) {
3277 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003278 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003279 } else if (mHidlSession_3_4 != nullptr) {
3280 // We do; use v3.4 for the call
3281 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003282 auto err = mHidlSession_3_4->configureStreams_3_4(
3283 requestedConfiguration3_4, configStream34Cb);
3284 res = postprocConfigStream34(err);
3285 if (res != OK) {
3286 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003287 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003288 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003289 // We do; use v3.3 for the call
3290 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003291 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003293 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003294 finalConfiguration = halConfiguration;
3295 status = s;
3296 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003297 if (!err.isOk()) {
3298 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3299 return DEAD_OBJECT;
3300 }
3301 } else {
3302 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3303 ALOGV("%s: v3.2 device found", __FUNCTION__);
3304 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003305 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003306 [&status, &finalConfiguration_3_2]
3307 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3308 finalConfiguration_3_2 = halConfiguration;
3309 status = s;
3310 });
3311 if (!err.isOk()) {
3312 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3313 return DEAD_OBJECT;
3314 }
3315 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3316 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3317 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3318 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003319 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003320 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003321 }
3322
3323 if (status != common::V1_0::Status::OK ) {
3324 return CameraProviderManager::mapToStatusT(status);
3325 }
3326
3327 // And convert output stream configuration from HIDL
3328
3329 for (size_t i = 0; i < config->num_streams; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003330 camera3::camera_stream_t *dst = config->streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 int streamId = Camera3Stream::cast(dst)->getId();
3332
3333 // Start scan at i, with the assumption that the stream order matches
3334 size_t realIdx = i;
3335 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003336 size_t halStreamCount = finalConfiguration.streams.size();
3337 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003338 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003339 found = true;
3340 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003341 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003342 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003343 }
3344 if (!found) {
3345 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3346 __FUNCTION__, streamId);
3347 return INVALID_OPERATION;
3348 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003349 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003350 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003351
Emilian Peev710c1422017-08-30 11:19:38 +01003352 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003353 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3354 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3355
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003356 if (mHidlSession_3_6 != nullptr) {
3357 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3358 }
3359
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003360 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003361 dstStream->setFormatOverride(false);
3362 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003363 if (dst->format != overrideFormat) {
3364 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3365 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003366 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003367 if (dst->data_space != overrideDataSpace) {
3368 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3369 streamId, dst->format);
3370 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003371 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003372 bool needFormatOverride =
3373 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3374 bool needDataspaceOverride =
3375 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003376 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003377 dstStream->setFormatOverride(needFormatOverride);
3378 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003379 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003380 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003381 }
3382
Emilian Peevf4816702020-04-03 15:44:51 -07003383 if (dst->stream_type == CAMERA_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003384 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003385 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003386 __FUNCTION__, streamId);
3387 return INVALID_OPERATION;
3388 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003389 dstStream->setUsage(
3390 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003391 } else {
3392 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003393 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003394 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3395 __FUNCTION__, streamId);
3396 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003397 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003398 dstStream->setUsage(
3399 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003400 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003401 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003402 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003403
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003404 return res;
3405}
3406
Emilian Peevf4816702020-04-03 15:44:51 -07003407status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003408 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003409 /*out*/std::vector<native_handle_t*>* handlesCreated,
3410 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003411 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003412 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3413 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3414 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003415 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003416 }
3417
3418 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003419
3420 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003421
3422 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003423 if (request->input_buffer != nullptr) {
3424 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3425 buffer_handle_t buf = *(request->input_buffer->buffer);
3426 auto pair = getBufferId(buf, streamId);
3427 bool isNewBuffer = pair.first;
3428 uint64_t bufferId = pair.second;
3429 captureRequest->inputBuffer.streamId = streamId;
3430 captureRequest->inputBuffer.bufferId = bufferId;
3431 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3432 captureRequest->inputBuffer.status = BufferStatus::OK;
3433 native_handle_t *acquireFence = nullptr;
3434 if (request->input_buffer->acquire_fence != -1) {
3435 acquireFence = native_handle_create(1,0);
3436 acquireFence->data[0] = request->input_buffer->acquire_fence;
3437 handlesCreated->push_back(acquireFence);
3438 }
3439 captureRequest->inputBuffer.acquireFence = acquireFence;
3440 captureRequest->inputBuffer.releaseFence = nullptr;
3441
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003442 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003443 request->input_buffer->buffer);
3444 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003445 } else {
3446 captureRequest->inputBuffer.streamId = -1;
3447 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3448 }
3449
3450 captureRequest->outputBuffers.resize(request->num_output_buffers);
3451 for (size_t i = 0; i < request->num_output_buffers; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003452 const camera_stream_buffer_t *src = request->output_buffers + i;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003453 StreamBuffer &dst = captureRequest->outputBuffers[i];
3454 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003455 if (src->buffer != nullptr) {
3456 buffer_handle_t buf = *(src->buffer);
3457 auto pair = getBufferId(buf, streamId);
3458 bool isNewBuffer = pair.first;
3459 dst.bufferId = pair.second;
3460 dst.buffer = isNewBuffer ? buf : nullptr;
3461 native_handle_t *acquireFence = nullptr;
3462 if (src->acquire_fence != -1) {
3463 acquireFence = native_handle_create(1,0);
3464 acquireFence->data[0] = src->acquire_fence;
3465 handlesCreated->push_back(acquireFence);
3466 }
3467 dst.acquireFence = acquireFence;
3468 } else if (mUseHalBufManager) {
3469 // HAL buffer management path
3470 dst.bufferId = BUFFER_ID_NO_BUFFER;
3471 dst.buffer = nullptr;
3472 dst.acquireFence = nullptr;
3473 } else {
3474 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3475 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003476 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003477 dst.streamId = streamId;
3478 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003479 dst.releaseFence = nullptr;
3480
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003481 // Output buffers are empty when using HAL buffer manager
3482 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003483 mBufferRecords.pushInflightBuffer(
3484 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003485 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003486 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003487 }
3488 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003489 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003490}
3491
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003492void Camera3Device::HalInterface::cleanupNativeHandles(
3493 std::vector<native_handle_t*> *handles, bool closeFd) {
3494 if (handles == nullptr) {
3495 return;
3496 }
3497 if (closeFd) {
3498 for (auto& handle : *handles) {
3499 native_handle_close(handle);
3500 }
3501 }
3502 for (auto& handle : *handles) {
3503 native_handle_delete(handle);
3504 }
3505 handles->clear();
3506 return;
3507}
3508
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003509status_t Camera3Device::HalInterface::processBatchCaptureRequests(
Emilian Peevf4816702020-04-03 15:44:51 -07003510 std::vector<camera_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003511 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3512 if (!valid()) return INVALID_OPERATION;
3513
Emilian Peevaebbe412018-01-15 13:53:24 +00003514 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3515 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3516 if (castResult_3_4.isOk()) {
3517 hidlSession_3_4 = castResult_3_4;
3518 }
3519
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003520 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003521 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003522 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003523 if (hidlSession_3_4 != nullptr) {
3524 captureRequests_3_4.resize(batchSize);
3525 } else {
3526 captureRequests.resize(batchSize);
3527 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003528 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003529 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003530
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003531 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003532 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003533 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003534 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003535 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003536 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003537 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3538 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003539 }
3540 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003541 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003542 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003543 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003544 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003545 }
3546
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003547 std::vector<device::V3_2::BufferCache> cachesToRemove;
3548 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003549 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003550 for (auto& pair : mFreedBuffers) {
3551 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003552 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003553 cachesToRemove.push_back({pair.first, pair.second});
3554 }
3555 }
3556 mFreedBuffers.clear();
3557 }
3558
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003559 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3560 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003561
3562 // Write metadata to FMQ.
3563 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevf4816702020-04-03 15:44:51 -07003564 camera_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003565 device::V3_2::CaptureRequest* captureRequest;
3566 if (hidlSession_3_4 != nullptr) {
3567 captureRequest = &captureRequests_3_4[i].v3_2;
3568 } else {
3569 captureRequest = &captureRequests[i];
3570 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003571
3572 if (request->settings != nullptr) {
3573 size_t settingsSize = get_camera_metadata_size(request->settings);
3574 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3575 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3576 captureRequest->settings.resize(0);
3577 captureRequest->fmqSettingsSize = settingsSize;
3578 } else {
3579 if (mRequestMetadataQueue != nullptr) {
3580 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3581 }
3582 captureRequest->settings.setToExternal(
3583 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3584 get_camera_metadata_size(request->settings));
3585 captureRequest->fmqSettingsSize = 0u;
3586 }
3587 } else {
3588 // A null request settings maps to a size-0 CameraMetadata
3589 captureRequest->settings.resize(0);
3590 captureRequest->fmqSettingsSize = 0u;
3591 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003592
3593 if (hidlSession_3_4 != nullptr) {
3594 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3595 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003596 if (request->physcam_settings != nullptr) {
3597 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3598 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3599 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3600 settingsSize)) {
3601 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3602 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3603 settingsSize;
3604 } else {
3605 if (mRequestMetadataQueue != nullptr) {
3606 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3607 }
3608 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3609 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3610 request->physcam_settings[j])),
3611 get_camera_metadata_size(request->physcam_settings[j]));
3612 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003613 }
Emilian Peev00420d22018-02-05 21:33:13 +00003614 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003615 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003616 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003617 }
3618 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3619 request->physcam_id[j];
3620 }
3621 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003622 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003623
3624 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003625 auto resultCallback =
3626 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3627 status = s;
3628 *numRequestProcessed = n;
3629 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003630 if (hidlSession_3_4 != nullptr) {
3631 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003632 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003633 } else {
3634 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003635 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003636 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003637 if (!err.isOk()) {
3638 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003639 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003640 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003641
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003642 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3643 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3644 __FUNCTION__, *numRequestProcessed, batchSize);
3645 status = common::V1_0::Status::INTERNAL_ERROR;
3646 }
3647
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003648 res = CameraProviderManager::mapToStatusT(status);
3649 if (res == OK) {
3650 if (mHidlSession->isRemote()) {
3651 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3652 // sent to camera HAL processes)
3653 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3654 } else {
3655 // In passthrough mode the FDs are now owned by HAL
3656 cleanupNativeHandles(&handlesCreated);
3657 }
3658 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003659 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003660 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003661 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003662 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003663}
3664
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003665status_t Camera3Device::HalInterface::flush() {
3666 ATRACE_NAME("CameraHal::flush");
3667 if (!valid()) return INVALID_OPERATION;
3668 status_t res = OK;
3669
Emilian Peev31abd0a2017-05-11 18:37:46 +01003670 auto err = mHidlSession->flush();
3671 if (!err.isOk()) {
3672 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3673 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003674 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003675 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003676 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003677
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003678 return res;
3679}
3680
Emilian Peev31abd0a2017-05-11 18:37:46 +01003681status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003682 ATRACE_NAME("CameraHal::dump");
3683 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003684
Emilian Peev31abd0a2017-05-11 18:37:46 +01003685 // Handled by CameraProviderManager::dump
3686
3687 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003688}
3689
3690status_t Camera3Device::HalInterface::close() {
3691 ATRACE_NAME("CameraHal::close()");
3692 if (!valid()) return INVALID_OPERATION;
3693 status_t res = OK;
3694
Emilian Peev31abd0a2017-05-11 18:37:46 +01003695 auto err = mHidlSession->close();
3696 // Interface will be dead shortly anyway, so don't log errors
3697 if (!err.isOk()) {
3698 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003699 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003700
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003701 return res;
3702}
3703
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003704void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3705 ATRACE_NAME("CameraHal::signalPipelineDrain");
3706 if (!valid() || mHidlSession_3_5 == nullptr) {
3707 ALOGE("%s called on invalid camera!", __FUNCTION__);
3708 return;
3709 }
3710
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003711 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003712 if (!err.isOk()) {
3713 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3714 return;
3715 }
3716}
3717
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003718status_t Camera3Device::HalInterface::switchToOffline(
3719 const std::vector<int32_t>& streamsToKeep,
3720 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003721 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3722 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003723 ATRACE_NAME("CameraHal::switchToOffline");
3724 if (!valid() || mHidlSession_3_6 == nullptr) {
3725 ALOGE("%s called on invalid camera!", __FUNCTION__);
3726 return INVALID_OPERATION;
3727 }
3728
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003729 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3730 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003731 return INVALID_OPERATION;
3732 }
3733
3734 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003735 auto resultCallback =
3736 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3737 status = s;
3738 *offlineSessionInfo = info;
3739 *offlineSession = session;
3740 };
3741 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3742
3743 if (!err.isOk()) {
3744 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3745 return DEAD_OBJECT;
3746 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003747
3748 status_t ret = CameraProviderManager::mapToStatusT(status);
3749 if (ret != OK) {
3750 return ret;
3751 }
3752
3753 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3754 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3755 // returns from switchToOffline.
3756
3757
3758 // Validate buffer caches
3759 std::vector<int32_t> streams;
3760 streams.reserve(offlineSessionInfo->offlineStreams.size());
3761 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3762 int32_t id = offlineStream.id;
3763 streams.push_back(id);
3764 // Verify buffer caches
3765 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3766 offlineStream.circulatingBufferIds.end());
3767 if (!verifyBufferIds(id, bufIds)) {
3768 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3769 return UNKNOWN_ERROR;
3770 }
3771 }
3772
3773 // Move buffer records
3774 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3775 bufferRecords->takeInflightBufferMap(mBufferRecords);
3776 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3777 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003778}
3779
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003780void Camera3Device::HalInterface::getInflightBufferKeys(
3781 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003782 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003783 return;
3784}
3785
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003786void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3787 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003788 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003789 return;
3790}
3791
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003792bool Camera3Device::HalInterface::verifyBufferIds(
3793 int32_t streamId, std::vector<uint64_t>& bufIds) {
3794 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003795}
3796
3797status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003798 int32_t frameNumber, int32_t streamId,
3799 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003800 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003801}
3802
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003803status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003804 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003805 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003806}
3807
3808// Find and pop a buffer_handle_t based on bufferId
3809status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003810 uint64_t bufferId,
3811 /*out*/ buffer_handle_t** buffer,
3812 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003813 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003814}
3815
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003816std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3817 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003818 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003819}
3820
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003821void Camera3Device::HalInterface::onBufferFreed(
3822 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003823 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3824 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3825 if (bufferId != BUFFER_ID_NO_BUFFER) {
3826 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003827 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003828}
3829
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003830void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003831 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3832 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3833 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003834 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3835 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003836}
3837
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003838/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003839 * RequestThread inner class methods
3840 */
3841
3842Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003843 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003844 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3845 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003846 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003847 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003848 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003849 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003850 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003851 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003852 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003853 mReconfigured(false),
3854 mDoPause(false),
3855 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003856 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003857 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003858 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003859 mCurrentAfTriggerId(0),
3860 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003861 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003862 mRepeatingLastFrameNumber(
3863 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003864 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003865 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003866 mRequestLatency(kRequestLatencyBinSize),
3867 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003868 mLatestSessionParams(sessionParamKeys.size()),
3869 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003870 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003871}
3872
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003873Camera3Device::RequestThread::~RequestThread() {}
3874
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003875void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003876 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003877 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003878 Mutex::Autolock l(mRequestLock);
3879 mListener = listener;
3880}
3881
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003882void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3883 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003884 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003885 Mutex::Autolock l(mRequestLock);
3886 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003887 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003888 // Prepare video stream for high speed recording.
3889 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003890 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003891}
3892
Jianing Wei90e59c92014-03-12 18:29:36 -07003893status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003894 List<sp<CaptureRequest> > &requests,
3895 /*out*/
3896 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003897 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003898 Mutex::Autolock l(mRequestLock);
3899 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3900 ++it) {
3901 mRequestQueue.push_back(*it);
3902 }
3903
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003904 if (lastFrameNumber != NULL) {
3905 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3906 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3907 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3908 *lastFrameNumber);
3909 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003910
Jianing Wei90e59c92014-03-12 18:29:36 -07003911 unpauseForNewRequests();
3912
3913 return OK;
3914}
3915
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003916
3917status_t Camera3Device::RequestThread::queueTrigger(
3918 RequestTrigger trigger[],
3919 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003920 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003921 Mutex::Autolock l(mTriggerMutex);
3922 status_t ret;
3923
3924 for (size_t i = 0; i < count; ++i) {
3925 ret = queueTriggerLocked(trigger[i]);
3926
3927 if (ret != OK) {
3928 return ret;
3929 }
3930 }
3931
3932 return OK;
3933}
3934
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003935const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3936 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003937 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003938 if (d != nullptr) return d->mId;
3939 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003940}
3941
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003942status_t Camera3Device::RequestThread::queueTriggerLocked(
3943 RequestTrigger trigger) {
3944
3945 uint32_t tag = trigger.metadataTag;
3946 ssize_t index = mTriggerMap.indexOfKey(tag);
3947
3948 switch (trigger.getTagType()) {
3949 case TYPE_BYTE:
3950 // fall-through
3951 case TYPE_INT32:
3952 break;
3953 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003954 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3955 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003956 return INVALID_OPERATION;
3957 }
3958
3959 /**
3960 * Collect only the latest trigger, since we only have 1 field
3961 * in the request settings per trigger tag, and can't send more than 1
3962 * trigger per request.
3963 */
3964 if (index != NAME_NOT_FOUND) {
3965 mTriggerMap.editValueAt(index) = trigger;
3966 } else {
3967 mTriggerMap.add(tag, trigger);
3968 }
3969
3970 return OK;
3971}
3972
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003973status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003974 const RequestList &requests,
3975 /*out*/
3976 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003977 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003978 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003979 if (lastFrameNumber != NULL) {
3980 *lastFrameNumber = mRepeatingLastFrameNumber;
3981 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003982 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003983 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003984 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3985 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003986
3987 unpauseForNewRequests();
3988
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003989 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003990 return OK;
3991}
3992
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003993bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003994 if (mRepeatingRequests.empty()) {
3995 return false;
3996 }
3997 int32_t requestId = requestIn->mResultExtras.requestId;
3998 const RequestList &repeatRequests = mRepeatingRequests;
3999 // All repeating requests are guaranteed to have same id so only check first quest
4000 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4001 return (firstRequest->mResultExtras.requestId == requestId);
4002}
4003
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004004status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004005 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004006 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004007 return clearRepeatingRequestsLocked(lastFrameNumber);
4008
4009}
4010
4011status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004012 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004013 if (lastFrameNumber != NULL) {
4014 *lastFrameNumber = mRepeatingLastFrameNumber;
4015 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004016 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004017 return OK;
4018}
4019
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004020status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004021 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004022 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004023 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004024 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004025
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004026 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004027
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004028 // Send errors for all requests pending in the request queue, including
4029 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004030 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004031 if (listener != NULL) {
4032 for (RequestList::iterator it = mRequestQueue.begin();
4033 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004034 // Abort the input buffers for reprocess requests.
4035 if ((*it)->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004036 camera_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004037 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4038 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004039 if (res != OK) {
4040 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4041 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4042 } else {
Emilian Peevf4816702020-04-03 15:44:51 -07004043 inputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004044 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4045 if (res != OK) {
4046 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4047 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4048 }
4049 }
4050 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004051 // Set the frame number this request would have had, if it
4052 // had been submitted; this frame number will not be reused.
4053 // The requestId and burstId fields were set when the request was
4054 // submitted originally (in convertMetadataListToRequestListLocked)
4055 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004056 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004057 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004058 }
4059 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004060 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004061
4062 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004063 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004064 if (lastFrameNumber != NULL) {
4065 *lastFrameNumber = mRepeatingLastFrameNumber;
4066 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004067 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004068 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004069 return OK;
4070}
4071
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004072status_t Camera3Device::RequestThread::flush() {
4073 ATRACE_CALL();
4074 Mutex::Autolock l(mFlushLock);
4075
Emilian Peev08dd2452017-04-06 16:55:14 +01004076 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004077}
4078
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004079void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004080 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004081 Mutex::Autolock l(mPauseLock);
4082 mDoPause = paused;
4083 mDoPauseSignal.signal();
4084}
4085
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004086status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4087 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004088 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004089 Mutex::Autolock l(mLatestRequestMutex);
4090 status_t res;
4091 while (mLatestRequestId != requestId) {
4092 nsecs_t startTime = systemTime();
4093
4094 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4095 if (res != OK) return res;
4096
4097 timeout -= (systemTime() - startTime);
4098 }
4099
4100 return OK;
4101}
4102
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004103void Camera3Device::RequestThread::requestExit() {
4104 // Call parent to set up shutdown
4105 Thread::requestExit();
4106 // The exit from any possible waits
4107 mDoPauseSignal.signal();
4108 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004109
4110 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4111 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004112}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004113
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004114void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004115 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004116 bool surfaceAbandoned = false;
4117 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004118 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004119 {
4120 Mutex::Autolock l(mRequestLock);
4121 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4122 // repeating requests.
4123 for (const auto& request : mRepeatingRequests) {
4124 for (const auto& s : request->mOutputStreams) {
4125 if (s->isAbandoned()) {
4126 surfaceAbandoned = true;
4127 clearRepeatingRequestsLocked(&lastFrameNumber);
4128 break;
4129 }
4130 }
4131 if (surfaceAbandoned) {
4132 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004133 }
4134 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004135 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004136 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004137
4138 if (listener != NULL && surfaceAbandoned) {
4139 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004140 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004141}
4142
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004143bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004144 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004145 status_t res;
4146 size_t batchSize = mNextRequests.size();
Emilian Peevf4816702020-04-03 15:44:51 -07004147 std::vector<camera_capture_request_t*> requests(batchSize);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004148 uint32_t numRequestProcessed = 0;
4149 for (size_t i = 0; i < batchSize; i++) {
4150 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004151 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004152 }
4153
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004154 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4155
4156 bool triggerRemoveFailed = false;
4157 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4158 for (size_t i = 0; i < numRequestProcessed; i++) {
4159 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4160 nextRequest.submitted = true;
4161
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004162 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004163
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004164 if (!triggerRemoveFailed) {
4165 // Remove any previously queued triggers (after unlock)
4166 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4167 if (removeTriggerRes != OK) {
4168 triggerRemoveFailed = true;
4169 triggerFailedRequest = nextRequest;
4170 }
4171 }
4172 }
4173
4174 if (triggerRemoveFailed) {
4175 SET_ERR("RequestThread: Unable to remove triggers "
4176 "(capture request %d, HAL device: %s (%d)",
4177 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4178 cleanUpFailedRequests(/*sendRequestError*/ false);
4179 return false;
4180 }
4181
4182 if (res != OK) {
4183 // Should only get a failure here for malformed requests or device-level
4184 // errors, so consider all errors fatal. Bad metadata failures should
4185 // come through notify.
4186 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4187 mNextRequests[numRequestProcessed].halRequest.frame_number,
4188 strerror(-res), res);
4189 cleanUpFailedRequests(/*sendRequestError*/ false);
4190 return false;
4191 }
4192 return true;
4193}
4194
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004195nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4196 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4197 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4198 find_camera_metadata_ro_entry(request,
4199 ANDROID_CONTROL_AE_MODE,
4200 &e);
4201 if (e.count == 0) return maxExpectedDuration;
4202
4203 switch (e.data.u8[0]) {
4204 case ANDROID_CONTROL_AE_MODE_OFF:
4205 find_camera_metadata_ro_entry(request,
4206 ANDROID_SENSOR_EXPOSURE_TIME,
4207 &e);
4208 if (e.count > 0) {
4209 maxExpectedDuration = e.data.i64[0];
4210 }
4211 find_camera_metadata_ro_entry(request,
4212 ANDROID_SENSOR_FRAME_DURATION,
4213 &e);
4214 if (e.count > 0) {
4215 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4216 }
4217 break;
4218 default:
4219 find_camera_metadata_ro_entry(request,
4220 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4221 &e);
4222 if (e.count > 1) {
4223 maxExpectedDuration = 1e9 / e.data.u8[0];
4224 }
4225 break;
4226 }
4227
4228 return maxExpectedDuration;
4229}
4230
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004231bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4232 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4233 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4234 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4235 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4236 return true;
4237 }
4238
4239 return false;
4240}
4241
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004242void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4243 // Update the latest request sent to HAL
4244 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4245 Mutex::Autolock al(mLatestRequestMutex);
4246
4247 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4248 mLatestRequest.acquire(cloned);
4249
4250 mLatestPhysicalRequest.clear();
4251 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4252 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4253 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4254 CameraMetadata(cloned));
4255 }
4256
4257 sp<Camera3Device> parent = mParent.promote();
4258 if (parent != NULL) {
4259 parent->monitorMetadata(TagMonitor::REQUEST,
4260 nextRequest.halRequest.frame_number,
4261 0, mLatestRequest, mLatestPhysicalRequest);
4262 }
4263 }
4264
4265 if (nextRequest.halRequest.settings != NULL) {
4266 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4267 nextRequest.halRequest.settings);
4268 }
4269
4270 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4271}
4272
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004273bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4274 ATRACE_CALL();
4275 bool updatesDetected = false;
4276
Emilian Peev4ec17882019-01-24 17:16:58 -08004277 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004278 for (auto tag : mSessionParamKeys) {
4279 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004280 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004281
4282 if (entry.count > 0) {
4283 bool isDifferent = false;
4284 if (lastEntry.count > 0) {
4285 // Have a last value, compare to see if changed
4286 if (lastEntry.type == entry.type &&
4287 lastEntry.count == entry.count) {
4288 // Same type and count, compare values
4289 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4290 size_t entryBytes = bytesPerValue * lastEntry.count;
4291 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4292 if (cmp != 0) {
4293 isDifferent = true;
4294 }
4295 } else {
4296 // Count or type has changed
4297 isDifferent = true;
4298 }
4299 } else {
4300 // No last entry, so always consider to be different
4301 isDifferent = true;
4302 }
4303
4304 if (isDifferent) {
4305 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004306 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4307 updatesDetected = true;
4308 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004309 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004310 }
4311 } else if (lastEntry.count > 0) {
4312 // Value has been removed
4313 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004314 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004315 updatesDetected = true;
4316 }
4317 }
4318
Emilian Peev4ec17882019-01-24 17:16:58 -08004319 bool reconfigureRequired;
4320 if (updatesDetected) {
4321 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4322 updatedParams);
4323 mLatestSessionParams = updatedParams;
4324 } else {
4325 reconfigureRequired = false;
4326 }
4327
4328 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004329}
4330
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004332 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004333 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004334 // Any function called from threadLoop() must not hold mInterfaceLock since
4335 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4336 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337
4338 // Handle paused state.
4339 if (waitIfPaused()) {
4340 return true;
4341 }
4342
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004343 // Wait for the next batch of requests.
4344 waitForNextRequestBatch();
4345 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004346 return true;
4347 }
4348
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004349 // Get the latest request ID, if any
4350 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004351 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004352 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004353 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004354 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004355 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4357 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004358 }
4359
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004360 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4361 // or a single request from streaming or burst. In either case the first element
4362 // should contain the latest camera settings that we need to check for any session
4363 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004364 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004365 res = OK;
4366
4367 //Input stream buffers are already acquired at this point so an input stream
4368 //will not be able to move to idle state unless we force it.
4369 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4370 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4371 if (res != OK) {
4372 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4373 cleanUpFailedRequests(/*sendRequestError*/ false);
4374 return false;
4375 }
4376 }
4377
4378 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004379 sp<Camera3Device> parent = mParent.promote();
4380 if (parent != nullptr) {
4381 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004382 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004383 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004384
4385 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4386 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4387 if (res != OK) {
4388 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4389 cleanUpFailedRequests(/*sendRequestError*/ false);
4390 return false;
4391 }
4392 }
4393 }
4394 }
4395
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004396 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004397 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004398 if (res == TIMED_OUT) {
4399 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004400 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004401 // Check if any stream is abandoned.
4402 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004403 return true;
4404 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004405 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004406 return false;
4407 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004408
Zhijun Hecc27e112013-10-03 16:12:43 -07004409 // Inform waitUntilRequestProcessed thread of a new request ID
4410 {
4411 Mutex::Autolock al(mLatestRequestMutex);
4412
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004413 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004414 mLatestRequestSignal.signal();
4415 }
4416
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004417 // Submit a batch of requests to HAL.
4418 // Use flush lock only when submitting multilple requests in a batch.
4419 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4420 // which may take a long time to finish so synchronizing flush() and
4421 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4422 // For now, only synchronize for high speed recording and we should figure something out for
4423 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004424 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004425
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004426 if (useFlushLock) {
4427 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004428 }
4429
Zhijun Hef0645c12016-08-02 00:58:11 -07004430 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004431 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004432
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004433 sp<Camera3Device> parent = mParent.promote();
4434 if (parent != nullptr) {
4435 parent->mRequestBufferSM.onSubmittingRequest();
4436 }
4437
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004438 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004439 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004440 submitRequestSuccess = sendRequestsBatch();
4441
Shuzhen Wang686f6442017-06-20 16:16:04 -07004442 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4443 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004444
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004445 if (useFlushLock) {
4446 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004447 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004448
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004449 // Unset as current request
4450 {
4451 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004452 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004453 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004454 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004455
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004456 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457}
4458
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004459status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004460 ATRACE_CALL();
4461
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004462 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004463 for (size_t i = 0; i < mNextRequests.size(); i++) {
4464 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004465 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004466 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4467 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004468
4469 // Prepare a request to HAL
4470 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4471
4472 // Insert any queued triggers (before metadata is locked)
4473 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004474 if (res < 0) {
4475 SET_ERR("RequestThread: Unable to insert triggers "
4476 "(capture request %d, HAL device: %s (%d)",
4477 halRequest->frame_number, strerror(-res), res);
4478 return INVALID_OPERATION;
4479 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004480
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004481 int triggerCount = res;
4482 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4483 mPrevTriggers = triggerCount;
4484
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004485 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4486
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004487 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004488 bool newRequest =
4489 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004490 // Request settings are all the same within one batch, so only treat the first
4491 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004492 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004493 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004494 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004495 /**
4496 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004497 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004498 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004499 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004500 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004501 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004502 "(capture request %d, HAL device: %s (%d)",
4503 halRequest->frame_number, strerror(-res), res);
4504 return INVALID_OPERATION;
4505 }
4506
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004507 {
4508 // Correct metadata regions for distortion correction if enabled
4509 sp<Camera3Device> parent = mParent.promote();
4510 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004511 List<PhysicalCameraSettings>::iterator it;
4512 for (it = captureRequest->mSettingsList.begin();
4513 it != captureRequest->mSettingsList.end(); it++) {
4514 if (parent->mDistortionMappers.find(it->cameraId) ==
4515 parent->mDistortionMappers.end()) {
4516 continue;
4517 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004518
4519 if (!captureRequest->mDistortionCorrectionUpdated) {
4520 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4521 &(it->metadata));
4522 if (res != OK) {
4523 SET_ERR("RequestThread: Unable to correct capture requests "
4524 "for lens distortion for request %d: %s (%d)",
4525 halRequest->frame_number, strerror(-res), res);
4526 return INVALID_OPERATION;
4527 }
4528 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004529 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004530 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004531
4532 for (it = captureRequest->mSettingsList.begin();
4533 it != captureRequest->mSettingsList.end(); it++) {
4534 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4535 parent->mZoomRatioMappers.end()) {
4536 continue;
4537 }
4538
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004539 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004540 cameraIdsWithZoom.insert(it->cameraId);
4541 }
4542
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004543 if (!captureRequest->mZoomRatioUpdated) {
4544 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4545 &(it->metadata));
4546 if (res != OK) {
4547 SET_ERR("RequestThread: Unable to correct capture requests "
4548 "for zoom ratio for request %d: %s (%d)",
4549 halRequest->frame_number, strerror(-res), res);
4550 return INVALID_OPERATION;
4551 }
4552 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004553 }
4554 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004555 if (captureRequest->mRotateAndCropAuto &&
4556 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004557 for (it = captureRequest->mSettingsList.begin();
4558 it != captureRequest->mSettingsList.end(); it++) {
4559 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4560 if (mapper != parent->mRotateAndCropMappers.end()) {
4561 res = mapper->second.updateCaptureRequest(&(it->metadata));
4562 if (res != OK) {
4563 SET_ERR("RequestThread: Unable to correct capture requests "
4564 "for rotate-and-crop for request %d: %s (%d)",
4565 halRequest->frame_number, strerror(-res), res);
4566 return INVALID_OPERATION;
4567 }
4568 }
4569 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004570 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004571 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004572 }
4573 }
4574
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004575 /**
4576 * The request should be presorted so accesses in HAL
4577 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4578 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004579 captureRequest->mSettingsList.begin()->metadata.sort();
4580 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004581 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004582 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004583 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4584
4585 IF_ALOGV() {
4586 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4587 find_camera_metadata_ro_entry(
4588 halRequest->settings,
4589 ANDROID_CONTROL_AF_TRIGGER,
4590 &e
4591 );
4592 if (e.count > 0) {
4593 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4594 __FUNCTION__,
4595 halRequest->frame_number,
4596 e.data.u8[0]);
4597 }
4598 }
4599 } else {
4600 // leave request.settings NULL to indicate 'reuse latest given'
4601 ALOGVV("%s: Request settings are REUSED",
4602 __FUNCTION__);
4603 }
4604
Emilian Peevaebbe412018-01-15 13:53:24 +00004605 if (captureRequest->mSettingsList.size() > 1) {
4606 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4607 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004608 if (newRequest) {
4609 halRequest->physcam_settings =
4610 new const camera_metadata* [halRequest->num_physcam_settings];
4611 } else {
4612 halRequest->physcam_settings = nullptr;
4613 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004614 auto it = ++captureRequest->mSettingsList.begin();
4615 size_t i = 0;
4616 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4617 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004618 if (newRequest) {
4619 it->metadata.sort();
4620 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4621 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004622 }
4623 }
4624
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004625 uint32_t totalNumBuffers = 0;
4626
4627 // Fill in buffers
4628 if (captureRequest->mInputStream != NULL) {
4629 halRequest->input_buffer = &captureRequest->mInputBuffer;
4630 totalNumBuffers += 1;
4631 } else {
4632 halRequest->input_buffer = NULL;
4633 }
4634
Emilian Peevf4816702020-04-03 15:44:51 -07004635 outputBuffers->insertAt(camera_stream_buffer_t(), 0,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004636 captureRequest->mOutputStreams.size());
4637 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004638 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004639
4640 sp<Camera3Device> parent = mParent.promote();
4641 if (parent == NULL) {
4642 // Should not happen, and nowhere to send errors to, so just log it
4643 CLOGE("RequestThread: Parent is gone");
4644 return INVALID_OPERATION;
4645 }
4646 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4647
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004648 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004649 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004650 sp<Camera3OutputStreamInterface> outputStream =
4651 captureRequest->mOutputStreams.editItemAt(j);
4652 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004653
4654 // Prepare video buffers for high speed recording on the first video request.
4655 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4656 // Only try to prepare video stream on the first video request.
4657 mPrepareVideoStream = false;
4658
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004659 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4660 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004661 while (res == NOT_ENOUGH_DATA) {
4662 res = outputStream->prepareNextBuffer();
4663 }
4664 if (res != OK) {
4665 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4666 __FUNCTION__, strerror(-res), res);
4667 outputStream->cancelPrepare();
4668 }
4669 }
4670
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004671 std::vector<size_t> uniqueSurfaceIds;
4672 res = outputStream->getUniqueSurfaceIds(
4673 captureRequest->mOutputSurfaces[streamId],
4674 &uniqueSurfaceIds);
4675 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4676 if (res != OK && res != INVALID_OPERATION) {
4677 ALOGE("%s: failed to query stream %d unique surface IDs",
4678 __FUNCTION__, streamId);
4679 return res;
4680 }
4681 if (res == OK) {
4682 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4683 }
4684
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004685 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004686 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004687 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004688 return TIMED_OUT;
4689 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004690 // HAL will request buffer through requestStreamBuffer API
Emilian Peevf4816702020-04-03 15:44:51 -07004691 camera_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004692 buffer.stream = outputStream->asHalStream();
4693 buffer.buffer = nullptr;
Emilian Peevf4816702020-04-03 15:44:51 -07004694 buffer.status = CAMERA_BUFFER_STATUS_OK;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004695 buffer.acquire_fence = -1;
4696 buffer.release_fence = -1;
4697 } else {
4698 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4699 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004700 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004701 if (res != OK) {
4702 // Can't get output buffer from gralloc queue - this could be due to
4703 // abandoned queue or other consumer misbehavior, so not a fatal
4704 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004705 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004706 " %s (%d)", strerror(-res), res);
4707
4708 return TIMED_OUT;
4709 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004710 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004711
4712 {
4713 sp<Camera3Device> parent = mParent.promote();
4714 if (parent != nullptr) {
4715 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4716 for (const auto& settings : captureRequest->mSettingsList) {
4717 if ((streamCameraId.isEmpty() &&
4718 parent->getId() == settings.cameraId.c_str()) ||
4719 streamCameraId == settings.cameraId.c_str()) {
4720 outputStream->fireBufferRequestForFrameNumber(
4721 captureRequest->mResultExtras.frameNumber,
4722 settings.metadata);
4723 }
4724 }
4725 }
4726 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004727
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004728 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4729
4730 if (!physicalCameraId.isEmpty()) {
4731 // Physical stream isn't supported for input request.
4732 if (halRequest->input_buffer) {
4733 CLOGE("Physical stream is not supported for input request");
4734 return INVALID_OPERATION;
4735 }
4736 requestedPhysicalCameras.insert(physicalCameraId);
4737 }
4738 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004739 }
4740 totalNumBuffers += halRequest->num_output_buffers;
4741
4742 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004743 // If this request list is for constrained high speed recording (not
4744 // preview), and the current request is not the last one in the batch,
4745 // do not send callback to the app.
4746 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004747 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004748 hasCallback = false;
4749 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004750 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004751 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004752 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4753 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4754 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4755 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4756 isStillCapture = true;
4757 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4758 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004759
4760 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4761 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4762 isZslCapture = true;
4763 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004764 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004765 res = parent->registerInFlight(halRequest->frame_number,
4766 totalNumBuffers, captureRequest->mResultExtras,
4767 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004768 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004769 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004770 requestedPhysicalCameras, isStillCapture, isZslCapture,
4771 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004772 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004773 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004774 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4775 ", burstId = %" PRId32 ".",
4776 __FUNCTION__,
4777 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4778 captureRequest->mResultExtras.burstId);
4779 if (res != OK) {
4780 SET_ERR("RequestThread: Unable to register new in-flight request:"
4781 " %s (%d)", strerror(-res), res);
4782 return INVALID_OPERATION;
4783 }
4784 }
4785
4786 return OK;
4787}
4788
Igor Murashkin1e479c02013-09-06 16:55:14 -07004789CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004790 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004791 Mutex::Autolock al(mLatestRequestMutex);
4792
4793 ALOGV("RequestThread::%s", __FUNCTION__);
4794
4795 return mLatestRequest;
4796}
4797
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004798bool Camera3Device::RequestThread::isStreamPending(
4799 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004800 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004801 Mutex::Autolock l(mRequestLock);
4802
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004803 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004804 if (!nextRequest.submitted) {
4805 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4806 if (stream == s) return true;
4807 }
4808 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004809 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004810 }
4811
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004812 for (const auto& request : mRequestQueue) {
4813 for (const auto& s : request->mOutputStreams) {
4814 if (stream == s) return true;
4815 }
4816 if (stream == request->mInputStream) return true;
4817 }
4818
4819 for (const auto& request : mRepeatingRequests) {
4820 for (const auto& s : request->mOutputStreams) {
4821 if (stream == s) return true;
4822 }
4823 if (stream == request->mInputStream) return true;
4824 }
4825
4826 return false;
4827}
Jianing Weicb0652e2014-03-12 18:29:36 -07004828
Emilian Peev40ead602017-09-26 15:46:36 +01004829bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4830 ATRACE_CALL();
4831 Mutex::Autolock l(mRequestLock);
4832
4833 for (const auto& nextRequest : mNextRequests) {
4834 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4835 if (s.first == streamId) {
4836 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4837 if (it != s.second.end()) {
4838 return true;
4839 }
4840 }
4841 }
4842 }
4843
4844 for (const auto& request : mRequestQueue) {
4845 for (const auto& s : request->mOutputSurfaces) {
4846 if (s.first == streamId) {
4847 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4848 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004849 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004850 }
4851 }
4852 }
4853 }
4854
4855 for (const auto& request : mRepeatingRequests) {
4856 for (const auto& s : request->mOutputSurfaces) {
4857 if (s.first == streamId) {
4858 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4859 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004860 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004861 }
4862 }
4863 }
4864 }
4865
4866 return false;
4867}
4868
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004869void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4870 if (!mUseHalBufManager) {
4871 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4872 return;
4873 }
4874
4875 Mutex::Autolock pl(mPauseLock);
4876 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004877 mInterface->signalPipelineDrain(streamIds);
4878 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004879 }
4880 // If request thread is still busy, wait until paused then notify HAL
4881 mNotifyPipelineDrain = true;
4882 mStreamIdsToBeDrained = streamIds;
4883}
4884
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004885void Camera3Device::RequestThread::resetPipelineDrain() {
4886 Mutex::Autolock pl(mPauseLock);
4887 mNotifyPipelineDrain = false;
4888 mStreamIdsToBeDrained.clear();
4889}
4890
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004891void Camera3Device::RequestThread::clearPreviousRequest() {
4892 Mutex::Autolock l(mRequestLock);
4893 mPrevRequest.clear();
4894}
4895
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004896status_t Camera3Device::RequestThread::switchToOffline(
4897 const std::vector<int32_t>& streamsToKeep,
4898 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004899 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4900 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004901 Mutex::Autolock l(mRequestLock);
4902 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4903
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004904 // Wait until request thread is fully stopped
4905 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4906
4907 // We could also check for mRepeatingRequests.empty(), but the API interface
4908 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4909 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004910 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4911 while (!queueEmpty) {
4912 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4913 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004914 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004915 return res;
4916 } else if (res != OK) {
4917 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4918 __FUNCTION__, strerror(-res), res);
4919 return res;
4920 }
4921 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4922 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004923
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004924 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004925 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004926}
4927
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004928status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4929 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4930 ATRACE_CALL();
4931 Mutex::Autolock l(mTriggerMutex);
4932 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4933 return BAD_VALUE;
4934 }
4935 mRotateAndCropOverride = rotateAndCropValue;
4936 return OK;
4937}
4938
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004939nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004940 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004941 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004942 return mExpectedInflightDuration > kMinInflightDuration ?
4943 mExpectedInflightDuration : kMinInflightDuration;
4944}
4945
Emilian Peevaebbe412018-01-15 13:53:24 +00004946void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
Emilian Peevf4816702020-04-03 15:44:51 -07004947 camera_capture_request_t *halRequest) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004948 if ((request == nullptr) || (halRequest == nullptr)) {
4949 ALOGE("%s: Invalid request!", __FUNCTION__);
4950 return;
4951 }
4952
4953 if (halRequest->num_physcam_settings > 0) {
4954 if (halRequest->physcam_id != nullptr) {
4955 delete [] halRequest->physcam_id;
4956 halRequest->physcam_id = nullptr;
4957 }
4958 if (halRequest->physcam_settings != nullptr) {
4959 auto it = ++(request->mSettingsList.begin());
4960 size_t i = 0;
4961 for (; it != request->mSettingsList.end(); it++, i++) {
4962 it->metadata.unlock(halRequest->physcam_settings[i]);
4963 }
4964 delete [] halRequest->physcam_settings;
4965 halRequest->physcam_settings = nullptr;
4966 }
4967 }
4968}
4969
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004970void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4971 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004972 return;
4973 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004974
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004975 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004976 // Skip the ones that have been submitted successfully.
4977 if (nextRequest.submitted) {
4978 continue;
4979 }
4980
4981 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
Emilian Peevf4816702020-04-03 15:44:51 -07004982 camera_capture_request_t* halRequest = &nextRequest.halRequest;
4983 Vector<camera_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004984
4985 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004986 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004987 }
4988
Emilian Peevaebbe412018-01-15 13:53:24 +00004989 cleanupPhysicalSettings(captureRequest, halRequest);
4990
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004991 if (captureRequest->mInputStream != NULL) {
Emilian Peevf4816702020-04-03 15:44:51 -07004992 captureRequest->mInputBuffer.status = CAMERA_BUFFER_STATUS_ERROR;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004993 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4994 }
4995
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004996 // No output buffer can be returned when using HAL buffer manager
4997 if (!mUseHalBufManager) {
4998 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4999 //Buffers that failed processing could still have
5000 //valid acquire fence.
5001 int acquireFence = (*outputBuffers)[i].acquire_fence;
5002 if (0 <= acquireFence) {
5003 close(acquireFence);
5004 outputBuffers->editItemAt(i).acquire_fence = -1;
5005 }
Emilian Peevf4816702020-04-03 15:44:51 -07005006 outputBuffers->editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005007 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5008 /*timestampIncreasing*/true, std::vector<size_t> (),
5009 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005010 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005011 }
5012
5013 if (sendRequestError) {
5014 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005015 sp<NotificationListener> listener = mListener.promote();
5016 if (listener != NULL) {
5017 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005018 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005019 captureRequest->mResultExtras);
5020 }
5021 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005022
5023 // Remove yet-to-be submitted inflight request from inflightMap
5024 {
5025 sp<Camera3Device> parent = mParent.promote();
5026 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005027 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005028 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5029 if (idx >= 0) {
5030 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5031 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5032 parent->removeInFlightMapEntryLocked(idx);
5033 }
5034 }
5035 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005036 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005037
5038 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005039 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005040}
5041
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005042void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005043 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005044 // Optimized a bit for the simple steady-state case (single repeating
5045 // request), to avoid putting that request in the queue temporarily.
5046 Mutex::Autolock l(mRequestLock);
5047
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005048 assert(mNextRequests.empty());
5049
5050 NextRequest nextRequest;
5051 nextRequest.captureRequest = waitForNextRequestLocked();
5052 if (nextRequest.captureRequest == nullptr) {
5053 return;
5054 }
5055
Emilian Peevf4816702020-04-03 15:44:51 -07005056 nextRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005057 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005058 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005059
5060 // Wait for additional requests
5061 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5062
5063 for (size_t i = 1; i < batchSize; i++) {
5064 NextRequest additionalRequest;
5065 additionalRequest.captureRequest = waitForNextRequestLocked();
5066 if (additionalRequest.captureRequest == nullptr) {
5067 break;
5068 }
5069
Emilian Peevf4816702020-04-03 15:44:51 -07005070 additionalRequest.halRequest = camera_capture_request_t();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005072 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005073 }
5074
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005075 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005076 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005077 mNextRequests.size(), batchSize);
5078 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005079 }
5080
5081 return;
5082}
5083
5084sp<Camera3Device::CaptureRequest>
5085 Camera3Device::RequestThread::waitForNextRequestLocked() {
5086 status_t res;
5087 sp<CaptureRequest> nextRequest;
5088
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005089 while (mRequestQueue.empty()) {
5090 if (!mRepeatingRequests.empty()) {
5091 // Always atomically enqueue all requests in a repeating request
5092 // list. Guarantees a complete in-sequence set of captures to
5093 // application.
5094 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005095 if (mFirstRepeating) {
5096 mFirstRepeating = false;
5097 } else {
5098 for (auto& request : requests) {
5099 // For repeating requests, override timestamp request using
5100 // the time a request is inserted into the request queue,
5101 // because the original repeating request will have an old
5102 // fixed timestamp.
5103 request->mRequestTimeNs = systemTime();
5104 }
5105 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005106 RequestList::const_iterator firstRequest =
5107 requests.begin();
5108 nextRequest = *firstRequest;
5109 mRequestQueue.insert(mRequestQueue.end(),
5110 ++firstRequest,
5111 requests.end());
5112 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005113
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005114 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005115
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005116 break;
5117 }
5118
5119 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5120
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005121 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5122 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005123 Mutex::Autolock pl(mPauseLock);
5124 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005125 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005126 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005127 if (mNotifyPipelineDrain) {
5128 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5129 mNotifyPipelineDrain = false;
5130 mStreamIdsToBeDrained.clear();
5131 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005132 // Let the tracker know
5133 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5134 if (statusTracker != 0) {
5135 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5136 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005137 sp<Camera3Device> parent = mParent.promote();
5138 if (parent != nullptr) {
5139 parent->mRequestBufferSM.onRequestThreadPaused();
5140 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005141 }
5142 // Stop waiting for now and let thread management happen
5143 return NULL;
5144 }
5145 }
5146
5147 if (nextRequest == NULL) {
5148 // Don't have a repeating request already in hand, so queue
5149 // must have an entry now.
5150 RequestList::iterator firstRequest =
5151 mRequestQueue.begin();
5152 nextRequest = *firstRequest;
5153 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005154 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5155 sp<NotificationListener> listener = mListener.promote();
5156 if (listener != NULL) {
5157 listener->notifyRequestQueueEmpty();
5158 }
5159 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005160 }
5161
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005162 // In case we've been unpaused by setPaused clearing mDoPause, need to
5163 // update internal pause state (capture/setRepeatingRequest unpause
5164 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005165 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005166 if (mPaused) {
5167 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5168 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5169 if (statusTracker != 0) {
5170 statusTracker->markComponentActive(mStatusId);
5171 }
5172 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005173 mPaused = false;
5174
5175 // Check if we've reconfigured since last time, and reset the preview
5176 // request if so. Can't use 'NULL request == repeat' across configure calls.
5177 if (mReconfigured) {
5178 mPrevRequest.clear();
5179 mReconfigured = false;
5180 }
5181
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005182 if (nextRequest != NULL) {
5183 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005184 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5185 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005186
5187 // Since RequestThread::clear() removes buffers from the input stream,
5188 // get the right buffer here before unlocking mRequestLock
5189 if (nextRequest->mInputStream != NULL) {
5190 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5191 if (res != OK) {
5192 // Can't get input buffer from gralloc queue - this could be due to
5193 // disconnected queue or other producer misbehavior, so not a fatal
5194 // error
5195 ALOGE("%s: Can't get input buffer, skipping request:"
5196 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005197
5198 sp<NotificationListener> listener = mListener.promote();
5199 if (listener != NULL) {
5200 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005201 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005202 nextRequest->mResultExtras);
5203 }
5204 return NULL;
5205 }
5206 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005207 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005208
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005209 return nextRequest;
5210}
5211
5212bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005213 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005214 status_t res;
5215 Mutex::Autolock l(mPauseLock);
5216 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005217 if (mPaused == false) {
5218 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005219 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005220 if (mNotifyPipelineDrain) {
5221 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5222 mNotifyPipelineDrain = false;
5223 mStreamIdsToBeDrained.clear();
5224 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005225 // Let the tracker know
5226 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5227 if (statusTracker != 0) {
5228 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5229 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005230 sp<Camera3Device> parent = mParent.promote();
5231 if (parent != nullptr) {
5232 parent->mRequestBufferSM.onRequestThreadPaused();
5233 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005234 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005235
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005236 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005237 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005238 return true;
5239 }
5240 }
5241 // We don't set mPaused to false here, because waitForNextRequest needs
5242 // to further manage the paused state in case of starvation.
5243 return false;
5244}
5245
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005246void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005247 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005248 // With work to do, mark thread as unpaused.
5249 // If paused by request (setPaused), don't resume, to avoid
5250 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005251 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005252 Mutex::Autolock p(mPauseLock);
5253 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005254 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5255 if (mPaused) {
5256 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5257 if (statusTracker != 0) {
5258 statusTracker->markComponentActive(mStatusId);
5259 }
5260 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005261 mPaused = false;
5262 }
5263}
5264
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005265void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5266 sp<Camera3Device> parent = mParent.promote();
5267 if (parent != NULL) {
5268 va_list args;
5269 va_start(args, fmt);
5270
5271 parent->setErrorStateV(fmt, args);
5272
5273 va_end(args);
5274 }
5275}
5276
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005277status_t Camera3Device::RequestThread::insertTriggers(
5278 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005279 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005280 Mutex::Autolock al(mTriggerMutex);
5281
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005282 sp<Camera3Device> parent = mParent.promote();
5283 if (parent == NULL) {
5284 CLOGE("RequestThread: Parent is gone");
5285 return DEAD_OBJECT;
5286 }
5287
Emilian Peevaebbe412018-01-15 13:53:24 +00005288 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005289 size_t count = mTriggerMap.size();
5290
5291 for (size_t i = 0; i < count; ++i) {
5292 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005293 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005294
5295 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5296 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5297 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005298 if (isAeTrigger) {
5299 request->mResultExtras.precaptureTriggerId = triggerId;
5300 mCurrentPreCaptureTriggerId = triggerId;
5301 } else {
5302 request->mResultExtras.afTriggerId = triggerId;
5303 mCurrentAfTriggerId = triggerId;
5304 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005305 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005306 }
5307
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005308 camera_metadata_entry entry = metadata.find(tag);
5309
5310 if (entry.count > 0) {
5311 /**
5312 * Already has an entry for this trigger in the request.
5313 * Rewrite it with our requested trigger value.
5314 */
5315 RequestTrigger oldTrigger = trigger;
5316
5317 oldTrigger.entryValue = entry.data.u8[0];
5318
5319 mTriggerReplacedMap.add(tag, oldTrigger);
5320 } else {
5321 /**
5322 * More typical, no trigger entry, so we just add it
5323 */
5324 mTriggerRemovedMap.add(tag, trigger);
5325 }
5326
5327 status_t res;
5328
5329 switch (trigger.getTagType()) {
5330 case TYPE_BYTE: {
5331 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5332 res = metadata.update(tag,
5333 &entryValue,
5334 /*count*/1);
5335 break;
5336 }
5337 case TYPE_INT32:
5338 res = metadata.update(tag,
5339 &trigger.entryValue,
5340 /*count*/1);
5341 break;
5342 default:
5343 ALOGE("%s: Type not supported: 0x%x",
5344 __FUNCTION__,
5345 trigger.getTagType());
5346 return INVALID_OPERATION;
5347 }
5348
5349 if (res != OK) {
5350 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5351 ", value %d", __FUNCTION__, trigger.getTagName(),
5352 trigger.entryValue);
5353 return res;
5354 }
5355
5356 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5357 trigger.getTagName(),
5358 trigger.entryValue);
5359 }
5360
5361 mTriggerMap.clear();
5362
5363 return count;
5364}
5365
5366status_t Camera3Device::RequestThread::removeTriggers(
5367 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005368 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005369 Mutex::Autolock al(mTriggerMutex);
5370
Emilian Peevaebbe412018-01-15 13:53:24 +00005371 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005372
5373 /**
5374 * Replace all old entries with their old values.
5375 */
5376 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5377 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5378
5379 status_t res;
5380
5381 uint32_t tag = trigger.metadataTag;
5382 switch (trigger.getTagType()) {
5383 case TYPE_BYTE: {
5384 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5385 res = metadata.update(tag,
5386 &entryValue,
5387 /*count*/1);
5388 break;
5389 }
5390 case TYPE_INT32:
5391 res = metadata.update(tag,
5392 &trigger.entryValue,
5393 /*count*/1);
5394 break;
5395 default:
5396 ALOGE("%s: Type not supported: 0x%x",
5397 __FUNCTION__,
5398 trigger.getTagType());
5399 return INVALID_OPERATION;
5400 }
5401
5402 if (res != OK) {
5403 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5404 ", trigger value %d", __FUNCTION__,
5405 trigger.getTagName(), trigger.entryValue);
5406 return res;
5407 }
5408 }
5409 mTriggerReplacedMap.clear();
5410
5411 /**
5412 * Remove all new entries.
5413 */
5414 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5415 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5416 status_t res = metadata.erase(trigger.metadataTag);
5417
5418 if (res != OK) {
5419 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5420 ", trigger value %d", __FUNCTION__,
5421 trigger.getTagName(), trigger.entryValue);
5422 return res;
5423 }
5424 }
5425 mTriggerRemovedMap.clear();
5426
5427 return OK;
5428}
5429
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005430status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005431 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005432 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005433 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005434 status_t res;
5435
Emilian Peevaebbe412018-01-15 13:53:24 +00005436 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005437
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005438 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005439 // exists
5440 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5441 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5442 if (afTrigger.count > 0 &&
5443 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5444 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005445 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005446 if (res != OK) return res;
5447 }
5448
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005449 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005450 // if none already exists
5451 camera_metadata_entry pcTrigger =
5452 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5453 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5454 if (pcTrigger.count > 0 &&
5455 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5456 pcId.count == 0) {
5457 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005458 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005459 if (res != OK) return res;
5460 }
5461
5462 return OK;
5463}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005464
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005465bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5466 const sp<CaptureRequest> &request) {
5467 ATRACE_CALL();
5468
5469 if (request->mRotateAndCropAuto) {
5470 Mutex::Autolock l(mTriggerMutex);
5471 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5472
5473 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5474 if (rotateAndCropEntry.count > 0) {
5475 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5476 return false;
5477 } else {
5478 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5479 return true;
5480 }
5481 } else {
5482 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5483 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5484 &rotateAndCrop_u8, 1);
5485 return true;
5486 }
5487 }
5488 return false;
5489}
5490
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005491/**
5492 * PreparerThread inner class methods
5493 */
5494
5495Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005496 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005497 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005498}
5499
5500Camera3Device::PreparerThread::~PreparerThread() {
5501 Thread::requestExitAndWait();
5502 if (mCurrentStream != nullptr) {
5503 mCurrentStream->cancelPrepare();
5504 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5505 mCurrentStream.clear();
5506 }
5507 clear();
5508}
5509
Ruben Brunkc78ac262015-08-13 17:58:46 -07005510status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005511 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005512 status_t res;
5513
5514 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005515 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005516
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005517 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005518 if (res == OK) {
5519 // No preparation needed, fire listener right off
5520 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005521 if (listener != NULL) {
5522 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005523 }
5524 return OK;
5525 } else if (res != NOT_ENOUGH_DATA) {
5526 return res;
5527 }
5528
5529 // Need to prepare, start up thread if necessary
5530 if (!mActive) {
5531 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5532 // isn't running
5533 Thread::requestExitAndWait();
5534 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5535 if (res != OK) {
5536 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005537 if (listener != NULL) {
5538 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005539 }
5540 return res;
5541 }
5542 mCancelNow = false;
5543 mActive = true;
5544 ALOGV("%s: Preparer stream started", __FUNCTION__);
5545 }
5546
5547 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005548 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005549 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5550
5551 return OK;
5552}
5553
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005554void Camera3Device::PreparerThread::pause() {
5555 ATRACE_CALL();
5556
5557 Mutex::Autolock l(mLock);
5558
5559 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5560 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5561 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5562 int currentMaxCount = mCurrentMaxCount;
5563 mPendingStreams.clear();
5564 mCancelNow = true;
5565 while (mActive) {
5566 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5567 if (res == TIMED_OUT) {
5568 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5569 return;
5570 } else if (res != OK) {
5571 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5572 return;
5573 }
5574 }
5575
5576 //Check whether the prepare thread was able to complete the current
5577 //stream. In case work is still pending emplace it along with the rest
5578 //of the streams in the pending list.
5579 if (currentStream != nullptr) {
5580 if (!mCurrentPrepareComplete) {
5581 pendingStreams.emplace(currentMaxCount, currentStream);
5582 }
5583 }
5584
5585 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5586 for (const auto& it : mPendingStreams) {
5587 it.second->cancelPrepare();
5588 }
5589}
5590
5591status_t Camera3Device::PreparerThread::resume() {
5592 ATRACE_CALL();
5593 status_t res;
5594
5595 Mutex::Autolock l(mLock);
5596 sp<NotificationListener> listener = mListener.promote();
5597
5598 if (mActive) {
5599 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5600 return NO_INIT;
5601 }
5602
5603 auto it = mPendingStreams.begin();
5604 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005605 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005606 if (res == OK) {
5607 if (listener != NULL) {
5608 listener->notifyPrepared(it->second->getId());
5609 }
5610 it = mPendingStreams.erase(it);
5611 } else if (res != NOT_ENOUGH_DATA) {
5612 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5613 res, strerror(-res));
5614 it = mPendingStreams.erase(it);
5615 } else {
5616 it++;
5617 }
5618 }
5619
5620 if (mPendingStreams.empty()) {
5621 return OK;
5622 }
5623
5624 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5625 if (res != OK) {
5626 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5627 __FUNCTION__, res, strerror(-res));
5628 return res;
5629 }
5630 mCancelNow = false;
5631 mActive = true;
5632 ALOGV("%s: Preparer stream started", __FUNCTION__);
5633
5634 return OK;
5635}
5636
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005637status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005638 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005639 Mutex::Autolock l(mLock);
5640
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005641 for (const auto& it : mPendingStreams) {
5642 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005643 }
5644 mPendingStreams.clear();
5645 mCancelNow = true;
5646
5647 return OK;
5648}
5649
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005650void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005651 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005652 Mutex::Autolock l(mLock);
5653 mListener = listener;
5654}
5655
5656bool Camera3Device::PreparerThread::threadLoop() {
5657 status_t res;
5658 {
5659 Mutex::Autolock l(mLock);
5660 if (mCurrentStream == nullptr) {
5661 // End thread if done with work
5662 if (mPendingStreams.empty()) {
5663 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5664 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5665 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5666 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005667 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005668 return false;
5669 }
5670
5671 // Get next stream to prepare
5672 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005673 mCurrentStream = it->second;
5674 mCurrentMaxCount = it->first;
5675 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005676 mPendingStreams.erase(it);
5677 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5678 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5679 } else if (mCancelNow) {
5680 mCurrentStream->cancelPrepare();
5681 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5682 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5683 mCurrentStream.clear();
5684 mCancelNow = false;
5685 return true;
5686 }
5687 }
5688
5689 res = mCurrentStream->prepareNextBuffer();
5690 if (res == NOT_ENOUGH_DATA) return true;
5691 if (res != OK) {
5692 // Something bad happened; try to recover by cancelling prepare and
5693 // signalling listener anyway
5694 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5695 mCurrentStream->getId(), res, strerror(-res));
5696 mCurrentStream->cancelPrepare();
5697 }
5698
5699 // This stream has finished, notify listener
5700 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005701 sp<NotificationListener> listener = mListener.promote();
5702 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005703 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5704 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005705 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005706 }
5707
5708 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5709 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005710 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005711
5712 return true;
5713}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005714
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005715status_t Camera3Device::RequestBufferStateMachine::initialize(
5716 sp<camera3::StatusTracker> statusTracker) {
5717 if (statusTracker == nullptr) {
5718 ALOGE("%s: statusTracker is null", __FUNCTION__);
5719 return BAD_VALUE;
5720 }
5721
5722 std::lock_guard<std::mutex> lock(mLock);
5723 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005724 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005725 return OK;
5726}
5727
5728bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5729 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005730 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005731 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005732 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005733 return true;
5734 }
5735 return false;
5736}
5737
5738void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5739 std::lock_guard<std::mutex> lock(mLock);
5740 if (!mRequestBufferOngoing) {
5741 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5742 return;
5743 }
5744 mRequestBufferOngoing = false;
5745 if (mStatus == RB_STATUS_PENDING_STOP) {
5746 checkSwitchToStopLocked();
5747 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005748 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005749}
5750
5751void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5752 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005753 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005754 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005755 return;
5756}
5757
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005758void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005759 std::lock_guard<std::mutex> lock(mLock);
5760 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005761 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5762 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005763 mInflightMapEmpty = false;
5764 if (mStatus == RB_STATUS_STOPPED) {
5765 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005766 }
5767 return;
5768}
5769
5770void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5771 std::lock_guard<std::mutex> lock(mLock);
5772 mRequestThreadPaused = true;
5773 if (mStatus == RB_STATUS_PENDING_STOP) {
5774 checkSwitchToStopLocked();
5775 }
5776 return;
5777}
5778
5779void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5780 std::lock_guard<std::mutex> lock(mLock);
5781 mInflightMapEmpty = true;
5782 if (mStatus == RB_STATUS_PENDING_STOP) {
5783 checkSwitchToStopLocked();
5784 }
5785 return;
5786}
5787
5788void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5789 std::lock_guard<std::mutex> lock(mLock);
5790 if (!checkSwitchToStopLocked()) {
5791 mStatus = RB_STATUS_PENDING_STOP;
5792 }
5793 return;
5794}
5795
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005796bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5797 std::lock_guard<std::mutex> lock(mLock);
5798 if (mRequestBufferOngoing) {
5799 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5800 __FUNCTION__);
5801 return false;
5802 }
5803 mSwitchedToOffline = true;
5804 mInflightMapEmpty = true;
5805 mRequestThreadPaused = true;
5806 mStatus = RB_STATUS_STOPPED;
5807 return true;
5808}
5809
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005810void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5811 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5812 if (statusTracker != nullptr) {
5813 if (active) {
5814 statusTracker->markComponentActive(mRequestBufferStatusId);
5815 } else {
5816 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5817 }
5818 }
5819}
5820
5821bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5822 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5823 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005824 return true;
5825 }
5826 return false;
5827}
5828
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005829bool Camera3Device::startRequestBuffer() {
5830 return mRequestBufferSM.startRequestBuffer();
5831}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005832
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005833void Camera3Device::endRequestBuffer() {
5834 mRequestBufferSM.endRequestBuffer();
5835}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005836
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005837nsecs_t Camera3Device::getWaitDuration() {
5838 return kBaseGetBufferWait + getExpectedInFlightDuration();
5839}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005840
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005841void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5842 mInterface->getInflightBufferKeys(out);
5843}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005844
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005845void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5846 mInterface->getInflightRequestBufferKeys(out);
5847}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005848
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005849std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5850 std::vector<sp<Camera3StreamInterface>> ret;
5851 bool hasInputStream = mInputStream != nullptr;
5852 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5853 if (hasInputStream) {
5854 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005855 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005856 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5857 ret.push_back(mOutputStreams[i]);
5858 }
5859 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5860 ret.push_back(mDeletedStreams[i]);
5861 }
5862 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005863}
5864
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005865status_t Camera3Device::switchToOffline(
5866 const std::vector<int32_t>& streamsToKeep,
5867 /*out*/ sp<CameraOfflineSessionBase>* session) {
5868 ATRACE_CALL();
5869 if (session == nullptr) {
5870 ALOGE("%s: session must not be null", __FUNCTION__);
5871 return BAD_VALUE;
5872 }
5873
5874 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005875
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005876 bool hasInputStream = mInputStream != nullptr;
5877 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5878 bool inputStreamSupportsOffline = hasInputStream ?
5879 mInputStream->getOfflineProcessingSupport() : false;
5880 auto outputStreamIds = mOutputStreams.getStreamIds();
5881 auto streamIds = outputStreamIds;
5882 if (hasInputStream) {
5883 streamIds.push_back(mInputStream->getId());
5884 }
5885
5886 // Check all streams in streamsToKeep supports offline mode
5887 for (auto id : streamsToKeep) {
5888 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5889 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5890 return BAD_VALUE;
5891 } else if (id == inputStreamId) {
5892 if (!inputStreamSupportsOffline) {
5893 ALOGE("%s: input stream %d cannot be switched to offline",
5894 __FUNCTION__, id);
5895 return BAD_VALUE;
5896 }
5897 } else {
5898 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5899 if (!stream->getOfflineProcessingSupport()) {
5900 ALOGE("%s: output stream %d cannot be switched to offline",
5901 __FUNCTION__, id);
5902 return BAD_VALUE;
5903 }
5904 }
5905 }
5906
5907 // TODO: block surface sharing and surface group streams until we can support them
5908
5909 // Stop repeating request, wait until all remaining requests are submitted, then call into
5910 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005911 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5912 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005913 camera3::BufferRecords bufferRecords;
5914 status_t ret = mRequestThread->switchToOffline(
5915 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005916
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005917 if (ret != OK) {
5918 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5919 return ret;
5920 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005921
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005922 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5923 if (!succ) {
5924 SET_ERR("HAL must not be calling requestStreamBuffers call");
5925 // TODO: block ALL callbacks from HAL till app configured new streams?
5926 return UNKNOWN_ERROR;
5927 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005928
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005929 // Verify offlineSessionInfo
5930 std::vector<int32_t> offlineStreamIds;
5931 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5932 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5933 // verify stream IDs
5934 int32_t id = offlineStream.id;
5935 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5936 SET_ERR("stream ID %d not found!", id);
5937 return UNKNOWN_ERROR;
5938 }
5939
5940 // When not using HAL buf manager, only allow streams requested by app to be preserved
5941 if (!mUseHalBufManager) {
5942 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5943 SET_ERR("stream ID %d must not be switched to offline!", id);
5944 return UNKNOWN_ERROR;
5945 }
5946 }
5947
5948 offlineStreamIds.push_back(id);
5949 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5950 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5951 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5952 // Verify number of outstanding buffers
5953 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5954 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5955 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5956 return UNKNOWN_ERROR;
5957 }
5958 }
5959
5960 // Verify all streams to be deleted don't have any outstanding buffers
5961 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5962 inputStreamId) == offlineStreamIds.end()) {
5963 if (mInputStream->hasOutstandingBuffers()) {
5964 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5965 inputStreamId, mInputStream->getOutstandingBuffersCount());
5966 return UNKNOWN_ERROR;
5967 }
5968 }
5969
5970 for (const auto& outStreamId : outputStreamIds) {
5971 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5972 outStreamId) == offlineStreamIds.end()) {
5973 auto outStream = mOutputStreams.get(outStreamId);
5974 if (outStream->hasOutstandingBuffers()) {
5975 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5976 outStreamId, outStream->getOutstandingBuffersCount());
5977 return UNKNOWN_ERROR;
5978 }
5979 }
5980 }
5981
5982 InFlightRequestMap offlineReqs;
5983 // Verify inflight requests and their pending buffers
5984 {
5985 std::lock_guard<std::mutex> l(mInFlightLock);
5986 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5987 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5988 if (idx == NAME_NOT_FOUND) {
5989 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5990 return UNKNOWN_ERROR;
5991 }
5992
5993 const auto& inflightReq = mInFlightMap.valueAt(idx);
5994 // TODO: check specific stream IDs
5995 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5996 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5997 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5998 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5999 return UNKNOWN_ERROR;
6000 }
6001 offlineReqs.add(offlineReq.frameNumber, inflightReq);
6002 }
6003 }
6004
6005 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006006 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006007 camera3::StreamSet offlineStreamSet;
6008 sp<camera3::Camera3Stream> inputStream;
6009 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6010 int32_t id = offlineStream.id;
6011 if (mInputStream != nullptr && id == mInputStream->getId()) {
6012 inputStream = mInputStream;
6013 } else {
6014 offlineStreamSet.add(id, mOutputStreams.get(id));
6015 }
6016 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006017
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006018 // TODO: check if we need to lock before copying states
6019 // though technically no other thread should be talking to Camera3Device at this point
6020 Camera3OfflineStates offlineStates(
6021 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006022 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6023 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6024 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6025 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6026 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6027 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6028 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006029
6030 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6031 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6032
6033 // Delete all streams that has been transferred to offline session
6034 Mutex::Autolock l(mLock);
6035 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6036 int32_t id = offlineStream.id;
6037 if (mInputStream != nullptr && id == mInputStream->getId()) {
6038 mInputStream.clear();
6039 } else {
6040 mOutputStreams.remove(id);
6041 }
6042 }
6043
6044 // disconnect all other streams and switch to UNCONFIGURED state
6045 if (mInputStream != nullptr) {
6046 ret = mInputStream->disconnect();
6047 if (ret != OK) {
6048 SET_ERR_L("disconnect input stream failed!");
6049 return UNKNOWN_ERROR;
6050 }
6051 }
6052
6053 for (auto streamId : mOutputStreams.getStreamIds()) {
6054 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6055 ret = stream->disconnect();
6056 if (ret != OK) {
6057 SET_ERR_L("disconnect output stream %d failed!", streamId);
6058 return UNKNOWN_ERROR;
6059 }
6060 }
6061
6062 mInputStream.clear();
6063 mOutputStreams.clear();
6064 mNeedConfig = true;
6065 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6066 mOperatingMode = NO_MODE;
6067 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006068 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006069
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006070 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006071 // TO be done by CameraDeviceClient/Camera3OfflineSession
6072 // register the offline client to camera service
6073 // Setup result passthing threads etc
6074 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6075 // TODO: check how many onIdle callback will be sent
6076 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006077}
6078
Emilian Peevcc0b7952020-01-07 13:54:47 -08006079void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6080 ATRACE_CALL();
6081
6082 if (offlineStreamIds == nullptr) {
6083 return;
6084 }
6085
6086 Mutex::Autolock il(mInterfaceLock);
6087
6088 auto streamIds = mOutputStreams.getStreamIds();
6089 bool hasInputStream = mInputStream != nullptr;
6090 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6091 offlineStreamIds->push_back(mInputStream->getId());
6092 }
6093
6094 for (const auto & streamId : streamIds) {
6095 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6096 // Streams that use the camera buffer manager are currently not supported in
6097 // offline mode
6098 if (stream->getOfflineProcessingSupport() &&
6099 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6100 offlineStreamIds->push_back(streamId);
6101 }
6102 }
6103}
6104
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006105status_t Camera3Device::setRotateAndCropAutoBehavior(
6106 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6107 ATRACE_CALL();
6108 Mutex::Autolock il(mInterfaceLock);
6109 Mutex::Autolock l(mLock);
6110 if (mRequestThread == nullptr) {
6111 return INVALID_OPERATION;
6112 }
6113 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6114}
6115
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006116}; // namespace android