blob: 8754ad3c8bbc3ce2b1d479db16dbd2ff340d9276 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -040059#include "device3/Camera3FakeStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070063#include "utils/TraceHFR.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070064#include "utils/CameraServiceProxyWrapper.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080065
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080066#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080067#include <tuple>
68
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080069using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070using namespace android::hardware::camera;
71using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080072
73namespace android {
74
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080075Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080076 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080077 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070078 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070079 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070080 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070081 mUsePartialResult(false),
82 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080083 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070085 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070087 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070088 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070089 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000090 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010091 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070092 mLastTemplateId(-1),
93 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094{
95 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080097}
98
99Camera3Device::~Camera3Device()
100{
101 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800102 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700103 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800104}
105
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800106const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800107 return mId;
108}
109
Emilian Peevbd8c5032018-02-14 23:05:40 +0000110status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800111 ATRACE_CALL();
112 Mutex::Autolock il(mInterfaceLock);
113 Mutex::Autolock l(mLock);
114
115 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
116 if (mStatus != STATUS_UNINITIALIZED) {
117 CLOGE("Already initialized!");
118 return INVALID_OPERATION;
119 }
120 if (manager == nullptr) return INVALID_OPERATION;
121
122 sp<ICameraDeviceSession> session;
123 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800124 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 /*out*/ &session);
126 ATRACE_END();
127 if (res != OK) {
128 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
129 return res;
130 }
131
Steven Moreland5ff9c912017-03-09 23:13:00 -0800132 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700134 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800135 session->close();
136 return res;
137 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800138 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800139
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700141 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (isLogical) {
143 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700144 res = manager->getCameraCharacteristics(
145 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700146 if (res != OK) {
147 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
148 physicalId.c_str(), strerror(-res), res);
149 session->close();
150 return res;
151 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700152
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800153 bool usePrecorrectArray =
154 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
155 if (usePrecorrectArray) {
156 res = mDistortionMappers[physicalId].setupStaticInfo(
157 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700158 if (res != OK) {
159 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
160 "correction", physicalId.c_str());
161 session->close();
162 return res;
163 }
164 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800166 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800167 &mPhysicalDeviceInfoMap[physicalId],
168 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700169 }
170 }
171
Yifan Hongf79b5542017-04-11 14:44:25 -0700172 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
174 [&queue](const auto& descriptor) {
175 queue = std::make_shared<RequestMetadataQueue>(descriptor);
176 if (!queue->isValid() || queue->availableToWrite() <= 0) {
177 ALOGE("HAL returns empty request metadata fmq, not use it");
178 queue = nullptr;
179 // don't use the queue onwards.
180 }
181 });
182 if (!requestQueueRet.isOk()) {
183 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
184 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700185 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700186 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700187
188 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700189 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190 [&resQueue](const auto& descriptor) {
191 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
192 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700193 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700194 resQueue = nullptr;
195 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 }
197 });
198 if (!resultQueueRet.isOk()) {
199 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
200 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700201 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700202 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700203 IF_ALOGV() {
204 session->interfaceChain([](
205 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
206 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800207 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700208 ALOGV(" %s", iface.c_str());
209 }
210 });
211 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700212
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800213 camera_metadata_entry bufMgrMode =
214 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
215 if (bufMgrMode.count > 0) {
216 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
217 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
218 }
219
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700220 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
221 for (size_t i = 0; i < capabilities.count; i++) {
222 uint8_t capability = capabilities.data.u8[i];
223 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
224 mSupportOfflineProcessing = true;
225 }
226 }
227
228 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000229 std::string providerType;
230 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000231 mTagMonitor.initialize(mVendorTagId);
232 if (!monitorTags.isEmpty()) {
233 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
234 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800235
Shuzhen Wang268a1362018-10-16 16:32:59 -0700236 // Metadata tags needs fixup for monochrome camera device version less
237 // than 3.5.
238 hardware::hidl_version maxVersion{0,0};
239 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
240 if (res != OK) {
241 ALOGE("%s: Error in getting camera device version id: %s (%d)",
242 __FUNCTION__, strerror(-res), res);
243 return res;
244 }
245 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
246 maxVersion.get_major(), maxVersion.get_minor());
247
248 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700249 for (size_t i = 0; i < capabilities.count; i++) {
250 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700251 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
252 isMonochrome = true;
253 }
254 }
255 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
256
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800257 return initializeCommonLocked();
258}
259
260status_t Camera3Device::initializeCommonLocked() {
261
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700262 /** Start up status tracker thread */
263 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 if (res != OK) {
266 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700269 mStatusTracker.clear();
270 return res;
271 }
272
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700273 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700274 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700275
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700276 if (mUseHalBufManager) {
277 res = mRequestBufferSM.initialize(mStatusTracker);
278 if (res != OK) {
279 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
280 strerror(-res), res);
281 mInterface->close();
282 mStatusTracker.clear();
283 return res;
284 }
285 }
286
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800287 /** Create buffer manager */
288 mBufferManager = new Camera3BufferManager();
289
290 Vector<int32_t> sessionParamKeys;
291 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
292 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
293 if (sessionKeysEntry.count > 0) {
294 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
295 }
296
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700297 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700298 mRequestThread = new RequestThread(
299 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800300 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800301 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700302 SET_ERR_L("Unable to start request queue thread: %s (%d)",
303 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800304 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306 return res;
307 }
308
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700309 mPreparerThread = new PreparerThread();
310
Ruben Brunk183f0562015-08-12 12:55:02 -0700311 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800312 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400313 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700314 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700315 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800316
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800317 // Measure the clock domain offset between camera and video/hw_composer
318 camera_metadata_entry timestampSource =
319 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
320 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
321 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
322 mTimestampOffset = getMonoToBoottimeOffset();
323 }
324
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700325 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100326 camera_metadata_entry partialResultsCount =
327 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
328 if (partialResultsCount.count > 0) {
329 mNumPartialResults = partialResultsCount.data.i32[0];
330 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700331 }
332
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700333 camera_metadata_entry configs =
334 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
335 for (uint32_t i = 0; i < configs.count; i += 4) {
336 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
337 configs.data.i32[i + 3] ==
338 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
339 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
340 configs.data.i32[i + 2]));
341 }
342 }
343
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800344 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
345 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700346 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700347 if (res != OK) {
348 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
349 return res;
350 }
351 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800353 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800355
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800356 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
357 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
358 }
359
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800360 return OK;
361}
362
363status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700364 return disconnectImpl();
365}
366
367status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800368 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700369 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800370
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700371 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700372 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700373 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800374 Mutex::Autolock il(mInterfaceLock);
375 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
376 {
377 Mutex::Autolock l(mLock);
378 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700379
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800380 if (mStatus == STATUS_ACTIVE ||
381 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
382 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800386 } else {
387 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
388 if (res != OK) {
389 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
390 maxExpectedDuration);
391 // Continue to close device even in case of error
392 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700393 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700394 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800395
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800396 if (mStatus == STATUS_ERROR) {
397 CLOGE("Shutting down in an error state");
398 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800400 if (mStatusTracker != NULL) {
401 mStatusTracker->requestExit();
402 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800404 if (mRequestThread != NULL) {
405 mRequestThread->requestExit();
406 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700407
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800408 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
409 for (size_t i = 0; i < mOutputStreams.size(); i++) {
410 streams.push_back(mOutputStreams[i]);
411 }
412 if (mInputStream != nullptr) {
413 streams.push_back(mInputStream);
414 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700415 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700416 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800417 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
418 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
420 // HAL may be in a bad state, so waiting for request thread
421 // (which may be stuck in the HAL processCaptureRequest call)
422 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800423 // give up mInterfaceLock here and then lock it again. Could this lead
424 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 mRequestThread->join();
426 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700427 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800428 Mutex::Autolock il(mInterfaceLock);
429 if (mStatusTracker != NULL) {
430 mStatusTracker->join();
431 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800432
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800433 HalInterface* interface;
434 {
435 Mutex::Autolock l(mLock);
436 mRequestThread.clear();
437 Mutex::Autolock stLock(mTrackerLock);
438 mStatusTracker.clear();
439 interface = mInterface.get();
440 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700441
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800442 // Call close without internal mutex held, as the HAL close may need to
443 // wait on assorted callbacks,etc, to complete before it can return.
444 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800446 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800447
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800448 {
449 Mutex::Autolock l(mLock);
450 mInterface->clear();
451 mOutputStreams.clear();
452 mInputStream.clear();
453 mDeletedStreams.clear();
454 mBufferManager.clear();
455 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
456 }
457
458 for (auto& weakStream : streams) {
459 sp<Camera3StreamInterface> stream = weakStream.promote();
460 if (stream != nullptr) {
461 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
462 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
463 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700464 }
465 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700466 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700467 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800468}
469
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700470// For dumping/debugging only -
471// try to acquire a lock a few times, eventually give up to proceed with
472// debug/dump operations
473bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
474 bool gotLock = false;
475 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
476 if (lock.tryLock() == NO_ERROR) {
477 gotLock = true;
478 break;
479 } else {
480 usleep(kDumpSleepDuration);
481 }
482 }
483 return gotLock;
484}
485
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700486Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
487 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100488 const int STREAM_CONFIGURATION_SIZE = 4;
489 const int STREAM_FORMAT_OFFSET = 0;
490 const int STREAM_WIDTH_OFFSET = 1;
491 const int STREAM_HEIGHT_OFFSET = 2;
492 const int STREAM_IS_INPUT_OFFSET = 3;
493 camera_metadata_ro_entry_t availableStreamConfigs =
494 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
495 if (availableStreamConfigs.count == 0 ||
496 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
497 return Size(0, 0);
498 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700499
Emilian Peev08dd2452017-04-06 16:55:14 +0100500 // Get max jpeg size (area-wise).
501 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
502 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
503 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
504 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
505 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
506 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
507 && format == HAL_PIXEL_FORMAT_BLOB &&
508 (width * height > maxJpegWidth * maxJpegHeight)) {
509 maxJpegWidth = width;
510 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700511 }
512 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100513
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700514 return Size(maxJpegWidth, maxJpegHeight);
515}
516
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800517nsecs_t Camera3Device::getMonoToBoottimeOffset() {
518 // try three times to get the clock offset, choose the one
519 // with the minimum gap in measurements.
520 const int tries = 3;
521 nsecs_t bestGap, measured;
522 for (int i = 0; i < tries; ++i) {
523 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
525 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
526 const nsecs_t gap = tmono2 - tmono;
527 if (i == 0 || gap < bestGap) {
528 bestGap = gap;
529 measured = tbase - ((tmono + tmono2) >> 1);
530 }
531 }
532 return measured;
533}
534
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800535hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
536 int frameworkFormat) {
537 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
538}
539
540DataspaceFlags Camera3Device::mapToHidlDataspace(
541 android_dataspace dataSpace) {
542 return dataSpace;
543}
544
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700545BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100546 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700547 return usage;
548}
549
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800550StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
551 switch (rotation) {
552 case CAMERA3_STREAM_ROTATION_0:
553 return StreamRotation::ROTATION_0;
554 case CAMERA3_STREAM_ROTATION_90:
555 return StreamRotation::ROTATION_90;
556 case CAMERA3_STREAM_ROTATION_180:
557 return StreamRotation::ROTATION_180;
558 case CAMERA3_STREAM_ROTATION_270:
559 return StreamRotation::ROTATION_270;
560 }
561 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
562 return StreamRotation::ROTATION_0;
563}
564
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800565status_t Camera3Device::mapToStreamConfigurationMode(
566 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
567 if (mode == nullptr) return BAD_VALUE;
568 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
569 switch(operationMode) {
570 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
571 *mode = StreamConfigurationMode::NORMAL_MODE;
572 break;
573 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
574 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
575 break;
576 default:
577 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
578 return BAD_VALUE;
579 }
580 } else {
581 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800583 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584}
585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586int Camera3Device::mapToFrameworkFormat(
587 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
588 return static_cast<uint32_t>(pixelFormat);
589}
590
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700591android_dataspace Camera3Device::mapToFrameworkDataspace(
592 DataspaceFlags dataSpace) {
593 return static_cast<android_dataspace>(dataSpace);
594}
595
Emilian Peev050f5dc2017-05-18 14:43:56 +0100596uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700597 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700598 return usage;
599}
600
Emilian Peev050f5dc2017-05-18 14:43:56 +0100601uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700602 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700603 return usage;
604}
605
Zhijun Hef7da0962014-04-24 13:27:56 -0700606ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700607 // Get max jpeg size (area-wise).
608 Size maxJpegResolution = getMaxJpegResolution();
609 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800610 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
611 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700612 return BAD_VALUE;
613 }
614
Zhijun Hef7da0962014-04-24 13:27:56 -0700615 // Get max jpeg buffer size
616 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700617 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
618 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
620 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700621 return BAD_VALUE;
622 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700623 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800624 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700625
626 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700627 float scaleFactor = ((float) (width * height)) /
628 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800629 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
630 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 if (jpegBufferSize > maxJpegBufferSize) {
632 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700633 }
634
635 return jpegBufferSize;
636}
637
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700638ssize_t Camera3Device::getPointCloudBufferSize() const {
639 const int FLOATS_PER_POINT=4;
640 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
641 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800642 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
643 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700644 return BAD_VALUE;
645 }
646 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
647 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
648 return maxBytesForPointCloud;
649}
650
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800652 const int PER_CONFIGURATION_SIZE = 3;
653 const int WIDTH_OFFSET = 0;
654 const int HEIGHT_OFFSET = 1;
655 const int SIZE_OFFSET = 2;
656 camera_metadata_ro_entry rawOpaqueSizes =
657 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800658 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800659 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800660 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
661 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800662 return BAD_VALUE;
663 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700664
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800665 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
666 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
667 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
668 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
669 }
670 }
671
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800672 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
673 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 return BAD_VALUE;
675}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700676
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800677status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
678 ATRACE_CALL();
679 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700680
681 // Try to lock, but continue in case of failure (to avoid blocking in
682 // deadlocks)
683 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
684 bool gotLock = tryLockSpinRightRound(mLock);
685
686 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800687 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
688 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700689 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800690 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
691 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700692
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800693 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700694
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 String16 templatesOption("-t");
696 int n = args.size();
697 for (int i = 0; i < n; i++) {
698 if (args[i] == templatesOption) {
699 dumpTemplates = true;
700 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000701 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700702 if (i + 1 < n) {
703 String8 monitorTags = String8(args[i + 1]);
704 if (monitorTags == "off") {
705 mTagMonitor.disableMonitoring();
706 } else {
707 mTagMonitor.parseTagsToMonitor(monitorTags);
708 }
709 } else {
710 mTagMonitor.disableMonitoring();
711 }
712 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800713 }
714
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800717 const char *status =
718 mStatus == STATUS_ERROR ? "ERROR" :
719 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700720 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
721 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800722 mStatus == STATUS_ACTIVE ? "ACTIVE" :
723 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700724
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800725 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700726 if (mStatus == STATUS_ERROR) {
727 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800729 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800730 const char *mode =
731 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
732 mOperatingMode == static_cast<int>(
733 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
734 "CUSTOM";
735 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800736
737 if (mInputStream != NULL) {
738 write(fd, lines.string(), lines.size());
739 mInputStream->dump(fd, args);
740 } else {
741 lines.appendFormat(" No input stream.\n");
742 write(fd, lines.string(), lines.size());
743 }
744 for (size_t i = 0; i < mOutputStreams.size(); i++) {
745 mOutputStreams[i]->dump(fd,args);
746 }
747
Zhijun He431503c2016-03-07 17:30:16 -0800748 if (mBufferManager != NULL) {
749 lines = String8(" Camera3 Buffer Manager:\n");
750 write(fd, lines.string(), lines.size());
751 mBufferManager->dump(fd, args);
752 }
Zhijun He125684a2015-12-26 15:07:30 -0800753
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700754 lines = String8(" In-flight requests:\n");
755 if (mInFlightMap.size() == 0) {
756 lines.append(" None\n");
757 } else {
758 for (size_t i = 0; i < mInFlightMap.size(); i++) {
759 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700760 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000761 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800762 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000763 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700764 }
765 }
766 write(fd, lines.string(), lines.size());
767
Shuzhen Wang686f6442017-06-20 16:16:04 -0700768 if (mRequestThread != NULL) {
769 mRequestThread->dumpCaptureRequestLatency(fd,
770 " ProcessCaptureRequest latency histogram:");
771 }
772
Igor Murashkin1e479c02013-09-06 16:55:14 -0700773 {
774 lines = String8(" Last request sent:\n");
775 write(fd, lines.string(), lines.size());
776
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700777 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700778 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
779 }
780
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800782 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800783 "TEMPLATE_PREVIEW",
784 "TEMPLATE_STILL_CAPTURE",
785 "TEMPLATE_VIDEO_RECORD",
786 "TEMPLATE_VIDEO_SNAPSHOT",
787 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800788 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800789 };
790
791 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800792 camera_metadata_t *templateRequest = nullptr;
793 mInterface->constructDefaultRequestSettings(
794 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800796 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800797 lines.append(" Not supported\n");
798 write(fd, lines.string(), lines.size());
799 } else {
800 write(fd, lines.string(), lines.size());
801 dump_indented_camera_metadata(templateRequest,
802 fd, /*verbosity*/2, /*indentation*/8);
803 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800804 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800805 }
806 }
807
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700808 mTagMonitor.dumpMonitoredMetadata(fd);
809
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800810 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800811 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800812 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800813 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800814 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800815
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700816 if (gotLock) mLock.unlock();
817 if (gotInterfaceLock) mInterfaceLock.unlock();
818
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800819 return OK;
820}
821
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800822const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800823 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800824 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
825 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700826 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800827 mStatus == STATUS_ERROR ?
828 "when in error state" : "before init");
829 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700830 if (physicalId.isEmpty()) {
831 return mDeviceInfo;
832 } else {
833 std::string id(physicalId.c_str());
834 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
835 return mPhysicalDeviceInfoMap.at(id);
836 } else {
837 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
838 return mDeviceInfo;
839 }
840 }
841}
842
843const CameraMetadata& Camera3Device::info() const {
844 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800845 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800846}
847
Jianing Wei90e59c92014-03-12 18:29:36 -0700848status_t Camera3Device::checkStatusOkToCaptureLocked() {
849 switch (mStatus) {
850 case STATUS_ERROR:
851 CLOGE("Device has encountered a serious error");
852 return INVALID_OPERATION;
853 case STATUS_UNINITIALIZED:
854 CLOGE("Device not initialized");
855 return INVALID_OPERATION;
856 case STATUS_UNCONFIGURED:
857 case STATUS_CONFIGURED:
858 case STATUS_ACTIVE:
859 // OK
860 break;
861 default:
862 SET_ERR_L("Unexpected status: %d", mStatus);
863 return INVALID_OPERATION;
864 }
865 return OK;
866}
867
868status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000869 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700870 const std::list<const SurfaceMap> &surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700871 bool repeating, nsecs_t requestTimeNs,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700872 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700873 if (requestList == NULL) {
874 CLOGE("requestList cannot be NULL.");
875 return BAD_VALUE;
876 }
877
Jianing Weicb0652e2014-03-12 18:29:36 -0700878 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700880 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
881 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
882 ++metadataIt, ++surfaceMapIt) {
883 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700884 if (newRequest == 0) {
885 CLOGE("Can't create capture request");
886 return BAD_VALUE;
887 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700888
Shuzhen Wang9d066012016-09-30 11:30:20 -0700889 newRequest->mRepeating = repeating;
Shuzhen Wang316781a2020-08-18 18:11:01 -0700890 newRequest->mRequestTimeNs = requestTimeNs;
Shuzhen Wang9d066012016-09-30 11:30:20 -0700891
Jianing Weicb0652e2014-03-12 18:29:36 -0700892 // Setup burst Id and request Id
893 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800894 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
895 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700896 CLOGE("RequestID does not exist in metadata");
897 return BAD_VALUE;
898 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800899 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700900
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700902
903 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700904 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700905 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
906 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
907 return BAD_VALUE;
908 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700909
910 // Setup batch size if this is a high speed video recording request.
911 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
912 auto firstRequest = requestList->begin();
913 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
914 if (outputStream->isVideoStream()) {
915 (*firstRequest)->mBatchSize = requestList->size();
916 break;
917 }
918 }
919 }
920
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 return OK;
922}
923
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800924status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800925 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800926
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000929 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800931 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932}
933
Emilian Peevaebbe412018-01-15 13:53:24 +0000934void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 std::list<const SurfaceMap>& surfaceMaps,
936 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 PhysicalCameraSettingsList requestList;
938 requestList.push_back({std::string(getId().string()), request});
939 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700940
941 SurfaceMap surfaceMap;
942 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
943 // With no surface list passed in, stream and surface will have 1-to-1
944 // mapping. So the surface index is 0 for each stream in the surfaceMap.
945 for (size_t i = 0; i < streams.count; i++) {
946 surfaceMap[streams.data.i32[i]].push_back(0);
947 }
948 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800949}
950
Jianing Wei90e59c92014-03-12 18:29:36 -0700951status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000952 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953 const std::list<const SurfaceMap> &surfaceMaps,
954 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700955 /*out*/
956 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700957 ATRACE_CALL();
Shuzhen Wang316781a2020-08-18 18:11:01 -0700958 nsecs_t requestTimeNs = systemTime();
959
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 Mutex::Autolock il(mInterfaceLock);
961 Mutex::Autolock l(mLock);
962
963 status_t res = checkStatusOkToCaptureLocked();
964 if (res != OK) {
965 // error logged by previous call
966 return res;
967 }
968
969 RequestList requestList;
970
Shuzhen Wang0129d522016-10-30 22:43:41 -0700971 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
Shuzhen Wang316781a2020-08-18 18:11:01 -0700972 repeating, requestTimeNs, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700973 if (res != OK) {
974 // error logged by previous call
975 return res;
976 }
977
978 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700979 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700981 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700982 }
983
984 if (res == OK) {
985 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
986 if (res != OK) {
987 SET_ERR_L("Can't transition to active in %f seconds!",
988 kActiveTimeout/1e9);
989 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800990 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700991 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700992 } else {
993 CLOGE("Cannot queue request. Impossible.");
994 return BAD_VALUE;
995 }
996
997 return res;
998}
999
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001000hardware::Return<void> Camera3Device::requestStreamBuffers(
1001 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1002 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001003 RequestBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001004 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001005 *this, *mInterface, *this};
1006 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001007 return hardware::Void();
1008}
1009
1010hardware::Return<void> Camera3Device::returnStreamBuffers(
1011 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001012 ReturnBufferStates states {
Shuzhen Wang316781a2020-08-18 18:11:01 -07001013 mId, mUseHalBufManager, mOutputStreams, mSessionStatsBuilder, *mInterface};
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001014 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001015 return hardware::Void();
1016}
1017
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001018hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001019 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001020 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001021 // Ideally we should grab mLock, but that can lead to deadlock, and
1022 // it's not super important to get up to date value of mStatus for this
1023 // warning print, hence skipping the lock here
1024 if (mStatus == STATUS_ERROR) {
1025 // Per API contract, HAL should act as closed after device error
1026 // But mStatus can be set to error by framework as well, so just log
1027 // a warning here.
1028 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001029 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001030
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001031 sp<NotificationListener> listener;
1032 {
1033 std::lock_guard<std::mutex> l(mOutputLock);
1034 listener = mListener.promote();
1035 }
1036
Yifan Honga640c5a2017-04-12 16:30:31 -07001037 if (mProcessCaptureResultLock.tryLock() != OK) {
1038 // This should never happen; it indicates a wrong client implementation
1039 // that doesn't follow the contract. But, we can be tolerant here.
1040 ALOGE("%s: callback overlapped! waiting 1s...",
1041 __FUNCTION__);
1042 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1043 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1044 __FUNCTION__);
1045 // really don't know what to do, so bail out.
1046 return hardware::Void();
1047 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 CaptureOutputStates states {
1050 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001051 mInFlightLock, mLastCompletedRegularFrameNumber,
1052 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1053 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001054 mNextShutterFrameNumber,
1055 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1056 mNextResultFrameNumber,
1057 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1058 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1059 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001060 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001061 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1062 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001063 };
1064
Yifan Honga640c5a2017-04-12 16:30:31 -07001065 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001066 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001067 }
1068 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return hardware::Void();
1070}
1071
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001072// Only one processCaptureResult should be called at a time, so
1073// the locks won't block. The locks are present here simply to enforce this.
1074hardware::Return<void> Camera3Device::processCaptureResult(
1075 const hardware::hidl_vec<
1076 hardware::camera::device::V3_2::CaptureResult>& results) {
1077 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1078
1079 // Ideally we should grab mLock, but that can lead to deadlock, and
1080 // it's not super important to get up to date value of mStatus for this
1081 // warning print, hence skipping the lock here
1082 if (mStatus == STATUS_ERROR) {
1083 // Per API contract, HAL should act as closed after device error
1084 // But mStatus can be set to error by framework as well, so just log
1085 // a warning here.
1086 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1087 }
1088
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001089 sp<NotificationListener> listener;
1090 {
1091 std::lock_guard<std::mutex> l(mOutputLock);
1092 listener = mListener.promote();
1093 }
1094
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001095 if (mProcessCaptureResultLock.tryLock() != OK) {
1096 // This should never happen; it indicates a wrong client implementation
1097 // that doesn't follow the contract. But, we can be tolerant here.
1098 ALOGE("%s: callback overlapped! waiting 1s...",
1099 __FUNCTION__);
1100 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1101 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1102 __FUNCTION__);
1103 // really don't know what to do, so bail out.
1104 return hardware::Void();
1105 }
1106 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001107
1108 CaptureOutputStates states {
1109 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001110 mInFlightLock, mLastCompletedRegularFrameNumber,
1111 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1112 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 mNextShutterFrameNumber,
1114 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1115 mNextResultFrameNumber,
1116 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1117 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1118 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001119 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001120 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1121 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001122 };
1123
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001124 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001125 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001126 }
1127 mProcessCaptureResultLock.unlock();
1128 return hardware::Void();
1129}
1130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001131hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001132 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133 // Ideally we should grab mLock, but that can lead to deadlock, and
1134 // it's not super important to get up to date value of mStatus for this
1135 // warning print, hence skipping the lock here
1136 if (mStatus == STATUS_ERROR) {
1137 // Per API contract, HAL should act as closed after device error
1138 // But mStatus can be set to error by framework as well, so just log
1139 // a warning here.
1140 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001141 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001143 sp<NotificationListener> listener;
1144 {
1145 std::lock_guard<std::mutex> l(mOutputLock);
1146 listener = mListener.promote();
1147 }
1148
1149 CaptureOutputStates states {
1150 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001151 mInFlightLock, mLastCompletedRegularFrameNumber,
1152 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1153 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 mNextShutterFrameNumber,
1155 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1156 mNextResultFrameNumber,
1157 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1158 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1159 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001160 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
Shuzhen Wang316781a2020-08-18 18:11:01 -07001161 mTagMonitor, mInputStream, mOutputStreams, mSessionStatsBuilder, listener, *this, *this,
1162 *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001163 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001165 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001166 }
1167 return hardware::Void();
1168}
1169
Emilian Peevaebbe412018-01-15 13:53:24 +00001170status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001171 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001172 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001173 ATRACE_CALL();
1174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001176}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001177
Jianing Weicb0652e2014-03-12 18:29:36 -07001178status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1179 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001180 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001183 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001185
Emilian Peevaebbe412018-01-15 13:53:24 +00001186 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001187 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001188}
1189
Emilian Peevaebbe412018-01-15 13:53:24 +00001190status_t Camera3Device::setStreamingRequestList(
1191 const List<const PhysicalCameraSettingsList> &requestsList,
1192 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001193 ATRACE_CALL();
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001196}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197
1198sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 status_t res;
1201
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001203 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1204 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001205 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1206 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001207 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001209 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001210 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001211 } else if (mStatus == STATUS_UNCONFIGURED) {
1212 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 CLOGE("No streams configured");
1214 return NULL;
1215 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 }
1217
Shuzhen Wang0129d522016-10-30 22:43:41 -07001218 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001220}
1221
Jianing Weicb0652e2014-03-12 18:29:36 -07001222status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001223 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001224 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001226
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001227 switch (mStatus) {
1228 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001234 case STATUS_UNCONFIGURED:
1235 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001236 case STATUS_ACTIVE:
1237 // OK
1238 break;
1239 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001240 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 return INVALID_OPERATION;
1242 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001243 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001244
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001245 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
1248status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001252 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001253}
1254
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255status_t Camera3Device::createInputStream(
1256 uint32_t width, uint32_t height, int format, int *id) {
1257 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001259 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001260 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001261 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1262 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001263
1264 status_t res;
1265 bool wasActive = false;
1266
1267 switch (mStatus) {
1268 case STATUS_ERROR:
1269 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1270 return INVALID_OPERATION;
1271 case STATUS_UNINITIALIZED:
1272 ALOGE("%s: Device not initialized", __FUNCTION__);
1273 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 case STATUS_UNCONFIGURED:
1275 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 // OK
1277 break;
1278 case STATUS_ACTIVE:
1279 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001280 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001283 return res;
1284 }
1285 wasActive = true;
1286 break;
1287 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001288 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 return INVALID_OPERATION;
1290 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001291 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 if (mInputStream != 0) {
1294 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 }
1297
1298 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1299 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001300 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301
1302 mInputStream = newStream;
1303
1304 *id = mNextStreamId++;
1305
1306 // Continue captures if active at start
1307 if (wasActive) {
1308 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001309 // Reuse current operating mode and session parameters for new stream config
1310 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001311 if (res != OK) {
1312 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1313 __FUNCTION__, mNextStreamId, strerror(-res), res);
1314 return res;
1315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317 }
1318
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001319 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001320 return OK;
1321}
1322
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001323status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001324 uint32_t width, uint32_t height, int format,
1325 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001326 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001327 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001328 ATRACE_CALL();
1329
1330 if (consumer == nullptr) {
1331 ALOGE("%s: consumer must not be null", __FUNCTION__);
1332 return BAD_VALUE;
1333 }
1334
1335 std::vector<sp<Surface>> consumers;
1336 consumers.push_back(consumer);
1337
1338 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1340 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001341}
1342
1343status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1344 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1345 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001346 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001347 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001348 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001349
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001350 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001351 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001352 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001353 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001354 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1355 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1356 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001358 status_t res;
1359 bool wasActive = false;
1360
1361 switch (mStatus) {
1362 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001363 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 return INVALID_OPERATION;
1365 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001366 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001368 case STATUS_UNCONFIGURED:
1369 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 // OK
1371 break;
1372 case STATUS_ACTIVE:
1373 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001374 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001376 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 return res;
1378 }
1379 wasActive = true;
1380 break;
1381 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001382 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 return INVALID_OPERATION;
1384 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001385 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001386
1387 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001388
Shuzhen Wang0129d522016-10-30 22:43:41 -07001389 if (consumers.size() == 0 && !hasDeferredConsumer) {
1390 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1391 return BAD_VALUE;
1392 }
Zhijun He5d677d12016-05-29 16:52:39 -07001393
Shuzhen Wang0129d522016-10-30 22:43:41 -07001394 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001395 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1396 return BAD_VALUE;
1397 }
1398
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001400 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001401 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001402 blobBufferSize = getPointCloudBufferSize();
1403 if (blobBufferSize <= 0) {
1404 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1405 return BAD_VALUE;
1406 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001407 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1408 blobBufferSize = width * height;
1409 } else {
1410 blobBufferSize = getJpegBufferSize(width, height);
1411 if (blobBufferSize <= 0) {
1412 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1413 return BAD_VALUE;
1414 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001415 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001416 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001417 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001418 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001419 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1420 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1421 if (rawOpaqueBufferSize <= 0) {
1422 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1423 return BAD_VALUE;
1424 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001426 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001427 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001428 } else if (isShared) {
1429 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1430 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001431 mTimestampOffset, physicalCameraId, streamSetId,
1432 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001433 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001434 newStream = new Camera3OutputStream(mNextStreamId,
1435 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001436 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001437 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001439 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001440 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001441 }
Emilian Peev40ead602017-09-26 15:46:36 +01001442
1443 size_t consumerCount = consumers.size();
1444 for (size_t i = 0; i < consumerCount; i++) {
1445 int id = newStream->getSurfaceId(consumers[i]);
1446 if (id < 0) {
1447 SET_ERR_L("Invalid surface id");
1448 return BAD_VALUE;
1449 }
1450 if (surfaceIds != nullptr) {
1451 surfaceIds->push_back(id);
1452 }
1453 }
1454
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001455 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456
Emilian Peev08dd2452017-04-06 16:55:14 +01001457 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001458
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() &&
1624 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1625 (!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
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001674status_t Camera3Device::createDefaultRequest(int templateId,
1675 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
1679 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1680 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(
1715 (camera3_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;
2164 }
2165 }
2166 listener->notifyIdle(requestCount, resultErrorCount, deviceError, streamStats);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002167 }
2168}
2169
Shuzhen Wang758c2152017-01-10 18:26:18 -08002170status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002171 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002172 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002173 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2174 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002175
2176 if (surfaceIds == nullptr) {
2177 return BAD_VALUE;
2178 }
2179
Zhijun He5d677d12016-05-29 16:52:39 -07002180 Mutex::Autolock il(mInterfaceLock);
2181 Mutex::Autolock l(mLock);
2182
Shuzhen Wang758c2152017-01-10 18:26:18 -08002183 if (consumers.size() == 0) {
2184 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002185 return BAD_VALUE;
2186 }
2187
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002188 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2189 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002190 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002191 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002192 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002193
2194 // isConsumerConfigurationDeferred will be off after setConsumers
2195 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002196 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002197 if (res != OK) {
2198 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2199 return res;
2200 }
2201
Emilian Peev40ead602017-09-26 15:46:36 +01002202 for (auto &consumer : consumers) {
2203 int id = stream->getSurfaceId(consumer);
2204 if (id < 0) {
2205 CLOGE("Invalid surface id!");
2206 return BAD_VALUE;
2207 }
2208 surfaceIds->push_back(id);
2209 }
2210
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002211 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002212 if (!stream->isConfiguring()) {
2213 CLOGE("Stream %d was already fully configured.", streamId);
2214 return INVALID_OPERATION;
2215 }
Zhijun He5d677d12016-05-29 16:52:39 -07002216
Shuzhen Wang0129d522016-10-30 22:43:41 -07002217 res = stream->finishConfiguration();
2218 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002219 // If finishConfiguration fails due to abandoned surface, do not set
2220 // device to error state.
2221 bool isSurfaceAbandoned =
2222 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2223 if (!isSurfaceAbandoned) {
2224 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2225 stream->getId(), strerror(-res), res);
2226 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002227 return res;
2228 }
Zhijun He5d677d12016-05-29 16:52:39 -07002229 }
2230
2231 return OK;
2232}
2233
Emilian Peev40ead602017-09-26 15:46:36 +01002234status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2235 const std::vector<OutputStreamInfo> &outputInfo,
2236 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2237 Mutex::Autolock il(mInterfaceLock);
2238 Mutex::Autolock l(mLock);
2239
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002240 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2241 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002242 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002243 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002244 }
2245
2246 for (const auto &it : removedSurfaceIds) {
2247 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2248 CLOGE("Shared surface still part of a pending request!");
2249 return -EBUSY;
2250 }
2251 }
2252
Emilian Peev40ead602017-09-26 15:46:36 +01002253 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2254 if (res != OK) {
2255 CLOGE("Stream %d failed to update stream (error %d %s) ",
2256 streamId, res, strerror(-res));
2257 if (res == UNKNOWN_ERROR) {
2258 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2259 __FUNCTION__);
2260 }
2261 return res;
2262 }
2263
2264 return res;
2265}
2266
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002267status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2268 Mutex::Autolock il(mInterfaceLock);
2269 Mutex::Autolock l(mLock);
2270
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002271 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2272 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002273 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2274 return BAD_VALUE;
2275 }
Shuzhen Wang316781a2020-08-18 18:11:01 -07002276
2277 if (dropping) {
2278 mSessionStatsBuilder.stopCounter(streamId);
2279 } else {
2280 mSessionStatsBuilder.startCounter(streamId);
2281 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002282 return stream->dropBuffers(dropping);
2283}
2284
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002285/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002286 * Camera3Device private methods
2287 */
2288
2289sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002290 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002293 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002294 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295
2296 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002297 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298 if (inputStreams.count > 0) {
2299 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002300 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002301 CLOGE("Request references unknown input stream %d",
2302 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002303 return NULL;
2304 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002307 SET_ERR_L("%s: input stream %d is not configured!",
2308 __FUNCTION__, mInputStream->getId());
2309 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002311 // Check if stream prepare is blocking requests.
2312 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002313 CLOGE("Request references an input stream that's being prepared!");
2314 return NULL;
2315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316
2317 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002318 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 }
2320
2321 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002322 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002324 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325 return NULL;
2326 }
2327
2328 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002329 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2330 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002331 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002332 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002333 return NULL;
2334 }
Zhijun He5d677d12016-05-29 16:52:39 -07002335 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002336 auto iter = surfaceMap.find(streams.data.i32[i]);
2337 if (iter != surfaceMap.end()) {
2338 const std::vector<size_t>& surfaces = iter->second;
2339 for (const auto& surface : surfaces) {
2340 if (stream->isConsumerConfigurationDeferred(surface)) {
2341 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2342 "due to deferred consumer", stream->getId(), surface);
2343 return NULL;
2344 }
2345 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002346 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002347 }
2348
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002349 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002350 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2351 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002352 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002353 // Check if stream prepare is blocking requests.
2354 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002355 CLOGE("Request references an output stream that's being prepared!");
2356 return NULL;
2357 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002358
2359 newRequest->mOutputStreams.push(stream);
2360 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002361 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002362 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002363
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002364 auto rotateAndCropEntry =
2365 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2366 if (rotateAndCropEntry.count > 0 &&
2367 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2368 newRequest->mRotateAndCropAuto = true;
2369 } else {
2370 newRequest->mRotateAndCropAuto = false;
2371 }
2372
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002373 auto zoomRatioEntry =
2374 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2375 if (zoomRatioEntry.count > 0 &&
2376 zoomRatioEntry.data.f[0] == 1.0f) {
2377 newRequest->mZoomRatioIs1x = true;
2378 } else {
2379 newRequest->mZoomRatioIs1x = false;
2380 }
2381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002382 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002383}
2384
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002385void Camera3Device::cancelStreamsConfigurationLocked() {
2386 int res = OK;
2387 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2388 res = mInputStream->cancelConfiguration();
2389 if (res != OK) {
2390 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2391 mInputStream->getId(), strerror(-res), res);
2392 }
2393 }
2394
2395 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002396 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002397 if (outputStream->isConfiguring()) {
2398 res = outputStream->cancelConfiguration();
2399 if (res != OK) {
2400 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2401 outputStream->getId(), strerror(-res), res);
2402 }
2403 }
2404 }
2405
2406 // Return state to that at start of call, so that future configures
2407 // properly clean things up
2408 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2409 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002410
2411 res = mPreparerThread->resume();
2412 if (res != OK) {
2413 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2414 }
2415}
2416
Emilian Peev0d0191e2020-04-21 17:01:18 -07002417bool Camera3Device::checkAbandonedStreamsLocked() {
2418 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2419 return true;
2420 }
2421
2422 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2423 auto stream = mOutputStreams[i];
2424 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2425 return true;
2426 }
2427 }
2428
2429 return false;
2430}
2431
Emilian Peev3bead5f2020-05-28 17:29:08 -07002432bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002433 ATRACE_CALL();
2434 bool ret = false;
2435
Shuzhen Wang316781a2020-08-18 18:11:01 -07002436 nsecs_t startTime = systemTime();
2437
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002438 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002439 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2440
2441 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002442 if (checkAbandonedStreamsLocked()) {
2443 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2444 __FUNCTION__);
2445 return true;
2446 }
2447
Emilian Peev3bead5f2020-05-28 17:29:08 -07002448 status_t rc = NO_ERROR;
2449 bool markClientActive = false;
2450 if (mStatus == STATUS_ACTIVE) {
2451 markClientActive = true;
2452 mPauseStateNotify = true;
2453 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2454
2455 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2456 }
2457
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002458 if (rc == NO_ERROR) {
2459 mNeedConfig = true;
2460 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2461 if (rc == NO_ERROR) {
2462 ret = true;
2463 mPauseStateNotify = false;
2464 //Moving to active state while holding 'mLock' is important.
2465 //There could be pending calls to 'create-/deleteStream' which
2466 //will trigger another stream configuration while the already
2467 //present streams end up with outstanding buffers that will
2468 //not get drained.
2469 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002470 } else if (rc == DEAD_OBJECT) {
2471 // DEAD_OBJECT can be returned if either the consumer surface is
2472 // abandoned, or the HAL has died.
2473 // - If the HAL has died, configureStreamsLocked call will set
2474 // device to error state,
2475 // - If surface is abandoned, we should not set device to error
2476 // state.
2477 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002478 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002479 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002480 }
2481 } else {
2482 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2483 }
2484
Shuzhen Wang316781a2020-08-18 18:11:01 -07002485 CameraServiceProxyWrapper::logStreamConfigured(mId, mOperatingMode, true /*internalReconfig*/,
2486 ns2ms(systemTime() - startTime));
2487
Emilian Peev3bead5f2020-05-28 17:29:08 -07002488 if (markClientActive) {
2489 mStatusTracker->markComponentActive(clientStatusId);
2490 }
2491
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002492 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002493}
2494
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002495status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002496 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497 ATRACE_CALL();
2498 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002499
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002500 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002501 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002502 return INVALID_OPERATION;
2503 }
2504
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002505 if (operatingMode < 0) {
2506 CLOGE("Invalid operating mode: %d", operatingMode);
2507 return BAD_VALUE;
2508 }
2509
2510 bool isConstrainedHighSpeed =
2511 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2512 operatingMode;
2513
2514 if (mOperatingMode != operatingMode) {
2515 mNeedConfig = true;
2516 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2517 mOperatingMode = operatingMode;
2518 }
2519
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002520 // In case called from configureStreams, abort queued input buffers not belonging to
2521 // any pending requests.
2522 if (mInputStream != NULL && notifyRequestThread) {
2523 while (true) {
2524 camera3_stream_buffer_t inputBuffer;
2525 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2526 /*respectHalLimit*/ false);
2527 if (res != OK) {
2528 // Exhausted acquiring all input buffers.
2529 break;
2530 }
2531
2532 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2533 res = mInputStream->returnInputBuffer(inputBuffer);
2534 if (res != OK) {
2535 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2536 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2537 }
2538 }
2539 }
2540
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002541 if (!mNeedConfig) {
2542 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2543 return OK;
2544 }
2545
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002546 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002547 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002548 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2549 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002550 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002551 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002552 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002553 }
2554
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002555 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002556 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002557
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002558 mPreparerThread->pause();
2559
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002561 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002562 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2563
2564 Vector<camera3_stream_t*> streams;
2565 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002566 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002567
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002568
2569 if (mInputStream != NULL) {
2570 camera3_stream_t *inputStream;
2571 inputStream = mInputStream->startConfiguration();
2572 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002573 CLOGE("Can't start input stream configuration");
2574 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002575 return INVALID_OPERATION;
2576 }
2577 streams.add(inputStream);
2578 }
2579
2580 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002581
2582 // Don't configure bidi streams twice, nor add them twice to the list
2583 if (mOutputStreams[i].get() ==
2584 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2585
2586 config.num_streams--;
2587 continue;
2588 }
2589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002590 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002591 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002593 CLOGE("Can't start output stream configuration");
2594 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595 return INVALID_OPERATION;
2596 }
2597 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002598
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002599 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002600 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2601 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002602 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2603 bufferSizes[k] = static_cast<uint32_t>(
2604 getJpegBufferSize(outputStream->width, outputStream->height));
2605 } else if (outputStream->data_space ==
2606 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2607 bufferSizes[k] = outputStream->width * outputStream->height;
2608 } else {
2609 ALOGW("%s: Blob dataSpace %d not supported",
2610 __FUNCTION__, outputStream->data_space);
2611 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002612 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002613 }
2614
2615 config.streams = streams.editArray();
2616
2617 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002618 // max_buffers, usage, and priv fields, as well as data_space and format
2619 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002620
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002621 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002622 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002623 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002624
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002625 if (res == BAD_VALUE) {
2626 // HAL rejected this set of streams as unsupported, clean up config
2627 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002628 CLOGE("Set of requested inputs/outputs not supported by HAL");
2629 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002630 return BAD_VALUE;
2631 } else if (res != OK) {
2632 // Some other kind of error from configure_streams - this is not
2633 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002634 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2635 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002636 return res;
2637 }
2638
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002639 // Finish all stream configuration immediately.
2640 // TODO: Try to relax this later back to lazy completion, which should be
2641 // faster
2642
Igor Murashkin073f8572013-05-02 14:59:28 -07002643 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002644 bool streamReConfigured = false;
2645 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002646 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002647 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002648 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002649 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002650 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2651 return DEAD_OBJECT;
2652 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002653 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002654 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002655 if (streamReConfigured) {
2656 mInterface->onStreamReConfigured(mInputStream->getId());
2657 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002658 }
2659
2660 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002661 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002662 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002663 bool streamReConfigured = false;
2664 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002665 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002666 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002667 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002668 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002669 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2670 return DEAD_OBJECT;
2671 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002672 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002673 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002674 if (streamReConfigured) {
2675 mInterface->onStreamReConfigured(outputStream->getId());
2676 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002677 }
2678 }
2679
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 // Request thread needs to know to avoid using repeat-last-settings protocol
2681 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002682 if (notifyRequestThread) {
2683 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2684 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002685
Zhijun He90f7c372016-08-16 16:19:43 -07002686 char value[PROPERTY_VALUE_MAX];
2687 property_get("camera.fifo.disable", value, "0");
2688 int32_t disableFifo = atoi(value);
2689 if (disableFifo != 1) {
2690 // Boost priority of request thread to SCHED_FIFO.
2691 pid_t requestThreadTid = mRequestThread->getTid();
2692 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002693 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002694 if (res != OK) {
2695 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2696 strerror(-res), res);
2697 } else {
2698 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2699 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002700 }
2701
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002702 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002703 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2704 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2705 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2706 sessionParams.unlock(newSessionParams);
2707 mSessionParams.unlock(currentSessionParams);
2708 if (updateSessionParams) {
2709 mSessionParams = sessionParams;
2710 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002712 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002713
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002714 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002715 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002716
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002717 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002718
Zhijun He0a210512014-07-24 13:45:15 -07002719 // tear down the deleted streams after configure streams.
2720 mDeletedStreams.clear();
2721
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002722 auto rc = mPreparerThread->resume();
2723 if (rc != OK) {
2724 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2725 return rc;
2726 }
2727
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002728 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002729 mRequestBufferSM.onStreamsConfigured();
2730 }
2731
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002732 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002733}
2734
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002735status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002736 ATRACE_CALL();
2737 status_t res;
2738
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002739 if (mFakeStreamId != NO_STREAM) {
2740 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002741 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002742 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002743 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002744 return INVALID_OPERATION;
2745 }
2746
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002747 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002748
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002749 sp<Camera3OutputStreamInterface> fakeStream =
2750 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002751
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002752 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002753 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002754 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002755 return res;
2756 }
2757
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002758 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002759 mNextStreamId++;
2760
2761 return OK;
2762}
2763
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002764status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002765 ATRACE_CALL();
2766 status_t res;
2767
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002768 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002769 if (mOutputStreams.size() == 1) return OK;
2770
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002771 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002772
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002773 // Ok, have a fake stream and there's at least one other output stream,
2774 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002775
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002776 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002777 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002778 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002779 return INVALID_OPERATION;
2780 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002781 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002782
2783 // Free up the stream endpoint so that it can be used by some other stream
2784 res = deletedStream->disconnect();
2785 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002786 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002787 // fall through since we want to still list the stream as deleted.
2788 }
2789 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002790 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002791
2792 return res;
2793}
2794
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002795void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002796 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002797 Mutex::Autolock l(mLock);
2798 va_list args;
2799 va_start(args, fmt);
2800
2801 setErrorStateLockedV(fmt, args);
2802
2803 va_end(args);
2804}
2805
2806void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002807 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002808 Mutex::Autolock l(mLock);
2809 setErrorStateLockedV(fmt, args);
2810}
2811
2812void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2813 va_list args;
2814 va_start(args, fmt);
2815
2816 setErrorStateLockedV(fmt, args);
2817
2818 va_end(args);
2819}
2820
2821void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002822 // Print out all error messages to log
2823 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002825
2826 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002827 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002828
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002829 mErrorCause = errorCause;
2830
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002831 if (mRequestThread != nullptr) {
2832 mRequestThread->setPaused(true);
2833 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002834 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002835
2836 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002837 sp<NotificationListener> listener = mListener.promote();
2838 if (listener != NULL) {
2839 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002840 CaptureResultExtras());
Shuzhen Wang316781a2020-08-18 18:11:01 -07002841 mSessionStatsBuilder.onDeviceError();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002842 }
2843
2844 // Save stack trace. View by dumping it later.
2845 CameraTraces::saveTrace();
2846 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002847}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002848
2849/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002850 * In-flight request management
2851 */
2852
Jianing Weicb0652e2014-03-12 18:29:36 -07002853status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002854 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002855 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002856 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002857 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002858 const SurfaceMap& outputSurfaces, nsecs_t requestTimeNs) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002859 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002860 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002861
2862 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002863 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002864 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002865 rotateAndCropAuto, cameraIdsWithZoom, requestTimeNs, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002866 if (res < 0) return res;
2867
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002868 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002869 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2870 // avoid a deadlock during reprocess requests.
2871 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002872 if (mStatusTracker != nullptr) {
2873 mStatusTracker->markComponentActive(mInFlightStatusId);
2874 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002875 }
2876
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002877 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002878 return OK;
2879}
2880
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002881void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002882 // Indicate idle inFlightMap to the status tracker
2883 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002884 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002885 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2886 // avoid a deadlock during reprocess requests.
2887 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002888 if (mStatusTracker != nullptr) {
2889 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2890 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002891 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002892 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002893}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002894
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002895void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002896 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002897 // something has likely gone wrong. This might still be legit only if application send in
2898 // a long burst of long exposure requests.
2899 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2900 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2901 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2902 mInFlightMap.size(), mExpectedInflightDuration);
2903 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2904 kInFlightWarnLimitHighSpeed) {
2905 CLOGW("In-flight list too large for high speed configuration: %zu,"
2906 "total inflight duration %" PRIu64,
2907 mInFlightMap.size(), mExpectedInflightDuration);
2908 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002909 }
2910}
2911
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002912void Camera3Device::onInflightMapFlushedLocked() {
2913 mExpectedInflightDuration = 0;
2914}
2915
2916void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002917 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002918 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2919 mInFlightMap.removeItemsAt(idx, 1);
2920
2921 onInflightEntryRemovedLocked(duration);
2922}
2923
2924
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002925void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002927 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002928 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002929 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002930 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002931 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002932
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002933 FlushInflightReqStates states {
2934 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
Shuzhen Wang316781a2020-08-18 18:11:01 -07002935 listener, *this, *mInterface, *this, mSessionStatsBuilder};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002936
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002937 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002938}
2939
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002940CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002941 ALOGV("%s", __FUNCTION__);
2942
Igor Murashkin1e479c02013-09-06 16:55:14 -07002943 CameraMetadata retVal;
2944
2945 if (mRequestThread != NULL) {
2946 retVal = mRequestThread->getLatestRequest();
2947 }
2948
Igor Murashkin1e479c02013-09-06 16:55:14 -07002949 return retVal;
2950}
2951
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002952void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002953 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2954 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2955
2956 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2957 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002958}
2959
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002960/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002961 * HalInterface inner class methods
2962 */
2963
Yifan Hongf79b5542017-04-11 14:44:25 -07002964Camera3Device::HalInterface::HalInterface(
2965 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002966 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002967 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002968 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002969 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002970 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002971 mIsReconfigurationQuerySupported(true),
2972 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002973 // Check with hardware service manager if we can downcast these interfaces
2974 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002975 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2976 if (castResult_3_6.isOk()) {
2977 mHidlSession_3_6 = castResult_3_6;
2978 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002979 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2980 if (castResult_3_5.isOk()) {
2981 mHidlSession_3_5 = castResult_3_5;
2982 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002983 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2984 if (castResult_3_4.isOk()) {
2985 mHidlSession_3_4 = castResult_3_4;
2986 }
2987 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2988 if (castResult_3_3.isOk()) {
2989 mHidlSession_3_3 = castResult_3_3;
2990 }
2991}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002992
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002993Camera3Device::HalInterface::HalInterface() :
2994 mUseHalBufManager(false),
2995 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002996
2997Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002998 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002999 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003000 mUseHalBufManager(other.mUseHalBufManager),
3001 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003002
3003bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003004 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003005}
3006
3007void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003008 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00003009 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003010 mHidlSession_3_4.clear();
3011 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003012 mHidlSession.clear();
3013}
3014
3015status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3016 camera3_request_template_t templateId,
3017 /*out*/ camera_metadata_t **requestTemplate) {
3018 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3019 if (!valid()) return INVALID_OPERATION;
3020 status_t res = OK;
3021
Emilian Peev31abd0a2017-05-11 18:37:46 +01003022 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003023
3024 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003025 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003026 status = s;
3027 if (status == common::V1_0::Status::OK) {
3028 const camera_metadata *r =
3029 reinterpret_cast<const camera_metadata_t*>(request.data());
3030 size_t expectedSize = request.size();
3031 int ret = validate_camera_metadata_structure(r, &expectedSize);
3032 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3033 *requestTemplate = clone_camera_metadata(r);
3034 if (*requestTemplate == nullptr) {
3035 ALOGE("%s: Unable to clone camera metadata received from HAL",
3036 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003037 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003038 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003039 } else {
3040 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3041 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003042 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003043 }
3044 };
3045 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003046 RequestTemplate id;
3047 switch (templateId) {
3048 case CAMERA3_TEMPLATE_PREVIEW:
3049 id = RequestTemplate::PREVIEW;
3050 break;
3051 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3052 id = RequestTemplate::STILL_CAPTURE;
3053 break;
3054 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3055 id = RequestTemplate::VIDEO_RECORD;
3056 break;
3057 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3058 id = RequestTemplate::VIDEO_SNAPSHOT;
3059 break;
3060 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3061 id = RequestTemplate::ZERO_SHUTTER_LAG;
3062 break;
3063 case CAMERA3_TEMPLATE_MANUAL:
3064 id = RequestTemplate::MANUAL;
3065 break;
3066 default:
3067 // Unknown template ID, or this HAL is too old to support it
3068 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003069 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003070 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003071
Emilian Peev31abd0a2017-05-11 18:37:46 +01003072 if (!err.isOk()) {
3073 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3074 res = DEAD_OBJECT;
3075 } else {
3076 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003077 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003078
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003079 return res;
3080}
3081
Emilian Peev4ec17882019-01-24 17:16:58 -08003082bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3083 CameraMetadata& newSessionParams) {
3084 // We do reconfiguration by default;
3085 bool ret = true;
3086 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3087 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3088 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3089 oldSessionParams.getAndLock());
3090 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3091 newSessionParams.getAndLock());
3092 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3093 get_camera_metadata_size(oldSessioMeta));
3094 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3095 get_camera_metadata_size(newSessioMeta));
3096 hardware::camera::common::V1_0::Status callStatus;
3097 bool required;
3098 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3099 bool requiredFlag) {
3100 callStatus = s;
3101 required = requiredFlag;
3102 };
3103 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3104 oldSessionParams.unlock(oldSessioMeta);
3105 newSessionParams.unlock(newSessioMeta);
3106 if (err.isOk()) {
3107 switch (callStatus) {
3108 case hardware::camera::common::V1_0::Status::OK:
3109 ret = required;
3110 break;
3111 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3112 mIsReconfigurationQuerySupported = false;
3113 ret = true;
3114 break;
3115 default:
3116 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3117 ret = true;
3118 }
3119 } else {
3120 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3121 ret = true;
3122 }
3123 }
3124
3125 return ret;
3126}
3127
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003128status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003129 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003130 ATRACE_NAME("CameraHal::configureStreams");
3131 if (!valid()) return INVALID_OPERATION;
3132 status_t res = OK;
3133
Emilian Peev31abd0a2017-05-11 18:37:46 +01003134 // Convert stream config to HIDL
3135 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003136 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3137 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3138 requestedConfiguration3_2.streams.resize(config->num_streams);
3139 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003140 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003141 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3142 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003143 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003144
Emilian Peev31abd0a2017-05-11 18:37:46 +01003145 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3146 cam3stream->setBufferFreedListener(this);
3147 int streamId = cam3stream->getId();
3148 StreamType streamType;
3149 switch (src->stream_type) {
3150 case CAMERA3_STREAM_OUTPUT:
3151 streamType = StreamType::OUTPUT;
3152 break;
3153 case CAMERA3_STREAM_INPUT:
3154 streamType = StreamType::INPUT;
3155 break;
3156 default:
3157 ALOGE("%s: Stream %d: Unsupported stream type %d",
3158 __FUNCTION__, streamId, config->streams[i]->stream_type);
3159 return BAD_VALUE;
3160 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003161 dst3_2.id = streamId;
3162 dst3_2.streamType = streamType;
3163 dst3_2.width = src->width;
3164 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003165 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003166 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003167 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3168 // to HAL are original, not the overriden ones.
3169 if (mHidlSession_3_5 != nullptr) {
3170 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3171 cam3stream->getOriginalFormat() : src->format);
3172 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3173 cam3stream->getOriginalDataSpace() : src->data_space);
3174 } else {
3175 dst3_2.format = mapToPixelFormat(src->format);
3176 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3177 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003178 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003179 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003180 if (src->physical_camera_id != nullptr) {
3181 dst3_4.physicalCameraId = src->physical_camera_id;
3182 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003183
3184 activeStreams.insert(streamId);
3185 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003186 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003187 }
3188 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003189 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003190
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003191 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003192 res = mapToStreamConfigurationMode(
3193 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003194 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003195 if (res != OK) {
3196 return res;
3197 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003198 requestedConfiguration3_2.operationMode = operationMode;
3199 requestedConfiguration3_4.operationMode = operationMode;
3200 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003201 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3202 get_camera_metadata_size(sessionParams));
3203
Emilian Peev31abd0a2017-05-11 18:37:46 +01003204 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003205 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003206 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003207 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003208 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003209
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003210 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003211 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3212 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003213 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003214 };
3215
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003216 auto configStream36Cb = [&status, &finalConfiguration3_6]
3217 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3218 finalConfiguration3_6 = halConfiguration;
3219 status = s;
3220 };
3221
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003222 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3223 (hardware::Return<void>& err) -> status_t {
3224 if (!err.isOk()) {
3225 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3226 return DEAD_OBJECT;
3227 }
3228 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3229 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3230 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3231 }
3232 return OK;
3233 };
3234
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003235 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3236 (hardware::Return<void>& err) -> status_t {
3237 if (!err.isOk()) {
3238 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3239 return DEAD_OBJECT;
3240 }
3241 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3242 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3243 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3244 }
3245 return OK;
3246 };
3247
Shuzhen Wang92653952019-05-07 15:11:43 -07003248 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003249 if (mHidlSession_3_6 != nullptr) {
3250 ALOGV("%s: v3.6 device found", __FUNCTION__);
3251 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3252 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3253 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3254 auto err = mHidlSession_3_6->configureStreams_3_6(
3255 requestedConfiguration3_5, configStream36Cb);
3256 res = postprocConfigStream36(err);
3257 if (res != OK) {
3258 return res;
3259 }
3260 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003261 ALOGV("%s: v3.5 device found", __FUNCTION__);
3262 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3263 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3264 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3265 auto err = mHidlSession_3_5->configureStreams_3_5(
3266 requestedConfiguration3_5, configStream34Cb);
3267 res = postprocConfigStream34(err);
3268 if (res != OK) {
3269 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003270 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003271 } else if (mHidlSession_3_4 != nullptr) {
3272 // We do; use v3.4 for the call
3273 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003274 auto err = mHidlSession_3_4->configureStreams_3_4(
3275 requestedConfiguration3_4, configStream34Cb);
3276 res = postprocConfigStream34(err);
3277 if (res != OK) {
3278 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003279 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003280 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003281 // We do; use v3.3 for the call
3282 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003283 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003284 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003285 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 finalConfiguration = halConfiguration;
3287 status = s;
3288 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003289 if (!err.isOk()) {
3290 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3291 return DEAD_OBJECT;
3292 }
3293 } else {
3294 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3295 ALOGV("%s: v3.2 device found", __FUNCTION__);
3296 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003297 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003298 [&status, &finalConfiguration_3_2]
3299 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3300 finalConfiguration_3_2 = halConfiguration;
3301 status = s;
3302 });
3303 if (!err.isOk()) {
3304 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3305 return DEAD_OBJECT;
3306 }
3307 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3308 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3309 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3310 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003311 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003312 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 }
3314
3315 if (status != common::V1_0::Status::OK ) {
3316 return CameraProviderManager::mapToStatusT(status);
3317 }
3318
3319 // And convert output stream configuration from HIDL
3320
3321 for (size_t i = 0; i < config->num_streams; i++) {
3322 camera3_stream_t *dst = config->streams[i];
3323 int streamId = Camera3Stream::cast(dst)->getId();
3324
3325 // Start scan at i, with the assumption that the stream order matches
3326 size_t realIdx = i;
3327 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003328 size_t halStreamCount = finalConfiguration.streams.size();
3329 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003330 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003331 found = true;
3332 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003333 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003334 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003335 }
3336 if (!found) {
3337 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3338 __FUNCTION__, streamId);
3339 return INVALID_OPERATION;
3340 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003341 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003342 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003343
Emilian Peev710c1422017-08-30 11:19:38 +01003344 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003345 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3346 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3347
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003348 if (mHidlSession_3_6 != nullptr) {
3349 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3350 }
3351
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003352 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003353 dstStream->setFormatOverride(false);
3354 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003355 if (dst->format != overrideFormat) {
3356 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3357 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003358 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003359 if (dst->data_space != overrideDataSpace) {
3360 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3361 streamId, dst->format);
3362 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003363 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003364 bool needFormatOverride =
3365 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3366 bool needDataspaceOverride =
3367 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003368 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003369 dstStream->setFormatOverride(needFormatOverride);
3370 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003371 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003372 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003373 }
3374
Emilian Peev31abd0a2017-05-11 18:37:46 +01003375 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003376 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003377 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003378 __FUNCTION__, streamId);
3379 return INVALID_OPERATION;
3380 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003381 dstStream->setUsage(
3382 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003383 } else {
3384 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003385 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003386 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3387 __FUNCTION__, streamId);
3388 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003389 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003390 dstStream->setUsage(
3391 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003392 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003393 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003394 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003396 return res;
3397}
3398
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003399status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003400 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003401 /*out*/std::vector<native_handle_t*>* handlesCreated,
3402 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003403 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003404 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3405 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3406 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003407 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003408 }
3409
3410 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003411
3412 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003413
3414 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003415 if (request->input_buffer != nullptr) {
3416 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3417 buffer_handle_t buf = *(request->input_buffer->buffer);
3418 auto pair = getBufferId(buf, streamId);
3419 bool isNewBuffer = pair.first;
3420 uint64_t bufferId = pair.second;
3421 captureRequest->inputBuffer.streamId = streamId;
3422 captureRequest->inputBuffer.bufferId = bufferId;
3423 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3424 captureRequest->inputBuffer.status = BufferStatus::OK;
3425 native_handle_t *acquireFence = nullptr;
3426 if (request->input_buffer->acquire_fence != -1) {
3427 acquireFence = native_handle_create(1,0);
3428 acquireFence->data[0] = request->input_buffer->acquire_fence;
3429 handlesCreated->push_back(acquireFence);
3430 }
3431 captureRequest->inputBuffer.acquireFence = acquireFence;
3432 captureRequest->inputBuffer.releaseFence = nullptr;
3433
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003434 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003435 request->input_buffer->buffer);
3436 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003437 } else {
3438 captureRequest->inputBuffer.streamId = -1;
3439 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3440 }
3441
3442 captureRequest->outputBuffers.resize(request->num_output_buffers);
3443 for (size_t i = 0; i < request->num_output_buffers; i++) {
3444 const camera3_stream_buffer_t *src = request->output_buffers + i;
3445 StreamBuffer &dst = captureRequest->outputBuffers[i];
3446 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003447 if (src->buffer != nullptr) {
3448 buffer_handle_t buf = *(src->buffer);
3449 auto pair = getBufferId(buf, streamId);
3450 bool isNewBuffer = pair.first;
3451 dst.bufferId = pair.second;
3452 dst.buffer = isNewBuffer ? buf : nullptr;
3453 native_handle_t *acquireFence = nullptr;
3454 if (src->acquire_fence != -1) {
3455 acquireFence = native_handle_create(1,0);
3456 acquireFence->data[0] = src->acquire_fence;
3457 handlesCreated->push_back(acquireFence);
3458 }
3459 dst.acquireFence = acquireFence;
3460 } else if (mUseHalBufManager) {
3461 // HAL buffer management path
3462 dst.bufferId = BUFFER_ID_NO_BUFFER;
3463 dst.buffer = nullptr;
3464 dst.acquireFence = nullptr;
3465 } else {
3466 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3467 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003468 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003469 dst.streamId = streamId;
3470 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003471 dst.releaseFence = nullptr;
3472
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003473 // Output buffers are empty when using HAL buffer manager
3474 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003475 mBufferRecords.pushInflightBuffer(
3476 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003477 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003478 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003479 }
3480 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003481 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003482}
3483
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003484void Camera3Device::HalInterface::cleanupNativeHandles(
3485 std::vector<native_handle_t*> *handles, bool closeFd) {
3486 if (handles == nullptr) {
3487 return;
3488 }
3489 if (closeFd) {
3490 for (auto& handle : *handles) {
3491 native_handle_close(handle);
3492 }
3493 }
3494 for (auto& handle : *handles) {
3495 native_handle_delete(handle);
3496 }
3497 handles->clear();
3498 return;
3499}
3500
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003501status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3502 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3503 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3504 if (!valid()) return INVALID_OPERATION;
3505
Emilian Peevaebbe412018-01-15 13:53:24 +00003506 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3507 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3508 if (castResult_3_4.isOk()) {
3509 hidlSession_3_4 = castResult_3_4;
3510 }
3511
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003512 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003513 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003514 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003515 if (hidlSession_3_4 != nullptr) {
3516 captureRequests_3_4.resize(batchSize);
3517 } else {
3518 captureRequests.resize(batchSize);
3519 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003520 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003521 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003522
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003523 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003524 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003525 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003526 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003527 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003528 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003529 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3530 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003531 }
3532 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003533 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003534 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003535 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003536 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003537 }
3538
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003539 std::vector<device::V3_2::BufferCache> cachesToRemove;
3540 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003541 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003542 for (auto& pair : mFreedBuffers) {
3543 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003544 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003545 cachesToRemove.push_back({pair.first, pair.second});
3546 }
3547 }
3548 mFreedBuffers.clear();
3549 }
3550
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003551 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3552 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003553
3554 // Write metadata to FMQ.
3555 for (size_t i = 0; i < batchSize; i++) {
3556 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003557 device::V3_2::CaptureRequest* captureRequest;
3558 if (hidlSession_3_4 != nullptr) {
3559 captureRequest = &captureRequests_3_4[i].v3_2;
3560 } else {
3561 captureRequest = &captureRequests[i];
3562 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003563
3564 if (request->settings != nullptr) {
3565 size_t settingsSize = get_camera_metadata_size(request->settings);
3566 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3567 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3568 captureRequest->settings.resize(0);
3569 captureRequest->fmqSettingsSize = settingsSize;
3570 } else {
3571 if (mRequestMetadataQueue != nullptr) {
3572 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3573 }
3574 captureRequest->settings.setToExternal(
3575 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3576 get_camera_metadata_size(request->settings));
3577 captureRequest->fmqSettingsSize = 0u;
3578 }
3579 } else {
3580 // A null request settings maps to a size-0 CameraMetadata
3581 captureRequest->settings.resize(0);
3582 captureRequest->fmqSettingsSize = 0u;
3583 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003584
3585 if (hidlSession_3_4 != nullptr) {
3586 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3587 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003588 if (request->physcam_settings != nullptr) {
3589 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3590 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3591 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3592 settingsSize)) {
3593 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3594 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3595 settingsSize;
3596 } else {
3597 if (mRequestMetadataQueue != nullptr) {
3598 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3599 }
3600 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3601 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3602 request->physcam_settings[j])),
3603 get_camera_metadata_size(request->physcam_settings[j]));
3604 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003605 }
Emilian Peev00420d22018-02-05 21:33:13 +00003606 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003607 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003608 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003609 }
3610 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3611 request->physcam_id[j];
3612 }
3613 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003614 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003615
3616 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003617 auto resultCallback =
3618 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3619 status = s;
3620 *numRequestProcessed = n;
3621 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003622 if (hidlSession_3_4 != nullptr) {
3623 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003624 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003625 } else {
3626 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003627 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003628 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003629 if (!err.isOk()) {
3630 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003631 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003632 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003633
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003634 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3635 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3636 __FUNCTION__, *numRequestProcessed, batchSize);
3637 status = common::V1_0::Status::INTERNAL_ERROR;
3638 }
3639
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003640 res = CameraProviderManager::mapToStatusT(status);
3641 if (res == OK) {
3642 if (mHidlSession->isRemote()) {
3643 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3644 // sent to camera HAL processes)
3645 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3646 } else {
3647 // In passthrough mode the FDs are now owned by HAL
3648 cleanupNativeHandles(&handlesCreated);
3649 }
3650 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003651 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003652 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003653 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003654 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003655}
3656
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003657status_t Camera3Device::HalInterface::flush() {
3658 ATRACE_NAME("CameraHal::flush");
3659 if (!valid()) return INVALID_OPERATION;
3660 status_t res = OK;
3661
Emilian Peev31abd0a2017-05-11 18:37:46 +01003662 auto err = mHidlSession->flush();
3663 if (!err.isOk()) {
3664 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3665 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003666 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003667 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003668 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003669
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003670 return res;
3671}
3672
Emilian Peev31abd0a2017-05-11 18:37:46 +01003673status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003674 ATRACE_NAME("CameraHal::dump");
3675 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003676
Emilian Peev31abd0a2017-05-11 18:37:46 +01003677 // Handled by CameraProviderManager::dump
3678
3679 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003680}
3681
3682status_t Camera3Device::HalInterface::close() {
3683 ATRACE_NAME("CameraHal::close()");
3684 if (!valid()) return INVALID_OPERATION;
3685 status_t res = OK;
3686
Emilian Peev31abd0a2017-05-11 18:37:46 +01003687 auto err = mHidlSession->close();
3688 // Interface will be dead shortly anyway, so don't log errors
3689 if (!err.isOk()) {
3690 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003691 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003692
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003693 return res;
3694}
3695
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003696void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3697 ATRACE_NAME("CameraHal::signalPipelineDrain");
3698 if (!valid() || mHidlSession_3_5 == nullptr) {
3699 ALOGE("%s called on invalid camera!", __FUNCTION__);
3700 return;
3701 }
3702
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003703 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003704 if (!err.isOk()) {
3705 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3706 return;
3707 }
3708}
3709
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003710status_t Camera3Device::HalInterface::switchToOffline(
3711 const std::vector<int32_t>& streamsToKeep,
3712 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003713 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3714 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003715 ATRACE_NAME("CameraHal::switchToOffline");
3716 if (!valid() || mHidlSession_3_6 == nullptr) {
3717 ALOGE("%s called on invalid camera!", __FUNCTION__);
3718 return INVALID_OPERATION;
3719 }
3720
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003721 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3722 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003723 return INVALID_OPERATION;
3724 }
3725
3726 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003727 auto resultCallback =
3728 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3729 status = s;
3730 *offlineSessionInfo = info;
3731 *offlineSession = session;
3732 };
3733 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3734
3735 if (!err.isOk()) {
3736 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3737 return DEAD_OBJECT;
3738 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003739
3740 status_t ret = CameraProviderManager::mapToStatusT(status);
3741 if (ret != OK) {
3742 return ret;
3743 }
3744
3745 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3746 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3747 // returns from switchToOffline.
3748
3749
3750 // Validate buffer caches
3751 std::vector<int32_t> streams;
3752 streams.reserve(offlineSessionInfo->offlineStreams.size());
3753 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3754 int32_t id = offlineStream.id;
3755 streams.push_back(id);
3756 // Verify buffer caches
3757 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3758 offlineStream.circulatingBufferIds.end());
3759 if (!verifyBufferIds(id, bufIds)) {
3760 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3761 return UNKNOWN_ERROR;
3762 }
3763 }
3764
3765 // Move buffer records
3766 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3767 bufferRecords->takeInflightBufferMap(mBufferRecords);
3768 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3769 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003770}
3771
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003772void Camera3Device::HalInterface::getInflightBufferKeys(
3773 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003774 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003775 return;
3776}
3777
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003778void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3779 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003780 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003781 return;
3782}
3783
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003784bool Camera3Device::HalInterface::verifyBufferIds(
3785 int32_t streamId, std::vector<uint64_t>& bufIds) {
3786 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003787}
3788
3789status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003790 int32_t frameNumber, int32_t streamId,
3791 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003792 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003793}
3794
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003795status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003796 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003797 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003798}
3799
3800// Find and pop a buffer_handle_t based on bufferId
3801status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003802 uint64_t bufferId,
3803 /*out*/ buffer_handle_t** buffer,
3804 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003805 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003806}
3807
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003808std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3809 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003810 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003811}
3812
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003813void Camera3Device::HalInterface::onBufferFreed(
3814 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003815 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3816 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3817 if (bufferId != BUFFER_ID_NO_BUFFER) {
3818 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003819 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003820}
3821
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003822void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003823 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3824 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3825 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003826 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3827 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003828}
3829
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003830/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003831 * RequestThread inner class methods
3832 */
3833
3834Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003835 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003836 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3837 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003838 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003839 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003840 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003841 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003842 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003843 mId(getId(parent)),
Shuzhen Wang316781a2020-08-18 18:11:01 -07003844 mFirstRepeating(false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003845 mReconfigured(false),
3846 mDoPause(false),
3847 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003848 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003849 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003850 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003851 mCurrentAfTriggerId(0),
3852 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003853 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003854 mRepeatingLastFrameNumber(
3855 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003856 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003857 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003858 mRequestLatency(kRequestLatencyBinSize),
3859 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003860 mLatestSessionParams(sessionParamKeys.size()),
3861 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003862 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003863}
3864
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003865Camera3Device::RequestThread::~RequestThread() {}
3866
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003867void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003868 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003869 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003870 Mutex::Autolock l(mRequestLock);
3871 mListener = listener;
3872}
3873
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003874void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3875 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003876 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003877 Mutex::Autolock l(mRequestLock);
3878 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003879 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003880 // Prepare video stream for high speed recording.
3881 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003882 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003883}
3884
Jianing Wei90e59c92014-03-12 18:29:36 -07003885status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003886 List<sp<CaptureRequest> > &requests,
3887 /*out*/
3888 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003889 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003890 Mutex::Autolock l(mRequestLock);
3891 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3892 ++it) {
3893 mRequestQueue.push_back(*it);
3894 }
3895
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003896 if (lastFrameNumber != NULL) {
3897 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3898 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3899 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3900 *lastFrameNumber);
3901 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003902
Jianing Wei90e59c92014-03-12 18:29:36 -07003903 unpauseForNewRequests();
3904
3905 return OK;
3906}
3907
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003908
3909status_t Camera3Device::RequestThread::queueTrigger(
3910 RequestTrigger trigger[],
3911 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003912 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003913 Mutex::Autolock l(mTriggerMutex);
3914 status_t ret;
3915
3916 for (size_t i = 0; i < count; ++i) {
3917 ret = queueTriggerLocked(trigger[i]);
3918
3919 if (ret != OK) {
3920 return ret;
3921 }
3922 }
3923
3924 return OK;
3925}
3926
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003927const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3928 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003929 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003930 if (d != nullptr) return d->mId;
3931 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003932}
3933
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003934status_t Camera3Device::RequestThread::queueTriggerLocked(
3935 RequestTrigger trigger) {
3936
3937 uint32_t tag = trigger.metadataTag;
3938 ssize_t index = mTriggerMap.indexOfKey(tag);
3939
3940 switch (trigger.getTagType()) {
3941 case TYPE_BYTE:
3942 // fall-through
3943 case TYPE_INT32:
3944 break;
3945 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003946 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3947 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003948 return INVALID_OPERATION;
3949 }
3950
3951 /**
3952 * Collect only the latest trigger, since we only have 1 field
3953 * in the request settings per trigger tag, and can't send more than 1
3954 * trigger per request.
3955 */
3956 if (index != NAME_NOT_FOUND) {
3957 mTriggerMap.editValueAt(index) = trigger;
3958 } else {
3959 mTriggerMap.add(tag, trigger);
3960 }
3961
3962 return OK;
3963}
3964
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003965status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003966 const RequestList &requests,
3967 /*out*/
3968 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003969 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003970 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003971 if (lastFrameNumber != NULL) {
3972 *lastFrameNumber = mRepeatingLastFrameNumber;
3973 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003974 mRepeatingRequests.clear();
Shuzhen Wang316781a2020-08-18 18:11:01 -07003975 mFirstRepeating = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003976 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3977 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003978
3979 unpauseForNewRequests();
3980
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003981 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003982 return OK;
3983}
3984
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003985bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003986 if (mRepeatingRequests.empty()) {
3987 return false;
3988 }
3989 int32_t requestId = requestIn->mResultExtras.requestId;
3990 const RequestList &repeatRequests = mRepeatingRequests;
3991 // All repeating requests are guaranteed to have same id so only check first quest
3992 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3993 return (firstRequest->mResultExtras.requestId == requestId);
3994}
3995
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003996status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003997 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003998 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003999 return clearRepeatingRequestsLocked(lastFrameNumber);
4000
4001}
4002
4003status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004004 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004005 if (lastFrameNumber != NULL) {
4006 *lastFrameNumber = mRepeatingLastFrameNumber;
4007 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004008 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004009 return OK;
4010}
4011
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004012status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004013 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004014 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004015 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004016 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004017
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004018 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004019
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004020 // Send errors for all requests pending in the request queue, including
4021 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004022 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004023 if (listener != NULL) {
4024 for (RequestList::iterator it = mRequestQueue.begin();
4025 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004026 // Abort the input buffers for reprocess requests.
4027 if ((*it)->mInputStream != NULL) {
4028 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004029 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4030 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004031 if (res != OK) {
4032 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4033 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4034 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07004035 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004036 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4037 if (res != OK) {
4038 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4039 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4040 }
4041 }
4042 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004043 // Set the frame number this request would have had, if it
4044 // had been submitted; this frame number will not be reused.
4045 // The requestId and burstId fields were set when the request was
4046 // submitted originally (in convertMetadataListToRequestListLocked)
4047 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004048 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004049 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004050 }
4051 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004052 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004053
4054 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004055 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004056 if (lastFrameNumber != NULL) {
4057 *lastFrameNumber = mRepeatingLastFrameNumber;
4058 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004059 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08004060 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004061 return OK;
4062}
4063
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004064status_t Camera3Device::RequestThread::flush() {
4065 ATRACE_CALL();
4066 Mutex::Autolock l(mFlushLock);
4067
Emilian Peev08dd2452017-04-06 16:55:14 +01004068 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004069}
4070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004071void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004072 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004073 Mutex::Autolock l(mPauseLock);
4074 mDoPause = paused;
4075 mDoPauseSignal.signal();
4076}
4077
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004078status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4079 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004080 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004081 Mutex::Autolock l(mLatestRequestMutex);
4082 status_t res;
4083 while (mLatestRequestId != requestId) {
4084 nsecs_t startTime = systemTime();
4085
4086 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4087 if (res != OK) return res;
4088
4089 timeout -= (systemTime() - startTime);
4090 }
4091
4092 return OK;
4093}
4094
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004095void Camera3Device::RequestThread::requestExit() {
4096 // Call parent to set up shutdown
4097 Thread::requestExit();
4098 // The exit from any possible waits
4099 mDoPauseSignal.signal();
4100 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004101
4102 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4103 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004104}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004105
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004106void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004107 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004108 bool surfaceAbandoned = false;
4109 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004110 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004111 {
4112 Mutex::Autolock l(mRequestLock);
4113 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4114 // repeating requests.
4115 for (const auto& request : mRepeatingRequests) {
4116 for (const auto& s : request->mOutputStreams) {
4117 if (s->isAbandoned()) {
4118 surfaceAbandoned = true;
4119 clearRepeatingRequestsLocked(&lastFrameNumber);
4120 break;
4121 }
4122 }
4123 if (surfaceAbandoned) {
4124 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004125 }
4126 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004127 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004128 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004129
4130 if (listener != NULL && surfaceAbandoned) {
4131 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004132 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004133}
4134
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004135bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004136 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004137 status_t res;
4138 size_t batchSize = mNextRequests.size();
4139 std::vector<camera3_capture_request_t*> requests(batchSize);
4140 uint32_t numRequestProcessed = 0;
4141 for (size_t i = 0; i < batchSize; i++) {
4142 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004143 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004144 }
4145
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004146 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4147
4148 bool triggerRemoveFailed = false;
4149 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4150 for (size_t i = 0; i < numRequestProcessed; i++) {
4151 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4152 nextRequest.submitted = true;
4153
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004154 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004155
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004156 if (!triggerRemoveFailed) {
4157 // Remove any previously queued triggers (after unlock)
4158 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4159 if (removeTriggerRes != OK) {
4160 triggerRemoveFailed = true;
4161 triggerFailedRequest = nextRequest;
4162 }
4163 }
4164 }
4165
4166 if (triggerRemoveFailed) {
4167 SET_ERR("RequestThread: Unable to remove triggers "
4168 "(capture request %d, HAL device: %s (%d)",
4169 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4170 cleanUpFailedRequests(/*sendRequestError*/ false);
4171 return false;
4172 }
4173
4174 if (res != OK) {
4175 // Should only get a failure here for malformed requests or device-level
4176 // errors, so consider all errors fatal. Bad metadata failures should
4177 // come through notify.
4178 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4179 mNextRequests[numRequestProcessed].halRequest.frame_number,
4180 strerror(-res), res);
4181 cleanUpFailedRequests(/*sendRequestError*/ false);
4182 return false;
4183 }
4184 return true;
4185}
4186
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004187nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4188 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4189 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4190 find_camera_metadata_ro_entry(request,
4191 ANDROID_CONTROL_AE_MODE,
4192 &e);
4193 if (e.count == 0) return maxExpectedDuration;
4194
4195 switch (e.data.u8[0]) {
4196 case ANDROID_CONTROL_AE_MODE_OFF:
4197 find_camera_metadata_ro_entry(request,
4198 ANDROID_SENSOR_EXPOSURE_TIME,
4199 &e);
4200 if (e.count > 0) {
4201 maxExpectedDuration = e.data.i64[0];
4202 }
4203 find_camera_metadata_ro_entry(request,
4204 ANDROID_SENSOR_FRAME_DURATION,
4205 &e);
4206 if (e.count > 0) {
4207 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4208 }
4209 break;
4210 default:
4211 find_camera_metadata_ro_entry(request,
4212 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4213 &e);
4214 if (e.count > 1) {
4215 maxExpectedDuration = 1e9 / e.data.u8[0];
4216 }
4217 break;
4218 }
4219
4220 return maxExpectedDuration;
4221}
4222
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004223bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4224 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4225 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4226 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4227 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4228 return true;
4229 }
4230
4231 return false;
4232}
4233
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004234void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4235 // Update the latest request sent to HAL
4236 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4237 Mutex::Autolock al(mLatestRequestMutex);
4238
4239 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4240 mLatestRequest.acquire(cloned);
4241
4242 mLatestPhysicalRequest.clear();
4243 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4244 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4245 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4246 CameraMetadata(cloned));
4247 }
4248
4249 sp<Camera3Device> parent = mParent.promote();
4250 if (parent != NULL) {
4251 parent->monitorMetadata(TagMonitor::REQUEST,
4252 nextRequest.halRequest.frame_number,
4253 0, mLatestRequest, mLatestPhysicalRequest);
4254 }
4255 }
4256
4257 if (nextRequest.halRequest.settings != NULL) {
4258 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4259 nextRequest.halRequest.settings);
4260 }
4261
4262 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4263}
4264
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004265bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4266 ATRACE_CALL();
4267 bool updatesDetected = false;
4268
Emilian Peev4ec17882019-01-24 17:16:58 -08004269 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004270 for (auto tag : mSessionParamKeys) {
4271 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004272 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004273
4274 if (entry.count > 0) {
4275 bool isDifferent = false;
4276 if (lastEntry.count > 0) {
4277 // Have a last value, compare to see if changed
4278 if (lastEntry.type == entry.type &&
4279 lastEntry.count == entry.count) {
4280 // Same type and count, compare values
4281 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4282 size_t entryBytes = bytesPerValue * lastEntry.count;
4283 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4284 if (cmp != 0) {
4285 isDifferent = true;
4286 }
4287 } else {
4288 // Count or type has changed
4289 isDifferent = true;
4290 }
4291 } else {
4292 // No last entry, so always consider to be different
4293 isDifferent = true;
4294 }
4295
4296 if (isDifferent) {
4297 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004298 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4299 updatesDetected = true;
4300 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004301 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004302 }
4303 } else if (lastEntry.count > 0) {
4304 // Value has been removed
4305 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004306 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004307 updatesDetected = true;
4308 }
4309 }
4310
Emilian Peev4ec17882019-01-24 17:16:58 -08004311 bool reconfigureRequired;
4312 if (updatesDetected) {
4313 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4314 updatedParams);
4315 mLatestSessionParams = updatedParams;
4316 } else {
4317 reconfigureRequired = false;
4318 }
4319
4320 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004321}
4322
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004323bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004324 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004325 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004326 // Any function called from threadLoop() must not hold mInterfaceLock since
4327 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4328 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004329
4330 // Handle paused state.
4331 if (waitIfPaused()) {
4332 return true;
4333 }
4334
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004335 // Wait for the next batch of requests.
4336 waitForNextRequestBatch();
4337 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 return true;
4339 }
4340
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004341 // Get the latest request ID, if any
4342 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004343 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004344 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004345 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004346 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004347 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004348 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4349 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004350 }
4351
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004352 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4353 // or a single request from streaming or burst. In either case the first element
4354 // should contain the latest camera settings that we need to check for any session
4355 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004356 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004357 res = OK;
4358
4359 //Input stream buffers are already acquired at this point so an input stream
4360 //will not be able to move to idle state unless we force it.
4361 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4362 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4363 if (res != OK) {
4364 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4365 cleanUpFailedRequests(/*sendRequestError*/ false);
4366 return false;
4367 }
4368 }
4369
4370 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004371 sp<Camera3Device> parent = mParent.promote();
4372 if (parent != nullptr) {
4373 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004374 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004375 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004376
4377 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4378 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4379 if (res != OK) {
4380 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4381 cleanUpFailedRequests(/*sendRequestError*/ false);
4382 return false;
4383 }
4384 }
4385 }
4386 }
4387
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004388 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004389 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004390 if (res == TIMED_OUT) {
4391 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004392 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004393 // Check if any stream is abandoned.
4394 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004395 return true;
4396 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004397 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004398 return false;
4399 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004400
Zhijun Hecc27e112013-10-03 16:12:43 -07004401 // Inform waitUntilRequestProcessed thread of a new request ID
4402 {
4403 Mutex::Autolock al(mLatestRequestMutex);
4404
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004405 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004406 mLatestRequestSignal.signal();
4407 }
4408
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004409 // Submit a batch of requests to HAL.
4410 // Use flush lock only when submitting multilple requests in a batch.
4411 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4412 // which may take a long time to finish so synchronizing flush() and
4413 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4414 // For now, only synchronize for high speed recording and we should figure something out for
4415 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004416 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004417
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004418 if (useFlushLock) {
4419 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004420 }
4421
Zhijun Hef0645c12016-08-02 00:58:11 -07004422 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004423 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004424
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004425 sp<Camera3Device> parent = mParent.promote();
4426 if (parent != nullptr) {
4427 parent->mRequestBufferSM.onSubmittingRequest();
4428 }
4429
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004430 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004431 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004432 submitRequestSuccess = sendRequestsBatch();
4433
Shuzhen Wang686f6442017-06-20 16:16:04 -07004434 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4435 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004436
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004437 if (useFlushLock) {
4438 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004439 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004440
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004441 // Unset as current request
4442 {
4443 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004444 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004445 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004446 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004447
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004448 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004449}
4450
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004451status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004452 ATRACE_CALL();
4453
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004454 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004455 for (size_t i = 0; i < mNextRequests.size(); i++) {
4456 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004457 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4458 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4459 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4460
4461 // Prepare a request to HAL
4462 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4463
4464 // Insert any queued triggers (before metadata is locked)
4465 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004466 if (res < 0) {
4467 SET_ERR("RequestThread: Unable to insert triggers "
4468 "(capture request %d, HAL device: %s (%d)",
4469 halRequest->frame_number, strerror(-res), res);
4470 return INVALID_OPERATION;
4471 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004472
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004473 int triggerCount = res;
4474 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4475 mPrevTriggers = triggerCount;
4476
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004477 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4478
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004479 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004480 bool newRequest =
4481 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004482 // Request settings are all the same within one batch, so only treat the first
4483 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004484 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004485 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004486 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004487 /**
4488 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004489 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004490 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004491 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004492 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004493 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004494 "(capture request %d, HAL device: %s (%d)",
4495 halRequest->frame_number, strerror(-res), res);
4496 return INVALID_OPERATION;
4497 }
4498
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004499 {
4500 // Correct metadata regions for distortion correction if enabled
4501 sp<Camera3Device> parent = mParent.promote();
4502 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004503 List<PhysicalCameraSettings>::iterator it;
4504 for (it = captureRequest->mSettingsList.begin();
4505 it != captureRequest->mSettingsList.end(); it++) {
4506 if (parent->mDistortionMappers.find(it->cameraId) ==
4507 parent->mDistortionMappers.end()) {
4508 continue;
4509 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004510
4511 if (!captureRequest->mDistortionCorrectionUpdated) {
4512 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4513 &(it->metadata));
4514 if (res != OK) {
4515 SET_ERR("RequestThread: Unable to correct capture requests "
4516 "for lens distortion for request %d: %s (%d)",
4517 halRequest->frame_number, strerror(-res), res);
4518 return INVALID_OPERATION;
4519 }
4520 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004521 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004522 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004523
4524 for (it = captureRequest->mSettingsList.begin();
4525 it != captureRequest->mSettingsList.end(); it++) {
4526 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4527 parent->mZoomRatioMappers.end()) {
4528 continue;
4529 }
4530
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004531 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004532 cameraIdsWithZoom.insert(it->cameraId);
4533 }
4534
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004535 if (!captureRequest->mZoomRatioUpdated) {
4536 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4537 &(it->metadata));
4538 if (res != OK) {
4539 SET_ERR("RequestThread: Unable to correct capture requests "
4540 "for zoom ratio for request %d: %s (%d)",
4541 halRequest->frame_number, strerror(-res), res);
4542 return INVALID_OPERATION;
4543 }
4544 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004545 }
4546 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004547 if (captureRequest->mRotateAndCropAuto &&
4548 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004549 for (it = captureRequest->mSettingsList.begin();
4550 it != captureRequest->mSettingsList.end(); it++) {
4551 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4552 if (mapper != parent->mRotateAndCropMappers.end()) {
4553 res = mapper->second.updateCaptureRequest(&(it->metadata));
4554 if (res != OK) {
4555 SET_ERR("RequestThread: Unable to correct capture requests "
4556 "for rotate-and-crop for request %d: %s (%d)",
4557 halRequest->frame_number, strerror(-res), res);
4558 return INVALID_OPERATION;
4559 }
4560 }
4561 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004562 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004563 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004564 }
4565 }
4566
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004567 /**
4568 * The request should be presorted so accesses in HAL
4569 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4570 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004571 captureRequest->mSettingsList.begin()->metadata.sort();
4572 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004573 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004574 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004575 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4576
4577 IF_ALOGV() {
4578 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4579 find_camera_metadata_ro_entry(
4580 halRequest->settings,
4581 ANDROID_CONTROL_AF_TRIGGER,
4582 &e
4583 );
4584 if (e.count > 0) {
4585 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4586 __FUNCTION__,
4587 halRequest->frame_number,
4588 e.data.u8[0]);
4589 }
4590 }
4591 } else {
4592 // leave request.settings NULL to indicate 'reuse latest given'
4593 ALOGVV("%s: Request settings are REUSED",
4594 __FUNCTION__);
4595 }
4596
Emilian Peevaebbe412018-01-15 13:53:24 +00004597 if (captureRequest->mSettingsList.size() > 1) {
4598 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4599 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004600 if (newRequest) {
4601 halRequest->physcam_settings =
4602 new const camera_metadata* [halRequest->num_physcam_settings];
4603 } else {
4604 halRequest->physcam_settings = nullptr;
4605 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004606 auto it = ++captureRequest->mSettingsList.begin();
4607 size_t i = 0;
4608 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4609 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004610 if (newRequest) {
4611 it->metadata.sort();
4612 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4613 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004614 }
4615 }
4616
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004617 uint32_t totalNumBuffers = 0;
4618
4619 // Fill in buffers
4620 if (captureRequest->mInputStream != NULL) {
4621 halRequest->input_buffer = &captureRequest->mInputBuffer;
4622 totalNumBuffers += 1;
4623 } else {
4624 halRequest->input_buffer = NULL;
4625 }
4626
4627 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4628 captureRequest->mOutputStreams.size());
4629 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004630 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004631
4632 sp<Camera3Device> parent = mParent.promote();
4633 if (parent == NULL) {
4634 // Should not happen, and nowhere to send errors to, so just log it
4635 CLOGE("RequestThread: Parent is gone");
4636 return INVALID_OPERATION;
4637 }
4638 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4639
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004640 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004641 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004642 sp<Camera3OutputStreamInterface> outputStream =
4643 captureRequest->mOutputStreams.editItemAt(j);
4644 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004645
4646 // Prepare video buffers for high speed recording on the first video request.
4647 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4648 // Only try to prepare video stream on the first video request.
4649 mPrepareVideoStream = false;
4650
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004651 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4652 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004653 while (res == NOT_ENOUGH_DATA) {
4654 res = outputStream->prepareNextBuffer();
4655 }
4656 if (res != OK) {
4657 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4658 __FUNCTION__, strerror(-res), res);
4659 outputStream->cancelPrepare();
4660 }
4661 }
4662
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004663 std::vector<size_t> uniqueSurfaceIds;
4664 res = outputStream->getUniqueSurfaceIds(
4665 captureRequest->mOutputSurfaces[streamId],
4666 &uniqueSurfaceIds);
4667 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4668 if (res != OK && res != INVALID_OPERATION) {
4669 ALOGE("%s: failed to query stream %d unique surface IDs",
4670 __FUNCTION__, streamId);
4671 return res;
4672 }
4673 if (res == OK) {
4674 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4675 }
4676
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004677 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004678 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004679 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004680 return TIMED_OUT;
4681 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004682 // HAL will request buffer through requestStreamBuffer API
4683 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4684 buffer.stream = outputStream->asHalStream();
4685 buffer.buffer = nullptr;
4686 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4687 buffer.acquire_fence = -1;
4688 buffer.release_fence = -1;
4689 } else {
4690 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4691 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004692 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004693 if (res != OK) {
4694 // Can't get output buffer from gralloc queue - this could be due to
4695 // abandoned queue or other consumer misbehavior, so not a fatal
4696 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004697 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004698 " %s (%d)", strerror(-res), res);
4699
4700 return TIMED_OUT;
4701 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004702 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004703
4704 {
4705 sp<Camera3Device> parent = mParent.promote();
4706 if (parent != nullptr) {
4707 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4708 for (const auto& settings : captureRequest->mSettingsList) {
4709 if ((streamCameraId.isEmpty() &&
4710 parent->getId() == settings.cameraId.c_str()) ||
4711 streamCameraId == settings.cameraId.c_str()) {
4712 outputStream->fireBufferRequestForFrameNumber(
4713 captureRequest->mResultExtras.frameNumber,
4714 settings.metadata);
4715 }
4716 }
4717 }
4718 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004719
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004720 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4721
4722 if (!physicalCameraId.isEmpty()) {
4723 // Physical stream isn't supported for input request.
4724 if (halRequest->input_buffer) {
4725 CLOGE("Physical stream is not supported for input request");
4726 return INVALID_OPERATION;
4727 }
4728 requestedPhysicalCameras.insert(physicalCameraId);
4729 }
4730 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004731 }
4732 totalNumBuffers += halRequest->num_output_buffers;
4733
4734 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004735 // If this request list is for constrained high speed recording (not
4736 // preview), and the current request is not the last one in the batch,
4737 // do not send callback to the app.
4738 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004739 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004740 hasCallback = false;
4741 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004742 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004743 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004744 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4745 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4746 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4747 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4748 isStillCapture = true;
4749 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4750 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004751
4752 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4753 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4754 isZslCapture = true;
4755 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004756 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004757 res = parent->registerInFlight(halRequest->frame_number,
4758 totalNumBuffers, captureRequest->mResultExtras,
4759 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004760 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004761 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004762 requestedPhysicalCameras, isStillCapture, isZslCapture,
4763 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004764 (mUseHalBufManager) ? uniqueSurfaceIdMap :
Shuzhen Wang316781a2020-08-18 18:11:01 -07004765 SurfaceMap{}, captureRequest->mRequestTimeNs);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004766 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4767 ", burstId = %" PRId32 ".",
4768 __FUNCTION__,
4769 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4770 captureRequest->mResultExtras.burstId);
4771 if (res != OK) {
4772 SET_ERR("RequestThread: Unable to register new in-flight request:"
4773 " %s (%d)", strerror(-res), res);
4774 return INVALID_OPERATION;
4775 }
4776 }
4777
4778 return OK;
4779}
4780
Igor Murashkin1e479c02013-09-06 16:55:14 -07004781CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004782 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004783 Mutex::Autolock al(mLatestRequestMutex);
4784
4785 ALOGV("RequestThread::%s", __FUNCTION__);
4786
4787 return mLatestRequest;
4788}
4789
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004790bool Camera3Device::RequestThread::isStreamPending(
4791 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004792 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004793 Mutex::Autolock l(mRequestLock);
4794
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004795 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004796 if (!nextRequest.submitted) {
4797 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4798 if (stream == s) return true;
4799 }
4800 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004801 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004802 }
4803
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004804 for (const auto& request : mRequestQueue) {
4805 for (const auto& s : request->mOutputStreams) {
4806 if (stream == s) return true;
4807 }
4808 if (stream == request->mInputStream) return true;
4809 }
4810
4811 for (const auto& request : mRepeatingRequests) {
4812 for (const auto& s : request->mOutputStreams) {
4813 if (stream == s) return true;
4814 }
4815 if (stream == request->mInputStream) return true;
4816 }
4817
4818 return false;
4819}
Jianing Weicb0652e2014-03-12 18:29:36 -07004820
Emilian Peev40ead602017-09-26 15:46:36 +01004821bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4822 ATRACE_CALL();
4823 Mutex::Autolock l(mRequestLock);
4824
4825 for (const auto& nextRequest : mNextRequests) {
4826 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4827 if (s.first == streamId) {
4828 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4829 if (it != s.second.end()) {
4830 return true;
4831 }
4832 }
4833 }
4834 }
4835
4836 for (const auto& request : mRequestQueue) {
4837 for (const auto& s : request->mOutputSurfaces) {
4838 if (s.first == streamId) {
4839 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4840 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004841 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004842 }
4843 }
4844 }
4845 }
4846
4847 for (const auto& request : mRepeatingRequests) {
4848 for (const auto& s : request->mOutputSurfaces) {
4849 if (s.first == streamId) {
4850 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4851 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004852 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004853 }
4854 }
4855 }
4856 }
4857
4858 return false;
4859}
4860
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004861void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4862 if (!mUseHalBufManager) {
4863 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4864 return;
4865 }
4866
4867 Mutex::Autolock pl(mPauseLock);
4868 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004869 mInterface->signalPipelineDrain(streamIds);
4870 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004871 }
4872 // If request thread is still busy, wait until paused then notify HAL
4873 mNotifyPipelineDrain = true;
4874 mStreamIdsToBeDrained = streamIds;
4875}
4876
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004877void Camera3Device::RequestThread::resetPipelineDrain() {
4878 Mutex::Autolock pl(mPauseLock);
4879 mNotifyPipelineDrain = false;
4880 mStreamIdsToBeDrained.clear();
4881}
4882
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004883void Camera3Device::RequestThread::clearPreviousRequest() {
4884 Mutex::Autolock l(mRequestLock);
4885 mPrevRequest.clear();
4886}
4887
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004888status_t Camera3Device::RequestThread::switchToOffline(
4889 const std::vector<int32_t>& streamsToKeep,
4890 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004891 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4892 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004893 Mutex::Autolock l(mRequestLock);
4894 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4895
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004896 // Wait until request thread is fully stopped
4897 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4898
4899 // We could also check for mRepeatingRequests.empty(), but the API interface
4900 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4901 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004902 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4903 while (!queueEmpty) {
4904 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4905 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004906 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004907 return res;
4908 } else if (res != OK) {
4909 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4910 __FUNCTION__, strerror(-res), res);
4911 return res;
4912 }
4913 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4914 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004915
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004916 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004917 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004918}
4919
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004920status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4921 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4922 ATRACE_CALL();
4923 Mutex::Autolock l(mTriggerMutex);
4924 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4925 return BAD_VALUE;
4926 }
4927 mRotateAndCropOverride = rotateAndCropValue;
4928 return OK;
4929}
4930
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004931nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004932 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004933 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004934 return mExpectedInflightDuration > kMinInflightDuration ?
4935 mExpectedInflightDuration : kMinInflightDuration;
4936}
4937
Emilian Peevaebbe412018-01-15 13:53:24 +00004938void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4939 camera3_capture_request_t *halRequest) {
4940 if ((request == nullptr) || (halRequest == nullptr)) {
4941 ALOGE("%s: Invalid request!", __FUNCTION__);
4942 return;
4943 }
4944
4945 if (halRequest->num_physcam_settings > 0) {
4946 if (halRequest->physcam_id != nullptr) {
4947 delete [] halRequest->physcam_id;
4948 halRequest->physcam_id = nullptr;
4949 }
4950 if (halRequest->physcam_settings != nullptr) {
4951 auto it = ++(request->mSettingsList.begin());
4952 size_t i = 0;
4953 for (; it != request->mSettingsList.end(); it++, i++) {
4954 it->metadata.unlock(halRequest->physcam_settings[i]);
4955 }
4956 delete [] halRequest->physcam_settings;
4957 halRequest->physcam_settings = nullptr;
4958 }
4959 }
4960}
4961
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004962void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4963 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004964 return;
4965 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004966
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004967 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004968 // Skip the ones that have been submitted successfully.
4969 if (nextRequest.submitted) {
4970 continue;
4971 }
4972
4973 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4974 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4975 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4976
4977 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004978 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004979 }
4980
Emilian Peevaebbe412018-01-15 13:53:24 +00004981 cleanupPhysicalSettings(captureRequest, halRequest);
4982
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004983 if (captureRequest->mInputStream != NULL) {
4984 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4985 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4986 }
4987
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004988 // No output buffer can be returned when using HAL buffer manager
4989 if (!mUseHalBufManager) {
4990 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4991 //Buffers that failed processing could still have
4992 //valid acquire fence.
4993 int acquireFence = (*outputBuffers)[i].acquire_fence;
4994 if (0 <= acquireFence) {
4995 close(acquireFence);
4996 outputBuffers->editItemAt(i).acquire_fence = -1;
4997 }
4998 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4999 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5000 /*timestampIncreasing*/true, std::vector<size_t> (),
5001 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005002 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005003 }
5004
5005 if (sendRequestError) {
5006 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005007 sp<NotificationListener> listener = mListener.promote();
5008 if (listener != NULL) {
5009 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005010 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005011 captureRequest->mResultExtras);
5012 }
5013 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005014
5015 // Remove yet-to-be submitted inflight request from inflightMap
5016 {
5017 sp<Camera3Device> parent = mParent.promote();
5018 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005019 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005020 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5021 if (idx >= 0) {
5022 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5023 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5024 parent->removeInFlightMapEntryLocked(idx);
5025 }
5026 }
5027 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005028 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005029
5030 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005031 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032}
5033
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005034void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005035 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005036 // Optimized a bit for the simple steady-state case (single repeating
5037 // request), to avoid putting that request in the queue temporarily.
5038 Mutex::Autolock l(mRequestLock);
5039
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005040 assert(mNextRequests.empty());
5041
5042 NextRequest nextRequest;
5043 nextRequest.captureRequest = waitForNextRequestLocked();
5044 if (nextRequest.captureRequest == nullptr) {
5045 return;
5046 }
5047
5048 nextRequest.halRequest = camera3_capture_request_t();
5049 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005050 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005051
5052 // Wait for additional requests
5053 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5054
5055 for (size_t i = 1; i < batchSize; i++) {
5056 NextRequest additionalRequest;
5057 additionalRequest.captureRequest = waitForNextRequestLocked();
5058 if (additionalRequest.captureRequest == nullptr) {
5059 break;
5060 }
5061
5062 additionalRequest.halRequest = camera3_capture_request_t();
5063 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005064 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005065 }
5066
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005067 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005068 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005069 mNextRequests.size(), batchSize);
5070 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 }
5072
5073 return;
5074}
5075
5076sp<Camera3Device::CaptureRequest>
5077 Camera3Device::RequestThread::waitForNextRequestLocked() {
5078 status_t res;
5079 sp<CaptureRequest> nextRequest;
5080
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005081 while (mRequestQueue.empty()) {
5082 if (!mRepeatingRequests.empty()) {
5083 // Always atomically enqueue all requests in a repeating request
5084 // list. Guarantees a complete in-sequence set of captures to
5085 // application.
5086 const RequestList &requests = mRepeatingRequests;
Shuzhen Wang316781a2020-08-18 18:11:01 -07005087 if (mFirstRepeating) {
5088 mFirstRepeating = false;
5089 } else {
5090 for (auto& request : requests) {
5091 // For repeating requests, override timestamp request using
5092 // the time a request is inserted into the request queue,
5093 // because the original repeating request will have an old
5094 // fixed timestamp.
5095 request->mRequestTimeNs = systemTime();
5096 }
5097 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005098 RequestList::const_iterator firstRequest =
5099 requests.begin();
5100 nextRequest = *firstRequest;
5101 mRequestQueue.insert(mRequestQueue.end(),
5102 ++firstRequest,
5103 requests.end());
5104 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005105
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005106 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005107
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005108 break;
5109 }
5110
5111 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5112
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005113 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5114 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005115 Mutex::Autolock pl(mPauseLock);
5116 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005117 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005118 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005119 if (mNotifyPipelineDrain) {
5120 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5121 mNotifyPipelineDrain = false;
5122 mStreamIdsToBeDrained.clear();
5123 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005124 // Let the tracker know
5125 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5126 if (statusTracker != 0) {
5127 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5128 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005129 sp<Camera3Device> parent = mParent.promote();
5130 if (parent != nullptr) {
5131 parent->mRequestBufferSM.onRequestThreadPaused();
5132 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005133 }
5134 // Stop waiting for now and let thread management happen
5135 return NULL;
5136 }
5137 }
5138
5139 if (nextRequest == NULL) {
5140 // Don't have a repeating request already in hand, so queue
5141 // must have an entry now.
5142 RequestList::iterator firstRequest =
5143 mRequestQueue.begin();
5144 nextRequest = *firstRequest;
5145 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005146 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5147 sp<NotificationListener> listener = mListener.promote();
5148 if (listener != NULL) {
5149 listener->notifyRequestQueueEmpty();
5150 }
5151 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005152 }
5153
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005154 // In case we've been unpaused by setPaused clearing mDoPause, need to
5155 // update internal pause state (capture/setRepeatingRequest unpause
5156 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005157 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005158 if (mPaused) {
5159 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5160 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5161 if (statusTracker != 0) {
5162 statusTracker->markComponentActive(mStatusId);
5163 }
5164 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005165 mPaused = false;
5166
5167 // Check if we've reconfigured since last time, and reset the preview
5168 // request if so. Can't use 'NULL request == repeat' across configure calls.
5169 if (mReconfigured) {
5170 mPrevRequest.clear();
5171 mReconfigured = false;
5172 }
5173
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005174 if (nextRequest != NULL) {
5175 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005176 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5177 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005178
5179 // Since RequestThread::clear() removes buffers from the input stream,
5180 // get the right buffer here before unlocking mRequestLock
5181 if (nextRequest->mInputStream != NULL) {
5182 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5183 if (res != OK) {
5184 // Can't get input buffer from gralloc queue - this could be due to
5185 // disconnected queue or other producer misbehavior, so not a fatal
5186 // error
5187 ALOGE("%s: Can't get input buffer, skipping request:"
5188 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005189
5190 sp<NotificationListener> listener = mListener.promote();
5191 if (listener != NULL) {
5192 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005193 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005194 nextRequest->mResultExtras);
5195 }
5196 return NULL;
5197 }
5198 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005199 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005200
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005201 return nextRequest;
5202}
5203
5204bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005205 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005206 status_t res;
5207 Mutex::Autolock l(mPauseLock);
5208 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005209 if (mPaused == false) {
5210 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005211 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005212 if (mNotifyPipelineDrain) {
5213 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5214 mNotifyPipelineDrain = false;
5215 mStreamIdsToBeDrained.clear();
5216 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005217 // Let the tracker know
5218 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5219 if (statusTracker != 0) {
5220 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5221 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005222 sp<Camera3Device> parent = mParent.promote();
5223 if (parent != nullptr) {
5224 parent->mRequestBufferSM.onRequestThreadPaused();
5225 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005226 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005227
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005228 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005229 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005230 return true;
5231 }
5232 }
5233 // We don't set mPaused to false here, because waitForNextRequest needs
5234 // to further manage the paused state in case of starvation.
5235 return false;
5236}
5237
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005238void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005239 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005240 // With work to do, mark thread as unpaused.
5241 // If paused by request (setPaused), don't resume, to avoid
5242 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005243 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005244 Mutex::Autolock p(mPauseLock);
5245 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005246 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5247 if (mPaused) {
5248 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5249 if (statusTracker != 0) {
5250 statusTracker->markComponentActive(mStatusId);
5251 }
5252 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005253 mPaused = false;
5254 }
5255}
5256
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005257void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5258 sp<Camera3Device> parent = mParent.promote();
5259 if (parent != NULL) {
5260 va_list args;
5261 va_start(args, fmt);
5262
5263 parent->setErrorStateV(fmt, args);
5264
5265 va_end(args);
5266 }
5267}
5268
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005269status_t Camera3Device::RequestThread::insertTriggers(
5270 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005271 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005272 Mutex::Autolock al(mTriggerMutex);
5273
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005274 sp<Camera3Device> parent = mParent.promote();
5275 if (parent == NULL) {
5276 CLOGE("RequestThread: Parent is gone");
5277 return DEAD_OBJECT;
5278 }
5279
Emilian Peevaebbe412018-01-15 13:53:24 +00005280 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005281 size_t count = mTriggerMap.size();
5282
5283 for (size_t i = 0; i < count; ++i) {
5284 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005285 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005286
5287 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5288 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5289 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005290 if (isAeTrigger) {
5291 request->mResultExtras.precaptureTriggerId = triggerId;
5292 mCurrentPreCaptureTriggerId = triggerId;
5293 } else {
5294 request->mResultExtras.afTriggerId = triggerId;
5295 mCurrentAfTriggerId = triggerId;
5296 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005297 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005298 }
5299
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005300 camera_metadata_entry entry = metadata.find(tag);
5301
5302 if (entry.count > 0) {
5303 /**
5304 * Already has an entry for this trigger in the request.
5305 * Rewrite it with our requested trigger value.
5306 */
5307 RequestTrigger oldTrigger = trigger;
5308
5309 oldTrigger.entryValue = entry.data.u8[0];
5310
5311 mTriggerReplacedMap.add(tag, oldTrigger);
5312 } else {
5313 /**
5314 * More typical, no trigger entry, so we just add it
5315 */
5316 mTriggerRemovedMap.add(tag, trigger);
5317 }
5318
5319 status_t res;
5320
5321 switch (trigger.getTagType()) {
5322 case TYPE_BYTE: {
5323 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5324 res = metadata.update(tag,
5325 &entryValue,
5326 /*count*/1);
5327 break;
5328 }
5329 case TYPE_INT32:
5330 res = metadata.update(tag,
5331 &trigger.entryValue,
5332 /*count*/1);
5333 break;
5334 default:
5335 ALOGE("%s: Type not supported: 0x%x",
5336 __FUNCTION__,
5337 trigger.getTagType());
5338 return INVALID_OPERATION;
5339 }
5340
5341 if (res != OK) {
5342 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5343 ", value %d", __FUNCTION__, trigger.getTagName(),
5344 trigger.entryValue);
5345 return res;
5346 }
5347
5348 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5349 trigger.getTagName(),
5350 trigger.entryValue);
5351 }
5352
5353 mTriggerMap.clear();
5354
5355 return count;
5356}
5357
5358status_t Camera3Device::RequestThread::removeTriggers(
5359 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005360 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005361 Mutex::Autolock al(mTriggerMutex);
5362
Emilian Peevaebbe412018-01-15 13:53:24 +00005363 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005364
5365 /**
5366 * Replace all old entries with their old values.
5367 */
5368 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5369 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5370
5371 status_t res;
5372
5373 uint32_t tag = trigger.metadataTag;
5374 switch (trigger.getTagType()) {
5375 case TYPE_BYTE: {
5376 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5377 res = metadata.update(tag,
5378 &entryValue,
5379 /*count*/1);
5380 break;
5381 }
5382 case TYPE_INT32:
5383 res = metadata.update(tag,
5384 &trigger.entryValue,
5385 /*count*/1);
5386 break;
5387 default:
5388 ALOGE("%s: Type not supported: 0x%x",
5389 __FUNCTION__,
5390 trigger.getTagType());
5391 return INVALID_OPERATION;
5392 }
5393
5394 if (res != OK) {
5395 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5396 ", trigger value %d", __FUNCTION__,
5397 trigger.getTagName(), trigger.entryValue);
5398 return res;
5399 }
5400 }
5401 mTriggerReplacedMap.clear();
5402
5403 /**
5404 * Remove all new entries.
5405 */
5406 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5407 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5408 status_t res = metadata.erase(trigger.metadataTag);
5409
5410 if (res != OK) {
5411 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5412 ", trigger value %d", __FUNCTION__,
5413 trigger.getTagName(), trigger.entryValue);
5414 return res;
5415 }
5416 }
5417 mTriggerRemovedMap.clear();
5418
5419 return OK;
5420}
5421
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005422status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005423 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005424 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005425 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005426 status_t res;
5427
Emilian Peevaebbe412018-01-15 13:53:24 +00005428 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005429
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005430 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005431 // exists
5432 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5433 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5434 if (afTrigger.count > 0 &&
5435 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5436 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005437 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005438 if (res != OK) return res;
5439 }
5440
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005441 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005442 // if none already exists
5443 camera_metadata_entry pcTrigger =
5444 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5445 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5446 if (pcTrigger.count > 0 &&
5447 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5448 pcId.count == 0) {
5449 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005450 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005451 if (res != OK) return res;
5452 }
5453
5454 return OK;
5455}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005456
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005457bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5458 const sp<CaptureRequest> &request) {
5459 ATRACE_CALL();
5460
5461 if (request->mRotateAndCropAuto) {
5462 Mutex::Autolock l(mTriggerMutex);
5463 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5464
5465 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5466 if (rotateAndCropEntry.count > 0) {
5467 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5468 return false;
5469 } else {
5470 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5471 return true;
5472 }
5473 } else {
5474 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5475 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5476 &rotateAndCrop_u8, 1);
5477 return true;
5478 }
5479 }
5480 return false;
5481}
5482
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005483/**
5484 * PreparerThread inner class methods
5485 */
5486
5487Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005488 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005489 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005490}
5491
5492Camera3Device::PreparerThread::~PreparerThread() {
5493 Thread::requestExitAndWait();
5494 if (mCurrentStream != nullptr) {
5495 mCurrentStream->cancelPrepare();
5496 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5497 mCurrentStream.clear();
5498 }
5499 clear();
5500}
5501
Ruben Brunkc78ac262015-08-13 17:58:46 -07005502status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005503 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005504 status_t res;
5505
5506 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005507 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005508
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005509 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005510 if (res == OK) {
5511 // No preparation needed, fire listener right off
5512 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005513 if (listener != NULL) {
5514 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005515 }
5516 return OK;
5517 } else if (res != NOT_ENOUGH_DATA) {
5518 return res;
5519 }
5520
5521 // Need to prepare, start up thread if necessary
5522 if (!mActive) {
5523 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5524 // isn't running
5525 Thread::requestExitAndWait();
5526 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5527 if (res != OK) {
5528 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005529 if (listener != NULL) {
5530 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005531 }
5532 return res;
5533 }
5534 mCancelNow = false;
5535 mActive = true;
5536 ALOGV("%s: Preparer stream started", __FUNCTION__);
5537 }
5538
5539 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005540 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005541 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5542
5543 return OK;
5544}
5545
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005546void Camera3Device::PreparerThread::pause() {
5547 ATRACE_CALL();
5548
5549 Mutex::Autolock l(mLock);
5550
5551 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5552 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5553 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5554 int currentMaxCount = mCurrentMaxCount;
5555 mPendingStreams.clear();
5556 mCancelNow = true;
5557 while (mActive) {
5558 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5559 if (res == TIMED_OUT) {
5560 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5561 return;
5562 } else if (res != OK) {
5563 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5564 return;
5565 }
5566 }
5567
5568 //Check whether the prepare thread was able to complete the current
5569 //stream. In case work is still pending emplace it along with the rest
5570 //of the streams in the pending list.
5571 if (currentStream != nullptr) {
5572 if (!mCurrentPrepareComplete) {
5573 pendingStreams.emplace(currentMaxCount, currentStream);
5574 }
5575 }
5576
5577 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5578 for (const auto& it : mPendingStreams) {
5579 it.second->cancelPrepare();
5580 }
5581}
5582
5583status_t Camera3Device::PreparerThread::resume() {
5584 ATRACE_CALL();
5585 status_t res;
5586
5587 Mutex::Autolock l(mLock);
5588 sp<NotificationListener> listener = mListener.promote();
5589
5590 if (mActive) {
5591 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5592 return NO_INIT;
5593 }
5594
5595 auto it = mPendingStreams.begin();
5596 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005597 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005598 if (res == OK) {
5599 if (listener != NULL) {
5600 listener->notifyPrepared(it->second->getId());
5601 }
5602 it = mPendingStreams.erase(it);
5603 } else if (res != NOT_ENOUGH_DATA) {
5604 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5605 res, strerror(-res));
5606 it = mPendingStreams.erase(it);
5607 } else {
5608 it++;
5609 }
5610 }
5611
5612 if (mPendingStreams.empty()) {
5613 return OK;
5614 }
5615
5616 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5617 if (res != OK) {
5618 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5619 __FUNCTION__, res, strerror(-res));
5620 return res;
5621 }
5622 mCancelNow = false;
5623 mActive = true;
5624 ALOGV("%s: Preparer stream started", __FUNCTION__);
5625
5626 return OK;
5627}
5628
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005629status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005630 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005631 Mutex::Autolock l(mLock);
5632
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005633 for (const auto& it : mPendingStreams) {
5634 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005635 }
5636 mPendingStreams.clear();
5637 mCancelNow = true;
5638
5639 return OK;
5640}
5641
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005642void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005643 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005644 Mutex::Autolock l(mLock);
5645 mListener = listener;
5646}
5647
5648bool Camera3Device::PreparerThread::threadLoop() {
5649 status_t res;
5650 {
5651 Mutex::Autolock l(mLock);
5652 if (mCurrentStream == nullptr) {
5653 // End thread if done with work
5654 if (mPendingStreams.empty()) {
5655 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5656 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5657 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5658 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005659 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005660 return false;
5661 }
5662
5663 // Get next stream to prepare
5664 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005665 mCurrentStream = it->second;
5666 mCurrentMaxCount = it->first;
5667 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005668 mPendingStreams.erase(it);
5669 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5670 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5671 } else if (mCancelNow) {
5672 mCurrentStream->cancelPrepare();
5673 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5674 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5675 mCurrentStream.clear();
5676 mCancelNow = false;
5677 return true;
5678 }
5679 }
5680
5681 res = mCurrentStream->prepareNextBuffer();
5682 if (res == NOT_ENOUGH_DATA) return true;
5683 if (res != OK) {
5684 // Something bad happened; try to recover by cancelling prepare and
5685 // signalling listener anyway
5686 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5687 mCurrentStream->getId(), res, strerror(-res));
5688 mCurrentStream->cancelPrepare();
5689 }
5690
5691 // This stream has finished, notify listener
5692 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005693 sp<NotificationListener> listener = mListener.promote();
5694 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005695 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5696 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005697 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005698 }
5699
5700 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5701 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005702 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005703
5704 return true;
5705}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005706
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005707status_t Camera3Device::RequestBufferStateMachine::initialize(
5708 sp<camera3::StatusTracker> statusTracker) {
5709 if (statusTracker == nullptr) {
5710 ALOGE("%s: statusTracker is null", __FUNCTION__);
5711 return BAD_VALUE;
5712 }
5713
5714 std::lock_guard<std::mutex> lock(mLock);
5715 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005716 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005717 return OK;
5718}
5719
5720bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5721 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005722 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005723 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005724 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005725 return true;
5726 }
5727 return false;
5728}
5729
5730void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5731 std::lock_guard<std::mutex> lock(mLock);
5732 if (!mRequestBufferOngoing) {
5733 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5734 return;
5735 }
5736 mRequestBufferOngoing = false;
5737 if (mStatus == RB_STATUS_PENDING_STOP) {
5738 checkSwitchToStopLocked();
5739 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005740 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005741}
5742
5743void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5744 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005745 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005746 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005747 return;
5748}
5749
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005750void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005751 std::lock_guard<std::mutex> lock(mLock);
5752 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005753 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5754 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005755 mInflightMapEmpty = false;
5756 if (mStatus == RB_STATUS_STOPPED) {
5757 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005758 }
5759 return;
5760}
5761
5762void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5763 std::lock_guard<std::mutex> lock(mLock);
5764 mRequestThreadPaused = true;
5765 if (mStatus == RB_STATUS_PENDING_STOP) {
5766 checkSwitchToStopLocked();
5767 }
5768 return;
5769}
5770
5771void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5772 std::lock_guard<std::mutex> lock(mLock);
5773 mInflightMapEmpty = true;
5774 if (mStatus == RB_STATUS_PENDING_STOP) {
5775 checkSwitchToStopLocked();
5776 }
5777 return;
5778}
5779
5780void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5781 std::lock_guard<std::mutex> lock(mLock);
5782 if (!checkSwitchToStopLocked()) {
5783 mStatus = RB_STATUS_PENDING_STOP;
5784 }
5785 return;
5786}
5787
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005788bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5789 std::lock_guard<std::mutex> lock(mLock);
5790 if (mRequestBufferOngoing) {
5791 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5792 __FUNCTION__);
5793 return false;
5794 }
5795 mSwitchedToOffline = true;
5796 mInflightMapEmpty = true;
5797 mRequestThreadPaused = true;
5798 mStatus = RB_STATUS_STOPPED;
5799 return true;
5800}
5801
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005802void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5803 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5804 if (statusTracker != nullptr) {
5805 if (active) {
5806 statusTracker->markComponentActive(mRequestBufferStatusId);
5807 } else {
5808 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5809 }
5810 }
5811}
5812
5813bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5814 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5815 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005816 return true;
5817 }
5818 return false;
5819}
5820
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005821bool Camera3Device::startRequestBuffer() {
5822 return mRequestBufferSM.startRequestBuffer();
5823}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005824
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005825void Camera3Device::endRequestBuffer() {
5826 mRequestBufferSM.endRequestBuffer();
5827}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005828
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005829nsecs_t Camera3Device::getWaitDuration() {
5830 return kBaseGetBufferWait + getExpectedInFlightDuration();
5831}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005832
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005833void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5834 mInterface->getInflightBufferKeys(out);
5835}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005836
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005837void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5838 mInterface->getInflightRequestBufferKeys(out);
5839}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005840
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005841std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5842 std::vector<sp<Camera3StreamInterface>> ret;
5843 bool hasInputStream = mInputStream != nullptr;
5844 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5845 if (hasInputStream) {
5846 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005847 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005848 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5849 ret.push_back(mOutputStreams[i]);
5850 }
5851 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5852 ret.push_back(mDeletedStreams[i]);
5853 }
5854 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005855}
5856
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005857status_t Camera3Device::switchToOffline(
5858 const std::vector<int32_t>& streamsToKeep,
5859 /*out*/ sp<CameraOfflineSessionBase>* session) {
5860 ATRACE_CALL();
5861 if (session == nullptr) {
5862 ALOGE("%s: session must not be null", __FUNCTION__);
5863 return BAD_VALUE;
5864 }
5865
5866 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005867
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005868 bool hasInputStream = mInputStream != nullptr;
5869 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5870 bool inputStreamSupportsOffline = hasInputStream ?
5871 mInputStream->getOfflineProcessingSupport() : false;
5872 auto outputStreamIds = mOutputStreams.getStreamIds();
5873 auto streamIds = outputStreamIds;
5874 if (hasInputStream) {
5875 streamIds.push_back(mInputStream->getId());
5876 }
5877
5878 // Check all streams in streamsToKeep supports offline mode
5879 for (auto id : streamsToKeep) {
5880 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5881 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5882 return BAD_VALUE;
5883 } else if (id == inputStreamId) {
5884 if (!inputStreamSupportsOffline) {
5885 ALOGE("%s: input stream %d cannot be switched to offline",
5886 __FUNCTION__, id);
5887 return BAD_VALUE;
5888 }
5889 } else {
5890 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5891 if (!stream->getOfflineProcessingSupport()) {
5892 ALOGE("%s: output stream %d cannot be switched to offline",
5893 __FUNCTION__, id);
5894 return BAD_VALUE;
5895 }
5896 }
5897 }
5898
5899 // TODO: block surface sharing and surface group streams until we can support them
5900
5901 // Stop repeating request, wait until all remaining requests are submitted, then call into
5902 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005903 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5904 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005905 camera3::BufferRecords bufferRecords;
5906 status_t ret = mRequestThread->switchToOffline(
5907 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005908
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005909 if (ret != OK) {
5910 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5911 return ret;
5912 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005913
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005914 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5915 if (!succ) {
5916 SET_ERR("HAL must not be calling requestStreamBuffers call");
5917 // TODO: block ALL callbacks from HAL till app configured new streams?
5918 return UNKNOWN_ERROR;
5919 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005920
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005921 // Verify offlineSessionInfo
5922 std::vector<int32_t> offlineStreamIds;
5923 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5924 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5925 // verify stream IDs
5926 int32_t id = offlineStream.id;
5927 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5928 SET_ERR("stream ID %d not found!", id);
5929 return UNKNOWN_ERROR;
5930 }
5931
5932 // When not using HAL buf manager, only allow streams requested by app to be preserved
5933 if (!mUseHalBufManager) {
5934 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5935 SET_ERR("stream ID %d must not be switched to offline!", id);
5936 return UNKNOWN_ERROR;
5937 }
5938 }
5939
5940 offlineStreamIds.push_back(id);
5941 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5942 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5943 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5944 // Verify number of outstanding buffers
5945 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5946 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5947 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5948 return UNKNOWN_ERROR;
5949 }
5950 }
5951
5952 // Verify all streams to be deleted don't have any outstanding buffers
5953 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5954 inputStreamId) == offlineStreamIds.end()) {
5955 if (mInputStream->hasOutstandingBuffers()) {
5956 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5957 inputStreamId, mInputStream->getOutstandingBuffersCount());
5958 return UNKNOWN_ERROR;
5959 }
5960 }
5961
5962 for (const auto& outStreamId : outputStreamIds) {
5963 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5964 outStreamId) == offlineStreamIds.end()) {
5965 auto outStream = mOutputStreams.get(outStreamId);
5966 if (outStream->hasOutstandingBuffers()) {
5967 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5968 outStreamId, outStream->getOutstandingBuffersCount());
5969 return UNKNOWN_ERROR;
5970 }
5971 }
5972 }
5973
5974 InFlightRequestMap offlineReqs;
5975 // Verify inflight requests and their pending buffers
5976 {
5977 std::lock_guard<std::mutex> l(mInFlightLock);
5978 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5979 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5980 if (idx == NAME_NOT_FOUND) {
5981 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5982 return UNKNOWN_ERROR;
5983 }
5984
5985 const auto& inflightReq = mInFlightMap.valueAt(idx);
5986 // TODO: check specific stream IDs
5987 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5988 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5989 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5990 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5991 return UNKNOWN_ERROR;
5992 }
5993 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5994 }
5995 }
5996
5997 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005998 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005999 camera3::StreamSet offlineStreamSet;
6000 sp<camera3::Camera3Stream> inputStream;
6001 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6002 int32_t id = offlineStream.id;
6003 if (mInputStream != nullptr && id == mInputStream->getId()) {
6004 inputStream = mInputStream;
6005 } else {
6006 offlineStreamSet.add(id, mOutputStreams.get(id));
6007 }
6008 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006009
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006010 // TODO: check if we need to lock before copying states
6011 // though technically no other thread should be talking to Camera3Device at this point
6012 Camera3OfflineStates offlineStates(
6013 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07006014 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
6015 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
6016 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
6017 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
6018 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
6019 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
6020 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006021
6022 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
6023 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
6024
6025 // Delete all streams that has been transferred to offline session
6026 Mutex::Autolock l(mLock);
6027 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
6028 int32_t id = offlineStream.id;
6029 if (mInputStream != nullptr && id == mInputStream->getId()) {
6030 mInputStream.clear();
6031 } else {
6032 mOutputStreams.remove(id);
6033 }
6034 }
6035
6036 // disconnect all other streams and switch to UNCONFIGURED state
6037 if (mInputStream != nullptr) {
6038 ret = mInputStream->disconnect();
6039 if (ret != OK) {
6040 SET_ERR_L("disconnect input stream failed!");
6041 return UNKNOWN_ERROR;
6042 }
6043 }
6044
6045 for (auto streamId : mOutputStreams.getStreamIds()) {
6046 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
6047 ret = stream->disconnect();
6048 if (ret != OK) {
6049 SET_ERR_L("disconnect output stream %d failed!", streamId);
6050 return UNKNOWN_ERROR;
6051 }
6052 }
6053
6054 mInputStream.clear();
6055 mOutputStreams.clear();
6056 mNeedConfig = true;
6057 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
6058 mOperatingMode = NO_MODE;
6059 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07006060 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006061
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006062 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08006063 // TO be done by CameraDeviceClient/Camera3OfflineSession
6064 // register the offline client to camera service
6065 // Setup result passthing threads etc
6066 // Initialize offline session so HAL can start sending callback to it (result Fmq)
6067 // TODO: check how many onIdle callback will be sent
6068 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006069}
6070
Emilian Peevcc0b7952020-01-07 13:54:47 -08006071void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
6072 ATRACE_CALL();
6073
6074 if (offlineStreamIds == nullptr) {
6075 return;
6076 }
6077
6078 Mutex::Autolock il(mInterfaceLock);
6079
6080 auto streamIds = mOutputStreams.getStreamIds();
6081 bool hasInputStream = mInputStream != nullptr;
6082 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6083 offlineStreamIds->push_back(mInputStream->getId());
6084 }
6085
6086 for (const auto & streamId : streamIds) {
6087 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6088 // Streams that use the camera buffer manager are currently not supported in
6089 // offline mode
6090 if (stream->getOfflineProcessingSupport() &&
6091 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6092 offlineStreamIds->push_back(streamId);
6093 }
6094 }
6095}
6096
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006097status_t Camera3Device::setRotateAndCropAutoBehavior(
6098 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6099 ATRACE_CALL();
6100 Mutex::Autolock il(mInterfaceLock);
6101 Mutex::Autolock l(mLock);
6102 if (mRequestThread == nullptr) {
6103 return INVALID_OPERATION;
6104 }
6105 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6106}
6107
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006108}; // namespace android